Skip to content

Instantly share code, notes, and snippets.

@sudoankit
Last active December 20, 2015 15:24
Show Gist options
  • Save sudoankit/1e37814ac0157f9e3fff to your computer and use it in GitHub Desktop.
Save sudoankit/1e37814ac0157f9e3fff to your computer and use it in GitHub Desktop.
The insertion sort using C++
#include<iostream>
using namespace std;
void insertion_sort(int A[],int n){
for(int i = 0 ; i < n ;i++){
int j,key; // I have taken hole as j. It's sounds better, anyways.
key = A[i];
j = i;
while(j > 0 && A[j-1] > key ){
A[j] = A[j-1]; //left shift
j--;
}
A[j] = key;
}
}
int main(){
int n;
cin >> n;
int *A = new int[n];
for(int j = 0; j < n ; j++){
cin >> A[j];
}
cout << "Initializing insertion sort" << '\n';
cout << "-----Sorted Array-----"<< '\n';
insertion_sort(A,n);
for(int j = 0; j < n ; j++){
cout << A[j] << '\n';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment