Monday, April 24, 2017

Insertion Sort - C++ Implementation

Try to understand the following procedure.

77  33  44  11  88  22  66  55

33  77 . . . . . . . . . . . . . . . . . .
33  44  77 . . . . . . . . . . . . . . .
11  33  44  77 . . . . . . . . . . . .
11  33  44  77  88 . . . . . . . . .
11  22  33  44  77  88 . . . . . .
11  22  33  44  66  77  88 . . .
11  22  33  44  55  66  77  88 

The following Code represent the concept.
/*  Bismillahir Rahmanir Rahim
    Implementation of Insertion Sort using C++
*/
#include<bits/stdc++.h>
using namespace std;

int main(){
    int ar[100000], n, i, j, key;
    cin>>n;  // number of elements
    for(i=0; i<n; i++) cin>>ar[i]; // input elements one by one
    
    for(i=1; i<n; i++){ // starting from 2nd element
        key=ar[i]; 
        j=i-1; 
        while(j>=0 && key<ar[j]){ //comparing key with all previous
            ar[j+1]=ar[j]; 
            j--;
        }
        ar[j+1]=key; 
    }
    
    for(i=0;i<n;i++) cout<<ar[i]<<" ";
    return 0;
}

No comments:

Post a Comment