If you're in a computer science background, widening your technical horizons is the best thing you should do. However, your programming skills matter the most and one must continuously keep sharpening these skills. And to become a better programmer in the future. Though there are multiple things to focus on, one specific area you must focus on is the world of data structures. Data structures in general are specific approaches to solve problems in such a way that computer resources get used minimum. In general, there are multiple data structures you can learn and implement as well. However, to keep things simple were going to start with some basic programs you must learn before moving on to complex algorithms. Therefore today we're going to learn how to Implement Insertion Sort using C++.

 

What is Insertion Sort?

 

  • Comes in the list of simplest data structure, Insertion Sort is the way of arranging elements in ascending order. The array is either sorted or is unsorted.

 

  • When the array is sorted this data structure works quickest. However, when elements aren't sorted it works the slowest.

 

What's The Approach?

 

  • Consider arr[n] of size n we want to implement Insertion Sort on. So firstly we'll iterate a loop from 1 to n.

 

  • Next, we'll compare the element at iterating index with its preceding element from the array. If the comparing element is smaller, we'll again compare it with the before elements.

 

  • Lastly, Move the greater elements one position up to make space for the swapped element.

 

Also Read: Implement Linked List using Java

 

C++ Program To Implement Insertion Sort

 

Input:

 

12, 11, 13, 5, 6

 

Output:

 

5 6 11 12 13

 

// C++ program for implementation of insertion sort  #include <bits/stdc++.h>  using namespace std;    /* Function to sort an array using insertion sort*/  void insertionSort(int arr[], int n)  {      int i, key, j;      for (i = 1; i < n; i++)      {          key = arr[i];          j = i - 1;            /* Move elements of arr[0..i-1], that are          greater than key, to one position ahead          of their current position */          while (j >= 0 && arr[j] > key)          {              arr[j + 1] = arr[j];              j = j - 1;          }          arr[j + 1] = key;      }  }    // A utility function to print an array of size n  void printArray(int arr[], int n)  {      int i;      for (i = 0; i < n; i++)          cout << arr[i] << " ";      cout << endl;  }    /* Driver code */  int main()  {      int arr[] = { 12, 11, 13, 5, 6 };      int n = sizeof(arr) / sizeof(arr[0]);        insertionSort(arr, n);      printArray(arr, n);        return 0;  }