Insertion Sort in C
Here you will learn algorithm of insertion sort and get the program code 0f Insertion Sort in C without function using c language.
What is Insertion Sort?
Insertion sort is a sorting algorithm that places an unsorted element into its proper position within a sorted array. It loops through the array, beginning with the second element and comparing each element to the one before it. If the element being compared is smaller than the one before it, they are swapped. This process is repeated again until an array is sorted in an order.
Algorithm of Insertion Sort in C
Insertion sort(ar[],n)
for j->2 to n
do key <-ar[j]
i<-j-1
while i>=0 and ar[i]>key
do ar[i+1]<-ar[i]
i<-i+1
ar[i+1]<-key
end
Insertion Sort Flowchart (DFD)
Example of Insertion Sort in C without function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | #include<stdio.h> void main() { int ar[7]; int key; int i,j; int temp; printf("\nEnter 7 elements for sorting with Insertion sort\n"); for(i=0;i<7;i++) { scanf("%d",&ar[i]); } for(j=1;j<7;j++) { key=ar[j]; i=j-1; while((i>=0)&&(ar[i]>=key)) { temp=ar[i+1]; ar[i+1]=ar[i]; ar[i]=temp; i=i-1; } ar[i+1]=key; } printf("\nElements after sorting with Insertion sort \n"); for(i=0;i<7;i++) { printf("%d \n",ar[i]); } // return 0; } |
Output
Check out our DAA Lab Manual and Programs