-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathbubble-sort.js
47 lines (42 loc) · 1.47 KB
/
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
/**
* @module lib/bubble-sort
* @license MIT Copyright 2014 Daniel Imms (http://www.growingwiththeweb.com)
*/
'use strict';
var attachObserver = require('./common/attach-observer');
var defaultSwap = require('./common/default-swap');
var exposeCompareObserver = require('./common/expose-compare-observer');
var exposeSwapObserver = require('./common/expose-swap-observer');
var wrapCompare = require('./common/wrap-compare');
/**
* Sorts an array using bubble sort.
* @param {Array} array The array to sort.
* @param {function} compare The compare function.
* @param {function} swap A function to call when the swap operation is
* performed. This can be used to listen in on internals of the algorithm.
* @returns The sorted array.
*/
function sort(array, compare, swap) {
for (var i = 0; i < array.length - 1; i++) {
for (var j = 1; j < array.length - i; j++) {
if (compare(array, j - 1, j) > 0) {
swap(array, j, j - 1);
}
}
}
return array;
}
/**
* Sorts an array using bubble sort.
* @param {Array} array The array to sort.
* @param {function} customCompare A custom compare function.
* @returns The sorted array.
*/
function sortExternal(array, customCompare) {
var compare = wrapCompare(customCompare, sortExternal.compareObserver);
var swap = attachObserver(defaultSwap, sortExternal.swapObserver);
return sort(array, compare, swap);
};
exposeCompareObserver(sortExternal);
exposeSwapObserver(sortExternal);
module.exports = sortExternal;