
Insertion Sort
This sorting algorithm works by repeatedly inserting elements into their correct position in an array.
void InsertionSort(int n, vector<int> &arr){
for(int i = 1; i < n; i++){
// for rounds 1 to n-1
//Here we assume 0 index value as sorted
int temp = arr[i];
int j = i-1;
for(; j >= 0; j--){
if(arr[j] > temp) // {1, 4, 2, 3}
// Shifting j index value forward by 1
arr[j+1] = arr[j]; // now array becomes {1, 4, 4, 3} 2 is already stored in temp
else
break;
}
swap(arr[j+1], temp);
}
}
Last updated