Program for insertion sort in c; Through this tutorial, we will learn how to implement the insertion sort program in c using for loop, while loop, and function.
Insertion sort is a sorting algorithm that places an unsorted element at its suitable place in each iteration. Insertion sort works similarly as we sort cards in our hand in a card game. We assume that the first card is already sorted then, we select an unsorted card.
C Program For Insertion Sort
- C Program to Insertion Sort using For Loop
- C Program to Insertion Sort using While Loop
- C Program to Insertion Sort using Function
C Program to Insertion Sort using For Loop
#include <stdio.h>
int main()
{
int a[100], number, i, j, temp;
printf("\n Please Enter the total Number of Elements : ");
scanf("%d", &number);
printf("\n Please Enter the Array Elements : ");
for(i = 0; i < number; i++)
scanf("%d", &a[i]);
for(i = 1; i <= number - 1; i++)
{
for(j = i; j > 0 && a[j - 1] > a[j]; j--)
{
temp = a[j];
a[j] = a[j - 1];
a[j - 1] = temp;
}
}
printf("\n Insertion Sort Result : ");
for(i = 0; i < number; i++)
{
printf(" %d \t", a[i]);
}
printf("\n");
return 0;
}
The output of the above c program; is as follows:
Please Enter the total Number of Elements : 5 Please Enter the Array Elements : 1 9 4 3 2 Insertion Sort Result : 1 2 3 4 9
C Program to Insertion Sort using While Loop
#include <stdio.h>
int main()
{
int a[100], number, i, j, temp;
printf("\n Please Enter the total Number of Elements : ");
scanf("%d", &number);
printf("\n Please Enter the Array Elements : ");
for(i = 0; i < number; i++)
scanf("%d", &a[i]);
i = 1;
while( i <= number - 1)
{
j = i;
while( j > 0 && a[j - 1] > a[j])
{
temp = a[j];
a[j] = a[j - 1];
a[j - 1] = temp;
j--;
}
i++;
}
printf("\n Result : ");
for(i = 0; i < number; i++)
{
printf(" %d \t", a[i]);
}
printf("\n");
return 0;
}
The output of the above c program; is as follows:
Please Enter the total Number of Elements : 5 Please Enter the Array Elements : 6 9 1 2 4 Result : 1 2 4 6 9
C Program to Insertion Sort using Function
#include <stdio.h>
void insFunc(int a[], int num) {
int i, j, temp;
for(i = 1; i <= num - 1; i++)
{
for(j = i; j > 0 && a[j - 1] > a[j]; j--)
{
temp = a[j];
a[j] = a[j - 1];
a[j - 1] = temp;
}
}
}
int main()
{
int a[100], num, i;
printf("\n Please Enter the total No. of Elements : ");
scanf("%d", &num);
printf("\n Please Enter the Array Elements : ");
for(i = 0; i < num; i++)
scanf("%d", &a[i]);
insFunc(a, num);
printf("\n Output : ");
for(i = 0; i < num; i++) {
printf(" %d \t", a[i]);
}
printf("\n");
return 0;
}
The output of the above c program; is as follows:
Please Enter the total No. of Elements : 5 Please Enter the Array Elements : 8 6 4 2 1 Output : 1 2 4 6 8