I was doing an insertion sort using Java. For example, if I have an integer array {8,7,6,5,4,3,2,1},
This will give me the result which is wrong: 7,6,5,4,3,2,1,8 picture
public static int[] insertionSort(int[] list) {
int[] insertionList = list.clone();
for(int i = 1; i < insertionList.length; i++) {
int temp = insertionList[i];
int j = i - 1;
while(j >= 0 && insertionList[j] > insertionList[i]) {
insertionList[j + 1] = insertionList[j];
j--;
}
insertionList[j + 1] = temp;
}
return insertionList;
}
And this will give me the result which I wanted: 1,2,3,4,5,6,7,8 picture
public static int[] insertionSort(int[] list) {
int[] insertionList = list.clone();
for(int i = 1; i < insertionList.length; i++) {
int temp = insertionList[i];
int j = i - 1;
while(j >= 0 && insertionList[j] > temp) {
insertionList[j + 1] = insertionList[j];
j--;
}
insertionList[j + 1] = temp;
}
return insertionList;
}
Just wondering what different between insertionList[i]
and temp
. I wrote two println
statements to test these, but they also show the same number.
Thanks!!!!!