Insertion sort algorithm picks elements one by one and places it to the right position where it belongs in the sorted list of elements. In the following C program we have implemented the same logic.
Before going through the program, lets see the steps of insertion sort with the help of an example.
Input elements: 89 17 8 12 0
Step 1: 89 17 8 12 0 (the bold elements are sorted list and non-bold unsorted list)
Step 2: 17 89 8 12 0 (each element will be removed from unsorted list and placed at the right position in the sorted list)
Step 3: 8 17 89 12 0
Step 4: 8 12 17 89 0
Step 5: 0 8 12 17 89
C Program – Insertion Sort implementation
#include<stdio.h> int main(){ /* Here i & j for loop counters, temp for swapping, * count for total number of elements, number[] to * store the input numbers in array. You can increase * or decrease the size of number array as per requirement */ int i, j, count, temp, number[25]; printf("How many numbers u are going to enter?: "); scanf("%d",&count); printf("Enter %d elements: ", count); // This loop would store the input numbers in array for(i=0;i<count;i++) scanf("%d",&number[i]); // Implementation of insertion sort algorithm for(i=1;i<count;i++){ temp=number[i]; j=i-1; while((temp<number[j])&&(j>=0)){ number[j+1]=number[j]; j=j-1; } number[j+1]=temp; } printf("Order of Sorted elements: "); for(i=0;i<count;i++) printf(" %d",number[i]); return 0; }
Output:
As you can observe in the output that we have entered 6 integer numbers in a random order and the above C program sorted them in ascending order by using the logic of insertion sort algorithm.
Leave a Reply