Insertion Sort:- This technique works like deck of cards, to arrange some cards we pick a card and insert it in its desired position.
We will solve the problem by taking an element as temp and will insert it into its desired position in the array.
Code:
#include<stdio.h> void main() { int x[7]={25,15,30,9,99,20,26}; int i,j,temp,n=7; printf("\nList of elements"); for(i=1;i<n;i++) printf("\n%d",x[i]); for(i=0;i<n;i++) { temp=x[i]; for(j=i-1; temp<x[j]&&j>=0 ; j--) { x[j+1]=x[j]; } x[j+1]=temp; } printf("\nAfter Sorting"); for(i=0;i<n;i++) printf("\n%d",x[i]); getch(); }
Output:
Explanation:
Step 1:
Here i=1
temp=x[1] i.e. 15
This temp value is taken to be inserted in its exact position in left most sorted array i.e x[0] ,containing only single which is sorted in itself.
Step 2:
Here i=2
temp=x[2] i.e. 30
This temp value is taken to be inserted in its exact position in left most sorted array i.e x[0] to x[1].
Step 3:
Here i=3
temp=x[3] i.e. 9
This temp value is taken to be inserted in its exact position in left most sorted array i.e x[0] to x[2].
Step 4:
Here i=4
temp=x[4] i.e. 99
This temp value is taken to be inserted in its exact position in left most sorted array i.e x[0] to x[3].
Step 5:
Here i=5
temp=x[5] i.e. 20
This temp value is taken to be inserted in its exact position in left most sorted array i.e x[0] to x[4].
Step 6:
Here i=6
temp=x[6] i.e. 26
This temp value is taken to be inserted in its exact position in left most sorted array i.e x[0] to x[5].
Finally,The list will be like this.


No comments:
Post a Comment