【发布时间】:2016-02-01 11:15:15
【问题描述】:
我正在尝试按升序对数组进行排序。由于某种原因,它只执行一次 for 循环。为什么直到所有东西都排序后才继续?
这是一个作业,所以我不能使用现有的排序方法。我应该自己写方法。
public class Sudoku {
public static void main(String[] args) {
int[] a = { 1, 4, 3, 5, 2 };
System.out.println(Arrays.toString(sortArray(a)));
}
public static int[] sortArray(int[] nonSortedArray) {
int[] sortedArray = new int[nonSortedArray.length];
int temp;
for (int i = 0; i < nonSortedArray.length - 1; i++) {
if (nonSortedArray[i] > nonSortedArray[i + 1]) {
temp = nonSortedArray[i];
nonSortedArray[i] = nonSortedArray[i + 1];
nonSortedArray[i + 1] = temp;
sortedArray = nonSortedArray;
}
}
return sortedArray;
}
}
【问题讨论】:
-
"由于某种原因,它只执行一次 for 循环。" -- 您在程序中的哪个位置告诉它执行多次?该程序只会执行您告诉它执行的操作。