I am trying to understand Insertionsort. I have heard that I can improve it with a sentinel.
This is my code without a sentinel:
public static int[] insertionSort(int[] sortieren) {
int temp;
for (int i = 1; i < sortieren.length; i++) {
temp = sortieren[i];
int j = i;
while (j > 0 && sortieren[j - 1] > temp) {
sortieren[j] = sortieren[j - 1];
j--;
}
sortieren[j] = temp;
}
return sortieren;
}
I am trying currently to understand in which case I can get an ArrayIndexOutOfBounds Exception. Can you help me to understand why there is a Sentinel necessary to improve that code, and where i have to enter it? I would say that I have to put a Integer.MIN_Value on the left edge of the array but Im not sure because I don't see a case where it runs out of the array.
I would appreciate it if you would help me to understand the usage of sentinels in Insertionsort.
With Sentinel...
public void insertionSort(int[] array) {
int temp;
int arraySentinel[] = new int[array.length+1];
for(int i = 0; i < array.length; i++){
arraySentinel[i+1] = array[i];
}
arraySentinel[0] = Integer.MIN_VALUE;
for (int i = 1; i < arraySentinel.length; i++) {
temp = arraySentinel[i];
int j = i;
/**
* Stabil weil sortieren[j-1] > temp!
* Wäre nicht stabil wenn >=!
*/
while (arraySentinel[j - 1] > temp) {
arraySentinel[j] = arraySentinel[j - 1];
j--;
}
arraySentinel[j] = temp;
}
for (int i = 1; i < arraySentinel.length; i++){
array[i-1] = arraySentinel[i];
}
}