forked from euclid1990/js-challenges
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbubble-sort.js
47 lines (42 loc) · 986 Bytes
/
bubble-sort.js
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
* Implement [Bubble sort]
*
* Copyright (c) 2018, Nguyen Van Vuong.
* Licensed under the MIT License.
*/
'use strict';
function swap(arr, i, j) {
let temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
function comparator(a, b) {
return a - b;
}
/**
* Bubble sort algorithm.
* Complexity: O(N^2).
*
* @example
* console.log(bubbleSort([2, 5, 1, 0, 4])); // [ 0, 1, 2, 4, 5 ]
*
* @public
* @module sorting/bubblesort
* @param {Array} array Input array.
* @param {Function} cmp Optional. A function that defines an
* alternative sort order. The function should return a negative,
* zero, or positive value, depending on the arguments.
* @return {Array} Sorted array.
*/
function bubbleSort(array, cmp) {
cmp = cmp || comparator;
for (let i = 0; i < array.length; i += 1) {
for (let j = i; j > 0; j -= 1) {
if (cmp(array[j], array[j - 1]) < 0) {
swap(array, j, j - 1);
}
}
}
return array;
}
module.exports = bubbleSort;