Insertion Sort Algorithm in Programming
Insertion Sort Algorithm in Programming
SHARES
This tutorial is intended to provide you information about what insertion sort
algorithm is and how to implement it in programming rather than it's technical
stuff, properties and comparision with other sorting algorithm. If you know what
insertion sort algorithm is then, visit this page to learn about properties of
insertion sort and comparision with other sorting algorithm.
Explanation
If there are n elements to be sorted. Then, this procedure is repeated n-1 times
to get sorted list of array.
Note: Though this program is in C, insertion sort algorithm can be similarly used
in other programming language as well.
Output
Here is another source code that uses the same insertion sort algorithm
technique to sort elements of an array.
/*This source code is also the implemention of insertion sort algorithm to sort elements of array.*/
/*This program is little complex because it contains multiple loops.*/
/*Program to Sort array in descending order*/
#include <stdio.h>
int main()
{
int data[100],n,i,j,hold,k;
printf("Enter number of terms(should be less than 100): ");
scanf("%d",&n);
printf("Enter elements: ");
for(i=0;i<=n‐1;++i)
{
scanf("%d",&data[i]);
}
for(i=1;i<=n‐1;++i)
{
for(j=0;j<i;++j)
if(data[j]<data[i])
/*To sort elements in ascending order change < to > in above line.*/
{
hold=data[i];
k=i;
while(k!=j)
{
data[k]=data[k‐1];
‐‐k;
}
data[j]=hold;
}
}
printf("In descending Order: ");
for(i=0;i<=n‐1;++i)
{