Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands.Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list. Each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there. It repeats until no input elements remain.
#include<stdio.h>
#include<conio.h>
void insertionsort(int b[20],int);
void main()
{ int arr[20],n,i;
clrscr();
printf("\n\n program to sort array using insertion sort");
printf("\n enter no. of elements : ");
scanf("%d",&n);
printf("\n enter array now : \n");
for(i=0;i<n;i++)
{ printf(" enter a[%d] = ",i);
scanf("%d",&arr[i]);
}
printf("sorted list in ascending order = \n");
insertionsort(&arr,n);
for(i=0;i<n;i++)
{ printf("%d ",arr[i]);
}
getch();
}
void insertionsort(int b[20],int n)
{ int i,j,temp;
for(i=1;i<n;i++)
{ temp = b[i];
j = i-1;
while(temp<b[j] && j>=0)
{ b[j+1] = b[j];
j = j-1;
}
b[j+1] = temp;
}
}
#include<stdio.h>
#include<conio.h>
void insertionsort(int b[20],int);
void main()
{ int arr[20],n,i;
clrscr();
printf("\n\n program to sort array using insertion sort");
printf("\n enter no. of elements : ");
scanf("%d",&n);
printf("\n enter array now : \n");
for(i=0;i<n;i++)
{ printf(" enter a[%d] = ",i);
scanf("%d",&arr[i]);
}
printf("sorted list in ascending order = \n");
insertionsort(&arr,n);
for(i=0;i<n;i++)
{ printf("%d ",arr[i]);
}
getch();
}
void insertionsort(int b[20],int n)
{ int i,j,temp;
for(i=1;i<n;i++)
{ temp = b[i];
j = i-1;
while(temp<b[j] && j>=0)
{ b[j+1] = b[j];
j = j-1;
}
b[j+1] = temp;
}
}

No comments:
Post a Comment
Guys if you think something is wrong or should be edit than please do comment.