forked from hustcc/JS-Sorting-Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutil.js
More file actions
73 lines (57 loc) · 1.74 KB
/
util.js
File metadata and controls
73 lines (57 loc) · 1.74 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
const os = require('os');
const bubbleSort = require('./01.bubbleSort.js');
const selectionSort = require('./02.selectionSort.js');
const insertionSort = require('./03.insertionSort.js');
const shellSort = require('./04.shellSort.js');
const arrayLength = 10000;
const testCount = 100;
function randomArray() {
const arr = [];
for (let i = 0; i < arrayLength; i++) {
arr.push(Math.floor(Math.random() * 1000));
}
return arr;
}
function getItemCounter(arr) {
const map = new Map();
arr.forEach(item => {
map.has(item) ? map.set(item, map.get(item) + 1) : map.set(item, 1);
});
return map;
}
/**
*
*
* @param {number[]} arr
* @param {number[]} sortedArr
*/
function check(arr, sortedArr) {
for (let i = 0; i < sortedArr.length - 1; i++) {
if (sortedArr[i] > sortedArr[i + 1]) {
throw new Error('升序排序错误');
}
}
const arrMap = getItemCounter(arr);
const sortedArrMap = getItemCounter(sortedArr);
for (let key of arrMap.keys()) {
if (sortedArrMap.get(key) === undefined
|| sortedArrMap.get(key) !== arrMap.get(key)) {
throw new Error('排序错误');
}
}
return true;
}
function test(sort, toBeSortedArr) {
const innerSorted = toBeSortedArr.slice();
const sortedArr = sort(innerSorted.slice());
check(innerSorted, sortedArr);
const sTime = Date.now();
for (let i = 0; i <= testCount; i++) {
sort(innerSorted.slice());
}
console.log(`${arrayLength} elements ${testCount} times test ${sort.name} cost ${Date.now() - sTime} ms`);
};
const toBeSortedArr = randomArray();
// test(bubbleSort, toBeSortedArr);
test(insertionSort, toBeSortedArr);
test(shellSort, toBeSortedArr);