C program to arrange a list of integers in ascending order using Insertion sort

INSERTION SORT

  1. Start with an empty left hand [sorted array] and the cards face down on the table [unsorted array].
  2. Then remove one card [key] at a time from the table [unsorted array], and insert it into the correct position in the left hand [sorted array].
  3. To find the correct position for the card, we compare it with each of the cards already in the hand, from right to left.
				
					#include<stdio.h>
void inst_sort(int[], int);
void main() 
{
int num[20],count,n;
printf("\n how many elements\n");
scanf("%d",&n);
printf("\nEnter the elements to sort\n");
for(count=0;count<n;count++)
scanf("%d",&num[count]);
inst_sort(num,n); /*function call for insertion sort*/

printf("\n\n elements after sorting:\n");
for(count=0;count<n;count++)
printf("%d\n",num[count]);
}
void inst_sort(int num[], int n) { /* function definition for insertion sort*/

int i,j,k;
for(j=1;j<n;j++) {

k=num[j];
for(i=j-1;i>=0&&k<num[i];i--)
num[i+1]=num[i];
num[i+1]=k;
}
}
				
			

Leave a Reply