How to understand the key value change in insertion sort?

I know what insertion sort is, but I don't understand the code. And I searched, this is all the explanation, but not the code. It will be easier for me if you answer the question step by step with examples! Thank you Use this code, for example. I put my questions in a 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.
  */
   }
}
+4
source share
2 answers

Your questions are a bit unclear, so let me try to explain what happens in the code before trying to answer them.

  • An external loop variable irepresents the start of unsorted data in an array. It will be increased from 1to nusingfor loop
  • key , while loop
  • j . 0 while loop

, ,

if arr [j] > , arr [j + 1] arr [j]

?

. arr[j+1] == key, while,

arr [j + 1].

. arr[j+1], , j = j -1, , , is shifted right

, , arr [j] , arr [j + 1].

arr[j] , , arr[j] . , j = 10 - . a[10] while, , j = 9 a[10] = a[9]

arr [j + 1] , arr [i]

, arr[i] while , , key

arr [j + 1] ? , , .

,

0

, , , i- . , .

A [] = {7,4,5,2} enter image description here

, 1 : key = arr [i] = arr 1= 4 , 4.And j = i-1, 0. , (j >= 0 && arr [j] > key) , j -, , j- ( arr [0] = 7) , , arr [j + 1] = arr [j] arr [j + 1], 1, arr [0], 7. j 1, j -1. - while , . , , , arr [j + 1], arr [0], "", 4. , , ( i) , ( j) , . - (arr [j] > key) , arr [j + 1] = , j + 1 i. .

+3

Source: https://habr.com/ru/post/1659206/


All Articles