The insertion sort algorithm works as follows.
Although it is easier to explain the idea of the insertion sort in two consecutive steps - first, find the right position, and second, insert the current element into the right position moving all elements starting from this position down, it is much more efficient to implement these two steps together in one loop. Lets compare two functions:
void isort(int data[], int N) { int i, j, k, s; for(i=1;i<N;i++){ s = data[i]; // find the right spot for the element s for(j=i-1;j>=0 && data[j]>s;j--); // now j+1 is the index of the position where s should be // move all elements [j+1, i-1] down for(k=i;k>j+1;k--) data[k] = data[k-1]; // put s in the right spot if( j < i-1 ) data[j+1] = s; } } |
void isort(int data[], int N) { int i, j, s; for(i=1;i<N;i++){ s = data[i]; // start moving all elements greater than s down for(j=i-1; j>=0 && data[j]>s; j--) data[j+1] = data[j]; // put s in the right spot if( j < i-1 ) data[j+1] = s; } } |
| N | One loop | Two loops | % slower |
|---|---|---|---|
| 20,000 | 172 | 282 | 64% |
| 40,000 | 656 | 1,062 | 62% |
| 80,000 | 2,669 | 4,191 | 57% |
| 160,000 | 11,734 | 18,737 | 59% |