# Insertion Sort Program in C

In this post, we will write a C program to implement the Insertion sort algorithm.

In this sorting technique, a region of the array, which might be the lower or upper part, is considered assorted. An element outside the sorted region is picked up and its appropriate place is searched for in the sorted region (so that even after the insertion of this element, the region remains sorted) and the element is inserted there, hence the name insertion sort.

# Insertion Sort Program in C

Let's create a file named insertionsort.c and add the following source code to it:

``````# include <stdio.h>
#define max 20

int main()
{
int arr[max],i,j,temp,len;

printf("How many numbers are there ? ");
scanf("%d",&len);
printf("Enter %d values to sort\n",len);
for(i=0;i<len;i++)
scanf("%d",&arr[i]);
for(i=1;i<len;i++)
{
for(j=i;j>0;j--)
{
if(arr[j]<arr[j-1])
{
temp=arr[j];
arr[j]=arr[j-1];
arr[j-1]=temp;
}
}
}
printf("\nThe ascending order of the values entered is:\n");
for(i=0;i<len;i++)
printf("%d\n",arr[i]);
return 0;
}
``````

To compile and run the above C program, you can use C Programs Compiler Online tool.

Output:

``````How many numbers are there ? 7
Enter 7 values to sort

7
5
6
1
2
3
4

The ascending order of the values entered is:
1
2
3
4
5
6
7``````