I'm trying to implement insertion sort in Java. I think something isn't quite right with my code.
public int[] sort(int[] unsorted) {
int i, j, v;
for (i = 1; i < unsorted.length - 1; i++) {
v = unsorted[i];
j = i;
while (unsorted[j-1] > v && j >= 1) {
unsorted[j] = unsorted[j -1];
j--;
}
unsorted[j] = v;
}
return unsorted;
}
I get an IndexOutOfBoundsException for my while loop ([j-1]). But how can I rewrite the code so it actually works?
whilestatement condition whenjhas just been decremented down to zero? You need to check first if the value ofjis "safe" before accessingunsorted[j-1].unsorted. Returningunsortedfrom a method calledsortis misleading, at least. Justsource, or similar.