Thursday, 15 March 2018

Insertion Sort Program (Ascending Order)

In C language we use various method for the sorting of elements but today we gonna work on Insertion sort that allows you to sort your elements in ascending order. The complexity in insertion sort is better than merge sort.
So, here the code for the same, hope so you will got the point.

/*Pre- Processors used throughout the program*/
#include<conio.h>
#include<stdlib.h>
#include<stdio.h>

#define MAX 25 /*Length for MAX*/

void main()
{
int num, a[MAX], temp ,i ,j; /*Declaration of variables*/
clrscr(); /*Clears the output screen*/
printf("Enter no. of elements for your list:- ");
scanf("%d",&num);
for(i=0;i<num;i++)
{
scanf("%d",&a[i]);
}
for(i=1;i<num;i++)
{
temp=a[i];
j=i-1;
while(temp<a[j]&&j>=0)
{
a[j+1]=a[j];
--j;
}
a[j+1]=temp;
}
printf("\nSorted List:- \n");
for(i=0;i<num;i++)
{
printf("%d\n",a[i]);

}

getch();
}


No comments:

Post a Comment