-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathselection-sort.js
54 lines (46 loc) · 1.55 KB
/
selection-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
48
49
50
51
52
53
54
/**
* @module lib/selection-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 selection 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++) {
var minIndex = i;
for (var j = i + 1; j < array.length; j++) {
if (compare(array, j, minIndex) < 0) {
minIndex = j;
}
}
if (minIndex !== i) {
swap(array, i, minIndex);
}
}
return array;
}
/**
* Sorts an array selection 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;