我想冒泡排序一个数组,该数组可以是来自用户的值的任何数字。但第一种方法不起作用。我真的想使用JOptionPanes,但我甚至不知道这是不是问题。它编译正确,但运行不正常。这是我目前的代码:
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);
}
}
答案 0 :(得分:0)
main方法中的for
循环从1变为amount
,但数字数组的数组索引范围从0到amount-1
。所以在那个循环中,改变:
numbers[i] = temp;
要:
numbers[i - 1] = temp;
它会起作用。