我正在尝试按升序对数组进行排序.由于某种原因,它仅执行一次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;
}
}
解决方法:
public static int[] sortArray(int[] nonSortedArray) {
int[] sortedArray = new int[nonSortedArray.length];
int temp;
for (int j = 0; j < nonSortedArray.length - 1; j++) {// added this for loop, think about logic why do we have to add this to make it work
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;
}
输出:[1、2、3、4、5]
要么
//making use of j
public static int[] sortArray(int[] nonSortedArray){
int[] sortedArray = new int[nonSortedArray.length];
int temp;
for (int i = 0; i <= nonSortedArray.length; i++)
{
for (int j = i+1; j < nonSortedArray.length; j++)
{
if (nonSortedArray[i] > nonSortedArray[j])
{
temp = nonSortedArray[i];
nonSortedArray[i] = nonSortedArray[j];
nonSortedArray[j] = temp;
sortedArray = nonSortedArray;
}
}
}
return sortedArray;
}
标签:arrays,java,sorting
来源: https://codeday.me/bug/20191027/1946729.html