Insertion Sort in C++

How to implement insertion sort in C++?

Insertion Sort in C++ is really simple, just take the number, compare it with all the elements on its left and place it at its proper place. For example in case of playing cards you pick the card and compare it with all the sorted cards and place it at its exact place.

The program is compiled using g++ compiler on windows.

Let’s see a graphical view of how insertion sort works:

How Insertion Sort works in graphical way:

insertion sort in C++

Algorithm for Insertion Sort:

Let ARR is an array with N elements

  1. Read ARR
  2. Repeat step 3 to 8 for I=1 to N-1
  3. Set Temp=ARR[I]
  4. Set J=I-1
  5. Repeat step 6 and 7 while Temp<ARR[J] AND J>=0
  6. Set ARR[J+1]=ARR[J] [Moves element forward]
  7. Set J=J-1

[End of step 5 inner
loop]

  1. Set ARR[J+1]=Temp [Insert element in proper place]

[End of step 2 outer
loop]

  1. Exit

 

Program to implement Insertion Sort in C++:

 

OUTPUT:

Insertion sort in c++

 

Complexity of Insertion Sort in C++:

There is 1 comparison during pass 1 for proper place. There are 2 comparisons during pass 2 for proper place. There are 3 comparisons during pass 3 for proper place, and so on accordingly.

 

F(n) = 1 + 2 + 3 + . . . . + (n-1) = n (n-1)/2 = O(n2)

 

Hence complexity for insertion sort program in C and C++ is O(n2).

 

Please comment if you face any problem.

Be the first to comment

Leave a Reply