insertion sorting in c programming - data structures and algorithms
October 7, 2022

Insertion Sorting in C Programming

INSERTION SORTING: – An insertion sort is one that sorts a set of records by inserting records into an existing sorted file. If the initial file is sorted only one comparison is made on each pass so that the sort is O (N). If the file is initially sorted in reverse order, the sort is O (N²). The simple insertion sort is still usually better than the bubble sort. The closer the file is to sorted order, the more efficient the simple insertion sort becomes. The average number of comparisons in the simple insertion sort (by considering all possible permutations of the input array) is also O (n²). The space requirements for the sort consist of only one temporary variable.

Both the selection sort and the simple insertion sort are more efficient than the bubble sort Selection sort requires fewer assignments than insertion sort but more companions The insertion sort algorithm is a very slow algorithm when n is very large. Insertion sort is usually used only when n is small. This algorithm is very popular with bridge players when they first sort their cards In this procedure, we pick up a particular value and then insert it at the appropriate place in the sorted sub-list. The worst-case performance occurs when the input array elements are in descending order. The first pass makes 1 comparison, the second pass makes 2 and the last pass makes an N – 1 comparison. So total comparisons are 1.2 * [N – 2) (N – 1) = NIN – 1 / 2 = O (N²).

Algorithm – Insertion sorting in c.


Here A is an array with N elements. This algorithm sorts the array A with N elements in ascending order.

1. Repeat Steps 2 to 5 for I=2 to N

2. Set ITEM: = A [1].

3. Set J: = 1-1.

4. Repeat Steps while J > = 1 AND A [J] > ITEM:

         (a) Set A [J + 1] = A [J]. [Moves element forward.]

         (b) Set J: = J – 1.

    [End of Step 4 loop]

5. Set A [J + 1]: = ITEM. [Inserts element in the proper place.]

    [End of Step 1 loop.]

6. Return.

Insertion sorting program in C.

#define SIZE 10
void insertion_sort(int [],int);

void main()
    int a[SIZE],i,n;
    printf("Enter how many elements");

    /*Input Array */

        printf("Enter element %d ",i+1);


    /* Output Array */



void insertion_sort(int a[], int n)
    int i,j,item;

        item = a[i];

        /*Shifting */

        for(j=i-1;j>=0 && a[j] > item; j--)
            a[j+1] = a[j];

        /* insert */
        a[j+1] = item;

Also, Read

  1. Sorting Techniques in Data Structures
  2. Selection sorting in C Programming
  3. Bubble Sorting in C Programming
  4. Shell Sorting in C Programming
  5. Merge Sorting in C Programming
  6. Radix Sorting in C Programming
  7. Quick Sorting in C Programming
  8. Heap Sorting in C Programming
  9. Selection Sorting Algorithm

Leave a Reply

Your email address will not be published. Required fields are marked *