Algorithm For Insertion Sort in C & C++
Algorithm For Insertion Sort in C & C++
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
3. Set Temp=ARR[I]
4. Set J=I-1
7. Set J=J-1
9. Exit
5 int main()
6 {
7 int i,j,n,temp,a[30];
9 cin>>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 {
25 j=j-1;
26 }
27
29 }
30
32 for(i=0;i<n;i++)
33 {
34 cout<<a[i]<<" ";
35 }
36
37 return 0;
38 }