I want to bubble sort an array that could be any number with values from the user. But the first method is not working. I really want to use JOptionPanes, but I don't even know if that is the problem. It compiles correctly, but doesn't run properly. This is my current code:
import javax.swing.*;
import java.io.*;
import java.util.*;
public class Gates_sortingBubble{
public static void main(String[] args)throws IOException{
String amountS;
amountS = JOptionPane.showInputDialog(null, "How many numbers would you like to sort?",
"Sorting Arrays", JOptionPane.INFORMATION_MESSAGE);
int amount = Integer.parseInt(amountS);
JOptionPane.showMessageDialog (null, "Please enter " + amount + " numbers you wish to sort.",
"Sorting Arrays", JOptionPane.INFORMATION_MESSAGE);
int[] numbers = new int [amount];
for(int i = 1; i <= amount; i++){
String tempS = JOptionPane.showInputDialog("Number " + i + ": ");
int temp = Integer.parseInt(tempS);
numbers[i] = temp;
}
sort(numbers);
}
public static void sort(int[] tosort){
int[] original = tosort.clone();
int j;
boolean flag = true; //set flag to true to begin first pass
int temp; //to hold the variable
while(flag){
flag= false; //set flag to false awaiting a possible swap
for( j=0; j < tosort.length -1; j++ ){
if ( tosort[ j ] < tosort[j+1] ){
temp = tosort[ j ]; //swap the array elements
tosort[ j ] = tosort[ j+1 ];
tosort[ j+1 ] = temp;
flag = true; //shows a swap occurred
}
}
}
print(tosort, original);
}
public static void print(int[] sorted, int[] unsorted){
JOptionPane.showMessageDialog (null, "Your original five numbers are: "
+ Arrays.toString(unsorted) + ". \nYour new five numbers are: "
+ Arrays.toString(sorted) + ".", "Sorted Arrays", JOptionPane.INFORMATION_MESSAGE);
}
}
Your for
loop in the main method goes from 1 to amount
, but the array indexes of the numbers array range from 0 to amount-1
. So in that loop, change:
numbers[i] = temp;
To:
numbers[i - 1] = temp;
And it will work.