C program to sort elements in an array using insertion sort

      One of the simplest sorting algorithms is the insertion sort. Insertion sort consists of n-1 passes. In ‘i’th pass we “insert” the ‘i’th element A[i] into its rightful place among A[1], A[2], . . . , A[i-1], which were previously placed in sorted order. After doing this insertion, the objects occupying A[1], . . . , A[i] are in sorted order.

    There are different sorting techniques available. Each of them has a unique accomplishment on data. Some sorting techniques are best for less data size and some are stable for any size of data but insertion sort is the best available sorting technique to operate on a low data size. Even the algorithms which are stable for any size of data makes use of insertion sort in the end to sort the data.

The following example implements this strategy.

insertion sort program in c




Source Code:

#include<stdio.h>
void insort(int [], int);
int main()
{
    int arr[50], n, key, index; 
    printf("How many elements do you want to create the array with?(max 50): ");
    fflush(stdout);
    scanf("%d", &n);
    puts("Enter the array elements one by one \n");
    for (index = 0; index < n; index++)
        scanf("%d", &arr[index]);                //Step1
    insort(arr, n);                              //Step2
    printf("\n The elements after sorting are...\n");
    for (index = 0; index < n; index++)
        printf("%d  ", arr[index]);             //Step3
   return 0;
}

void insort(int A[], int size)
{	
    int i , j, temp; 
    for ( i = 1 ; i < size; i++ )
     {
 	 temp = A[i] ;
 	 for (j= i-1;j > =0 && temp < A[j];j--)
	     A[j+1] = A[j];
 	 A[j+1] = temp;
     }
}


edit-code-image

Sample Test cases:

1. How many elements do you want to create the array with?(max 50): 5
   Enter the array elements one by one
   5
   89
   12
    0
   45
  The elements after sorting are...
   0  5  12  45  89

2. How many elements do you want to create the array with?(max 50): 5
   Enter the array elements one by one
    0
    1
    1
    1
    2
  The elements after sorting are...
  0  1  1  1  2

Explanation:

Step 1: The elements of an array are read from the user using scanf() function.

Step 2: The function insort(arr,n) is called from the main program which sorts the elements of an array.

Step 3: After sorting the elements are printed on the output screen using printf() function.

More Insights:

Sorting

More Content:C Programs