Skip to content

Instantly share code, notes, and snippets.

@shahjugal
Last active July 18, 2022 10:05
Show Gist options
  • Save shahjugal/9e54625195e909ea5a5c4c1d72a518b3 to your computer and use it in GitHub Desktop.
Save shahjugal/9e54625195e909ea5a5c4c1d72a518b3 to your computer and use it in GitHub Desktop.
Insertion Sort
void insertionSort(vector<int>& arr){
int lastIndex = arr.size() - 1;
// Repeat from second element to last element.
for(int i = 1; i <= lastIndex; i++){
// Store the current element in a variable.
int element = arr[i];
// Find right index where element can fit in and make space for it.
// By shifting all other sorted elements by one place which is after.
// te destination index for element.
int j = i-1;
while(j>=0){
if(arr[j]>element){
arr[j+1] = arr[j];
j--; // Decreasing j so that we will check for element before it.
}else{
// if element is already bigger than this element then we wont check for further element
// and current j's very next index is correct index where the element should be put.
break;
}
}
// Place element in destination.
arr[j + 1] = element;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment