C Program to sort the elements using Insertion Sort
#include<stdio.h>int n, a[20];
void insertion_sort()
{
int i, j, temp;
for(i=1; i<n ;i++)
{
temp = a[i];
j = i-1;
while(j>=0 && temp < a[j])
{
a[j+1] = a[j];
j = j-1;
}
a[j+1] = temp;
}
}
void main()
{
int i;
printf("\nEnter the number of elements: ");
scanf("%d",&n);
printf("\nEnter the array elements:");
for(i=0;i<n;i++)
scanf("%d", &a[i]);
insertion_sort();
printf("\nThe array elements after insertion sort: ");
for(i=0;i<n;i++)
printf("%d ", a[i]);
}
Output:
Enter the number of elements: 7
Enter the array elements: 89 45 68 90 29 34 17
The array elements after insertion sort: 17 29 34 45 68 89 90
No comments:
Post a Comment