C Program to sort an array using Insertion Sort using functions
Program
#include<stdio.h>
#define SIZE 10
void insertionSort(int count, int a[])
{
int i, j, temp;
for (i = 0; i < count; i++)
{
temp = a[i];
j = i - 1;
while ((temp < a[j]) && (j >= 0))
{
a[j + 1] = a[j];
j = j - 1;
}
a[j + 1] = temp;
}
printf("Sorted Elements:\n");
for (i = 0; i < count; i++)
printf("%d\n", a[i]);
}
void main()
{
int count, i;
int a[SIZE];
printf("Enter the size of the array:\t");
scanf("%d", &count);
printf("Enter %d elements:\n", count);
for (i = 0; i < count; i++)
scanf("%d", &a[i]);
insertionSort(count, a);
}
Output
Enter the size of the array: 6
Enter 6 elements:
45
87
96
41
21
2
Sorted Elements:
2
21
41
45
87
96