Insertion sort is a to some extent an interesting algorithm with an expensive runtime characteristic having O(n2). This algorithm can be best thought of as a sorting scheme which can be compared to that of sorting a hand of playing cards, i.e., you take one card and then look at the rest with the intent of building up an ordered set of cards in your hand.
Algorithm for Insertion Sort
- algorithm Insertion_sort(list)
- Pre: list 6= fi
- Post: list has been sorted into values of ascending order
- unsorted <- 1
- while unsorted < list.Count
- hold <- list[unsorted]
- i à unsorted - 1
- while i >= 0 and hold < list[i]
- list[i + 1] <- list[i]
- i <- i - 1
- end while
- list[i + 1] <- hold
- unsorted <- unsorted + 1
- end while
- return list
- end Insertion_sort
Example:
#include <iostream>
#include <conio.h>
int main()
{
int a[16], i, j, k, tmp;
cout << "enter the number of elements\n";
for (i = 0; i < 6; i++) { cin >> a[i];
}
for (i = 1; i < 6; i++) { for (j = i; j >= 1; j--) {
if (a[j] < a[j - 1]) {
tmp = a[j];
a[j] = a[j - 1];
a[j - 1] = tmp;
}
else
break;
}
}
cout << "sorted array\n" << endl;
for (k = 0; k < 6; k++) {
cout << a[k] << "\t";
}
}
Output: