it’s a insertion sort algorithm
I understand forwarding the greatest no to next index but cant understand when it moves forward how its previous position (index) is being taken by the smaller number that was just compare e.g in list [2,1] 2 moves to next index by list[j+1]=list[j]; but how 1 moves backward or to previous index
//unsorted array
int[] list = new int[] { 5, 2, 4, 6, 1 };
// the key element being sorted
int key;
//
//start looping starting from the second element
for (int i = 1; i < list.Length; i++)
{
key = list[i];//store the key
int j = i - 1;//get the previous index
//
//loop until you meet a smaller number or 0
while (j >= 0 && list[j] > key)
{
//move the greater number forward
list[j + 1] = list[j];
// Decrementing
j--;
}
//set the key in the proper index
list[j + 1] = key;
}
That is done in the last line inside the loop. After moving one or more (or even zero) items forward, the current value is put in the correct position.
For example, if you have sorted the array up to the last item, and it looks like this:
The value 1 is copied into the
keyvariable, then items are copied forward one by one:Now the value from the
keyvariable is placed where the last item was copied from:The theory behind the insert sort is to take items from one array and insert into a new array. The implementation that you are using is only using a single array, and you can think of it as divided into a sorted part and an unsorted part. The sorted part starts out with the size zero:
when the array is sorted, items are picked from the unsorted part and are inserted at the right place in the sorted part. The sorted part grows and the unsorted part shrinks, until the unsorted part is empty: