並べ替えのスキームは、実際には選択並べ替えです。
Sort 1. 12 89 18 4 6
Sort 2. 4 12 89 18 6
Sort 3. 4 6 12 89 18
Sort 4. 4 6 12 18 89
最小の数値を見つけて、リストの先頭に配置します。通常の挿入ソートでは、次のようになります。
Sort 1. 12 89 18 4 6
Sort 2. 12 18 89 4 6
Sort 3. 4 12 18 89 6
Sort 4. 4 6 12 18 89
つまり、18 が 89 未満であるが 12 より大きいことがわかり、12 と 89 の間に 18 が挿入され、最初の反復が実行されます。その後、プロセスを繰り返します。
これが私のコードです:
void insertion(int *x,int n){ // int *x - array, n- array's length
int i,j,k,temp,elem; // i,j,k - counters, elem - to store the element at pos x[i]
for(i=0;i<n;i++){
elem=x[i]; // store the element
j=i;
while(j>0 && x[j-1]>elem){ // the magic(actual sorting)
x[j]=x[j-1];
j--;
}
x[j]=elem; // swap the elements
if(i>=1){ // here begins printing every sorting step, i>=1 because first time j is not greater than 0 so it just run through the loop first time
printf("sort %d. ",i); // printing the step
for(k=0;k<n;k++) // loop through array
printf("%d ",x[k]); // display the elements already sorted
printf("\n"); // when the array is displayed, insert a \n so that the next display will be on a new line
}
}
}