Files
  • index.js
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function bubbleSort(array) {
  let switched
  do {
    switched = false
    for (let i = 0; i < array.length; i++) {
      if (array[i] > array[i + 1]) {
        [array[i], array[i + 1]] = [array[i + 1], array[i]]
        switched = true
      }
    }
  } while(switched)
  return array
}

bubbleSort([9, 5, 10, 3, 2]) // [2, 3, 5, 9, 10]

// Best time: O(n). 
// Average and worst time: O(n ^ 2). 
// Space: O(1). O(n). 
node v10.15.2 linux/amd64