Insertion Sort
Insertion Sort
Insertion Sort
Sorting is a process of rearranged a sequences of elements so as to put them in some
logical order. Sorting is an effective approach for addressing other problem. Scientists
often use sorting algorithm as start point to solve other problem. It plays a major rule in
commercial data processing and in modern scientific computing.
Process of insertion sort
The array is searched sequentially and unsorted items are moved and inserted into
sorted sub-list in the same array. This algorithm is not suitable for large data sets as its
average and worst case complexity are O (n2).
In computer implementation, we have to make a space to insert current item by moving
smallest items one position to the left (or large to the right) before inserting current item
into a freed position as shown in Figure 1.
0 1 2 3 4 5
10 18 25 30 23 17 10 18 23 25 30 30
J=0 I=1 Key = 18 J=4 I=5 Key = 17
10 18 25 30 23 17 10 18 23 25 25 30
J=1 I=2 Key = 25 J=4 I=5 Key = 17
10 18 25 30 23 17 10 18 23 23 25 30
J=2 I=3 Key = 30 J=2 I=5 Key = 17
10 18 25 30 30 17 10 18 18 23 25 30
J=3 I=4 Key = 23 J=0 I=5 Key = 17
10 18 25 25 30 17 10 17 18 23 25 30
J=2 I=4 Key = 23 J=0 I=5 Key = 17
10 18 23 25 30 17
J=2 I=4 Key = 23
Figure 1: Process of insertion sort
Pseudo code
Algorithm InsertionSort (data, n)
for (int i = 1; i < n; i++) {
int key = data[i ];
int j = i - 1;
// Compare key with each element on the left of it until an element smaller than
// it is found.
// For descending order, change key<array[j] to key>array[j].
while (key < data[j] && j >= 0) {
data[j + 1] = data[j];
--j; }
data[j + 1] = key;
}
cout <<"\n Array size is "<< size <<"\n "<<"Sorted array in ascending order:\n";
for (int i = 0; i < size; i++) {
cout <<"\n"<<" "<< data[i] << " ";
} cout << endl;
}