Insert Sort

About

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 #include <bits/stdc++.h> using namespace std; void print(int a[], int n) { for (int i = 0; i < n; i++) { cout << a[i] << " "; } cout << endl; } // InsertSort void insertSort(int a[], int n) { for (int i = 0; i < n; i++) { int hole = i; int val = a[i]; while (hole > 0 && a[hole - 1] > val) { a[hole] = a[hole - 1]; hole = hole - 1; } a[hole] = val; } print(a, n); } signed main(){ int n; cin >> n; int a[n]; for (int i = 0; i < n; i++) { cin >> a[i]; } InsertSort(a, n); print(a, n); return 0; }

Insertion sort is a simple sorting algorithm that works similar to the way you sort playing cards in your hands. The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and placed at the correct position in the sorted part.

Characteristics of Insertion Sort:

  • This algorithm is one of the simplest algorithm with simple implementation
  • Basically, Insertion sort is efficient for small data values
  • Insertion sort is adaptive in nature, i.e. it is appropriate for data sets which are already partially sorted.

Insertion Sort Algorithm

  • To sort an array of size N in ascending order:
  • Iterate from arr[1] to arr[N] over the array.
  • Compare the current element (key) to its predecessor.
  • If the key element is smaller than its predecessor, compare it to the elements before. Move the greater elements one position up to make space for the swapped element.

Time Complexity

  • Worst Case Time Complexity is: O(N^2)
  • Average Case Time Complexity is: Ω(N^2)
  • Best Case Time Complexity is: Ω(N)