[AlgoExpert] Insertion Sort

Insertion Sort

  • Time : O(n^2)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// best : O(n) time | O(1) space
// avg : O(n^2) time | O(1) space
// worst : O(n^2) time | O(1) space
vector<int> insertionSort(vector<int> array) {
int n = array.size();
for(int i = 0; i < n; i++) {
int j = i;
while(j > 0 and array[j-1] > array[j]) {
swap(array[j], array[j-1]);
j--;
}
}
return array;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/09/PS/AlgoExpert/insertion-sort/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.