I'm trying to sort an array in ascending order. For some reason it only performs the for loop once. Why doesn't it keep going until everything is sorted?
It's for an assignment so I am not allowed to use existing sort methods. I'm supposed to write the method myself.
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;
}
}
See Question&Answers more detail:os