0% found this document useful (0 votes)
24 views2 pages

Koko

This document provides pseudocode and C code to implement insertion sort. The pseudocode outlines the steps of the algorithm, which iterates through the array, inserts each element into its sorted position, and shifts other elements over as needed. The C code implements insertion sort on an integer array, sorts the array, prints it, and checks that it is fully sorted.

Uploaded by

mitaaaaloooo
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views2 pages

Koko

This document provides pseudocode and C code to implement insertion sort. The pseudocode outlines the steps of the algorithm, which iterates through the array, inserts each element into its sorted position, and shifts other elements over as needed. The C code implements insertion sort on an integer array, sorts the array, prints it, and checks that it is fully sorted.

Uploaded by

mitaaaaloooo
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 2

insertionSort(array A)

{ This procedure sorts in ascending order. }


begin
for i := 1 to length[A]-1 do
begin
value := A[i];
j := i - 1;
done := false;
repeat
{ To sort in descending order simply reverse
the operator i.e. A[j] < value }
if A[j] > value then
begin
A[j + 1] := A[j];
j := j - 1;
if j < 0 then
done := true;
end
else
done := true;
until done;
A[j + 1] := value;
end;
end;

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

You might also like