-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path04-selection-sort.js
44 lines (39 loc) · 936 Bytes
/
04-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
function selectionSort(array) {
var swap = function(x, y) {
var temp = array[x];
array[x] = array[y];
array[y] = temp;
};
for (var i = 0, length = array.length; i < length - 1; i++) {
var minIndex = i;
for (var j = i + 1; j < length; j++) {
if (array[j] < array[minIndex]) {
minIndex = j;
}
}
swap(i, minIndex);
}
return array;
}
(function(sort) {
var random = function(max) {
var array = [];
for (var i = 0; i < max; i++) {
array[i] = i;
}
array.sort(function() {
return 0.5 - Math.random();
});
return array;
};
var test = function(count) {
for (var i = 0; i < count; i++) {
var array = random(10);
console.log('[No.' + (i + 1) + '] begin: ', array);
console.time('time');
console.log('[No.' + (i + 1) + '] end: ', sort(array));
console.timeEnd('time');
}
};
test(3);
}(selectionSort));