I am doing on java.
package com.example.demo;
public class Sortinnnn {
public static void main(String[] args) {
int[] resultArray = insertionSort(new int[]{2, 9, 5, 4, 8, 1, 6});
for (int i = 0; i < resultArray.length; i++) {
System.out.println(resultArray[i]);
}
}
public static int[] insertionSort(int[] list) {
for (int i = 1; i < list.length; i++) {
int currentElement = list[i];
int k;
for (k = i - 1; k >= 0 && list[k] > currentElement; k--) {
list[k + 1] = list[k];
}
list[k + 1] = currentElement;
}
return list;
}
}
There is a certain step list[k+1]=list[k]. Book claims it is shifting. But here is what I do not get it.
i starts from 2nd element.
k starts from one element before i. And it goes towards -ve axis, towards zero.
list[k+1]=list[k]
assume a situation
2,1,3,4,5
Since 1<2, we need to shift.
list[1]=list[0]
2 goes to list[1] location.
Now, later after the end of kth loop, we put ith element i.e. the currentElement variable value. But book is putting again list[k+1]=currentElement.
The last value of k will be always be 0. So, list[1]=currentElement? How does this even work?