I know what insertion sort is but I don't understand the code. And I searched it is all explanation about the sort but not the code. It will be easier for me if you answer the question step by step with examples! Thanks! Use this code for example. I put my questions in comment to make it clearer.
void insertionSort(int arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i-1;
while (j >= 0 && arr[j] > key)
{
arr[j+1] = arr[j];
/* if arr[j] > key, at here arr[j+1] has the number in arr[j] which is i
* or key right? But now only arr[j+1] changed. There are only two same
* numbers which is the bigger number, arr[j] is not changed to the smaller
* number which arr[j+1] was.
*/
j = j-1;
}
arr[j+1] = key;
/* so at here arr[j+1] now has the value of key which is arr[i], so the
* sorted arr[j+1] ended up unchanged? I know this step is supposed to
* change key to use it to compare numbers after.
*/
}
}