Skip to content
This repository was archived by the owner on Dec 12, 2023. It is now read-only.

Commit 959bbff

Browse files
committed
Implement selection sort in JavaScript.
1 parent 1635c61 commit 959bbff

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

selection-sort/selection-sort.js

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
module.exports = function (array, compare) {
2+
// Not an array, empty or array of 1 is already sorted
3+
if (!Array.isArray(array) || array.length < 2) {
4+
return array;
5+
}
6+
7+
var swap = function (array, first, second) {
8+
var temp = array[first];
9+
array[first] = array[second];
10+
array[second] = temp;
11+
return array;
12+
};
13+
14+
// Create a compare func if not passed in
15+
if (typeof compare !== 'function') {
16+
compare = function (a, b) {
17+
return a > b ? 1 : -1;
18+
};
19+
}
20+
21+
var min, i, j;
22+
23+
for (i = 0; i < array.length; i++) {
24+
min = i;
25+
for (j = i + 1; j < array.length; j++) {
26+
if (compare(array[j], array[min]) < 0) {
27+
min = j;
28+
}
29+
}
30+
31+
swap(array, i, min);
32+
}
33+
34+
return array;
35+
};

0 commit comments

Comments
 (0)