Insertion Sort in C & C++ – Program & Algorithm
In this tutorial I will explain about algorithm for insertion sort in C and C++ using
program example. The insertion sort inserts each element in proper place. The strategy
behind the insertion sort is similar to the process of sorting a pack of cards. You can
take a card, move it to its location in sequence and move the remaining cards left or
right as needed.
In insertion sort, we assume that first element A[0] in pass 1 is already sorted. In pass
2 the next second element A[1] is compared with the first one and inserted into its
proper place either before or after the first element. In pass 3 the third element A[2] is
inserted into its proper place and so on.
Algorithm for Insertion Sort in C & C++
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]
8. Set ARR[J+1]=Temp [Insert element in proper place]
[End of step 2 outer
loop]
9. Exit
Program for Insertion Sort in C++
1 #include<iostream>
3 using namespace std;
5 int main()
6 {
7 int i,j,n,temp,a[30];
8 cout<<"Enter the number of elements:";
9 cin>>n;
10 cout<<"\nEnter the elements\n";
11
12 for(i=0;i<n;i++)
13 {
14 cin>>a[i];
15 }
16
17 for(i=1;i<=n-1;i++)
18 {
19 temp=a[i];
20 j=i-1;
21
22 while((temp<a[j])&&(j>=0))
23 {
24 a[j+1]=a[j]; //moves element forward
25 j=j-1;
26 }
27
28 a[j+1]=temp; //insert element in proper place
29 }
30
31 cout<<"\nSorted list is as follows\n";
32 for(i=0;i<n;i++)
33 {
34 cout<<a[i]<<" ";
35 }
36
37 return 0;
38 }