Professional Documents
Culture Documents
Lesson 5
INSERTION SORT
Insertion Sort
Module III
13
Figure 4 shows the fifth pass in detail. At this point in the algorithm, a
sorted sublist of five items consisting of 17, 26, 54, 77, and 93 exists. We want
to insert 31 back into the already sorted items. The first comparison against
93 causes 93 to be shifted to the right. 77 and 54 are also shifted. When the
item 26 is encountered, the shifting process stops and 31 is placed in the open
position. Now we have a sorted sublist of six items.
Algorithm
Sample Implementation
Module III
14
Module III
15
Lesson 6
COUNTING SORT
Counting Sort
Algorithm:
1. Find out the maximum (max) element from the given array.
Module III
16
5. Find the index of each element of the original array in the count array.
This gives the cumulative count. Place the element at the index
calculated.
6. After placing each element at its correct position, decrease its count
by one.
Pseudocode:
Time Complexity
There are mainly four loops. (Finding the greatest value can be done outside
the function.)
for loop time of counting
1st O(max)
2nd O(size)
3rd O(max)
th
4 O(size)
Module III
17
Module III