[AlgoExpert] Bubble Sort

Bubble Sort

  • Time : O(n^2)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 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> bubbleSort(vector<int> array) {
int n = array.size();
bool sorted = false;
for(int i = 0; i < n and !sorted; i++) {
sorted = true;
for(int j = 0; j + 1 < n - i; j++) {
if(array[j] > array[j + 1]) {
swap(array[j], array[j + 1]);
sorted = false;
}
}
}
return array;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/09/PS/AlgoExpert/bubble-sort/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.