所以这是我的问题。我输入10个数字,数组应该对它进行排序,以便最大数字首先出现,然后是下一个数字,依此类推。 当我得到输出时,它显示一些奇怪的迹象。有人可以帮忙吗?
谢谢。 //丹尼尔
package revising_selection_sort;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Revising_selection_sort {
public static double[] selectionSort(double[] list) {
for (int i = 0; i < list.length; i++) {
double currentMax = list[i];
int currentMaxIndex = i;
for (int j = i + 1; j < list.length; j++) {
if (currentMax < list[j]) {
currentMax = list[j];
currentMaxIndex = j;
}
}
if (currentMaxIndex != i) {
list[currentMaxIndex] = list[i];
list[i] = currentMax;
}
}
return list;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double arr[] = new double[10];
int num1;
int num2;
int num3;
int num4;
int num5;
int num6;
int num7;
int num8;
int num9;
int num10;
String nr1 = JOptionPane.showInputDialog("Indtast 1. hele tal");
num1 = Integer.parseInt(nr1);
String nr2 = JOptionPane.showInputDialog("Indtast 2. hele tal");
num2 = Integer.parseInt(nr2);
String nr3 = JOptionPane.showInputDialog("Indtast 3. hele tal");
num3 = Integer.parseInt(nr3);
String nr4 = JOptionPane.showInputDialog("Indtast 4. hele tal");
num4 = Integer.parseInt(nr4);
String nr5 = JOptionPane.showInputDialog("Indtast 5. hele tal");
num5 = Integer.parseInt(nr5);
String nr6 = JOptionPane.showInputDialog("Indtast 6. hele tal");
num6 = Integer.parseInt(nr6);
String nr7 = JOptionPane.showInputDialog("Indtast 7. hele tal");
num7 = Integer.parseInt(nr7);
String nr8 = JOptionPane.showInputDialog("Indtast 8. hele tal");
num8 = Integer.parseInt(nr8);
String nr9 = JOptionPane.showInputDialog("Indtast 9. hele tal");
num9 = Integer.parseInt(nr9);
String nr10 = JOptionPane.showInputDialog("Indtast 10. hele tal");
num10 = Integer.parseInt(nr10);
arr[0] = num1;
arr[1] = num2;
arr[2] = num3;
arr[3] = num4;
arr[4] = num5;
arr[5] = num6;
arr[6] = num7;
arr[7] = num8;
arr[8] = num9;
arr[9] = num10;
String result;
result = String.format("The sorted array is: " + selectionSort(arr));
JOptionPane.showMessageDialog(null, result);
}
}
答案 0 :(得分:0)
要查看正确的排序数组输出,您应该执行以下操作:
调用selectionSort(arr)后 Arrays.toString(arr)
或直接
Arrays.toString(selectionSort(arr))
所以最后看起来像这样:
result = String.format("The sorted array is: "
+ Arrays.toString(selectionSort(arr)));
此外,在修改selectionSort(double[] list)
数组本身时,您无需从list
方法返回任何内容。