Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions Cpp/insertion_sort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#include<iostream>
using namespace std;

//Sort the elements in increasing order
void insertion_sort(int a[],int n){

for(int i=1; i<=n-1; i++){

int current = a[i];

int prev = i - 1;
//loop to find the right index where the element current should be inserted
while(prev>=0 and a[prev] > current){
a[prev + 1] = a[prev];
prev = prev - 1;
}

a[prev+1] = current;
}


}


int main(){
int arr[] = {-2,3,4,-1,5,-12,6,1,3};
int n = sizeof(arr)/sizeof(int);
insertion_sort(arr,n);

for(auto x : arr){
cout << x <<",";
}

return 0;
}