Koko
Koko
Below is the pseudocode for insertion sort for a zero-based array (as in C):
1. for j ←1 to length(A)-1
2. key ← A[ j ]
3. > A[ j ] is added in the sorted sequence A[1, .. j-1]
4. i ← j - 1
5. while i >= 0 and A [ i ] > key
6. A[ i +1 ] ← A[ i ]
7. i ← i -1
8. A [i +1] ← key
#include <stdio.h>
28
29
30 /* Sort an array of integers */
31 void insertion_sort(int a[], int length)
32 {
33 int i;
34 for (i=0; i < length; i++)
35 {
36 /* Insert a[i] into the sorted sublist */
37 int j, v = a[i];
38
39 for (j = i - 1; j >= 0; j--)
40 {
41 if (a[j] <= v) break;
42 a[j + 1] = a[j];
43 }
44 a[j + 1] = v;
45
46 }
47 }
48
49 void checkThatArrayIsSorted (int array[], int length)
50 {
51 int i;
52 for (i = 1; i < length; i+=1)
53 {
54 if (array[i-1] > array[i])
55 {
56 printf("The array is not in sorted order at position %d\n",
i-1);
57 }
58 }
59 }
60
61
62 int main(void)
63 {
64 unsigned int i;
65 int a[] = {5,1,9,3,2};
66 insertion_sort(a, sizeof(a)/sizeof(*a));
67 /* Print out a */
68 for(i=0; i<sizeof(a)/sizeof(*a); i++)
69 {
70 printf("%d\n", a[i]);
71 }
72
73 checkThatArrayIsSorted(a, sizeof(a)/sizeof(*a));
74
75 return 0;
76 }
77