-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbubble-sort.js
More file actions
29 lines (23 loc) · 681 Bytes
/
bubble-sort.js
File metadata and controls
29 lines (23 loc) · 681 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
const { swap } = require('./sorting-common');
// tag::sort[]
/**
* Bubble sort - Bubbles up bigger values to the right side
* Runtime: O(n^2)
* @param {Array|Set} collection elements to be sorted
*/
function bubbleSort(collection) {
const array = Array.from(collection); // <1>
for (let i = 1; i < array.length; i++) { // <6>
let swapped = false;
for (let current = 0; current < array.length - i; current++) { // <4>
if (array[current] > array[current + 1]) { // <2>
swap(array, current, current + 1); // <3>
swapped = true;
}
}
if (!swapped) break; // <5>
}
return array;
}
// end::sort[]
module.exports = bubbleSort;