Last Updated:

# Insertion Sort in C

## Algorithm

Input: Input the size and elements of an array.
Output: Displays the array in sorted order

1.Start
2.Read the size of the array say n
3.i = 0
4.while ( i <n )
4.1 read a [ i ]
4.2 i++
5.for i = 1 to n
5.1.j=i-1
5.2.temp=a[i]
5.3.for j = i-1 to j>=0 and a[ j ]>temp
5.3.1.a[ j+1 ]=a[ j ]
5.4.a[ j+1 ]=temp
6.Print "The sorted array is " a [ n ]
7.Stop

## C Program

#include<stdio.h>
void main()
{
int n,temp,small;
printf("Enter the size of array:");
scanf("%d",&n);
int a[n];
printf("Enter the elements in the array:\n");
for(int i=0;i<n;i++) {
scanf("%d",&a[i]);
}
printf("The array before sorting is:");
for(int i=0;i<n;i++) {
printf("%d\t",a[i]);
}
//loop for unsorted array
for(int i=1;i<n;i++) {
int j=i-1;
temp=a[i];
//loop for checking and shifting elements to right
for(j;j>=0 && a[j]>temp;j--) {
a[j+1]=a[j];
}
//statement for insertion of element
a[j+1]=temp;
}
printf("\nThe array after sorting is:");
for(int i=0;i<n;i++) {
printf("%d\t",a[i]);
}
}

## Output

Enter the size of array:5
Enter the elements in the array:
4
3
2
5
1
The array before sorting is:4   3       2       5       1
The array after sorting is:1    2       3       4       5