Insertion Sort

Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort.Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there. It repeats until no input elements remain.



Insertion Sort Visualization

A[0] A[1] A[2] A[3] A[4] A[5] A[6] A[7] A[8] A[9] A[10]
94 64 92 36 20 5 83 75 23 19 36


      




Best Case complexity : O(n)

Worst Case complexity : O(n²)

Trace
  • Procedure Insertion_sort(list)
  •   i=0 , j=1
  •   for all elements in list[n]
  •       if list[i] > list[j]
  •             if i+1 == j
  •                 swap(list[i],list[j])
  •             else
  •                   temp=list[j]
  •                   k=j
  •                   while true
  •                        if list[k] > temp
  •                              swap(list[k],list[k+1])
  •                              k--
  •                        else
  •                              list[k+1]=temp
  •                              break
  •       else
  •             i++
  •   i=0 , j++
  •   return list
  • end Insertion_Sort




Insertion Sort Code in C:

                      
                        #include <stdio.h>
 
                        int main()
                        {
                          int n, array[1000], c, d, t;
                         
                          printf("Enter number of elements\n");
                          scanf("%d", &n);
                         
                          printf("Enter %d integers\n", n);
                         
                          for (c = 0; c < n; c++)
                            scanf("%d", &array[c]);
                         
                          for (c = 1 ; c <= n - 1; c++) {
                            d = c;
                         
                            while ( d > 0 && array[d-1] > array[d]) {
                              t          = array[d];
                              array[d]   = array[d-1];
                              array[d-1] = t;
                         
                              d--;
                            }
                          }
                         
                          printf("Sorted list in ascending order:\n");
                         
                          for (c = 0; c <= n - 1; c++) {
                            printf("%d\n", array[c]);
                          }
                         
                          return 0;
                        }