forked from blakeembrey/code-problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselection-sort.js
More file actions
35 lines (29 loc) · 741 Bytes
/
Copy pathselection-sort.js
File metadata and controls
35 lines (29 loc) · 741 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
30
31
32
33
34
35
module.exports = function (array, compare) {
// Not an array, empty or array of 1 is already sorted
if (!Array.isArray(array) || array.length < 2) {
return array;
}
var swap = function (array, first, second) {
var temp = array[first];
array[first] = array[second];
array[second] = temp;
return array;
};
// Create a compare func if not passed in
if (typeof compare !== 'function') {
compare = function (a, b) {
return a > b ? 1 : -1;
};
}
var min, i, j;
for (i = 0; i < array.length; i++) {
min = i;
for (j = i + 1; j < array.length; j++) {
if (compare(array[j], array[min]) < 0) {
min = j;
}
}
swap(array, i, min);
}
return array;
};