Insertion Sort
Sorting : -
Input: A Sequence of n numbers (a1,a2 …….an).
Output: A permutation (recording) <a’1,a’2,….a’n> of the input sequence such that a’1 <=a’2<=,….<=a’n.
Insertion Sort
Insertion sort is an efficient sorting algorithm for sorting a small number of elements. Insertion sort works the way people sort a hand of playing card. We start with empty hand and card face down on the table. We remove one card at a time from the table and insert it into the correct position in the left hand. For correct position of card we compare it with each of the card already in the hand in left.
algorthms-cormen |
Algorithm
INSERT-SORT(A)
- for j <-- 2 to length[A]
- do key <-- A[j]
- Insert A[j] into the sorted sequence A[1.... j-1]
- i <-- 1
- while i > 0 and A[j] > key
- do A[i+1] <-- A[i]
- i <-- i-1
- A[i+1] <-- key
Ex: A = (5,2,4,6,1,3) the index j indicate the current card being inserted into the hand. At the beginning of each iteration of teh outer loop, which is indexed by j,the subarra consisting of elements A[1...j-1] constitute the currently stored hand, and elements A[j+1..n] correspond to the pile of card stil on table. A[1...j-1] elements oroginally at position 1 through j-1, but now in sorted order.
Ex: A[6,5,3,1,8,7,2,4]
wikipedia |
Time Complexity: O(n*2)
Auxiliary Space: O(1)
Boundary Cases: Insertion sort takes maximum time to sort if elements are sorted in reverse order. And it takes minimum time (Order of n) when elements are already sorted.
Sorting In Place: Yes
Stable: Yes
C PROGRAM FOR INSERTION SORT ALGORITHM
#include <stdio.h>
int main()
{
int n, array[1000], i, j, t;
printf("Enter number of elements: \n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (i = 0; i < n; i++)
scanf("%d", &array[i]);
for (i = 1 ; i <= n - 1; i++)
{
j = i;
while ( j > 0 && array[j-1] > array[j]) {
t = array[j];
array[j] = array[j-1];
array[j-1] = t;
j--;
}
}
printf("Sorted list in ascending order:\n");
for (i = 0; i <= n - 1; i++)
{
printf("%d ", array[i]);
}
return 0;
}
OUTPUT
Enter number of elements:
8
Enter 8 integers
67 -2 0 12 87 45 5 1
Sorted list in ascending order:
-2 0 1 5 12 45 67 87
Comments
Post a Comment