-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsortAlgo.js
More file actions
93 lines (73 loc) · 1.81 KB
/
Copy pathsortAlgo.js
File metadata and controls
93 lines (73 loc) · 1.81 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
const l = 10000;
const createRandomArray = () => {
for (var a = [], i = 0; i < l; ++i) a[i] = i;
function shuffle(array) {
var tmp,
current,
top = array.length;
if (top)
while (--top) {
current = Math.floor(Math.random() * (top + 1));
tmp = array[current];
array[current] = array[top];
array[top] = tmp;
}
return array;
}
return shuffle(a);
};
const measurePerformance = (fn) => {
const start = performance.now();
console.log(fn());
const end = performance.now();
console.log({ performance: end - start });
};
const sortTry1 = (array) => {
let result = [];
//find minimum push it and remove it from array
while (array.length) {
let minimum = array[0];
array.forEach((v) => {
if (v < minimum) {
minimum = v;
}
});
array.splice(array.indexOf(minimum), 1);
result.push(minimum);
}
return result;
};
measurePerformance(() => sortTry1(createRandomArray()));
function merge(left, right) {
let arr = [];
while (left.length && right.length) {
if (left[0] < right[0]) {
arr.push(left.shift());
} else {
arr.push(right.shift());
}
}
return [...arr, ...left, ...right];
}
function mergeSort(array) {
const half = array.length / 2;
if (array.length < 2) {
return array;
}
const left = array.splice(0, half);
return merge(mergeSort(left), mergeSort(array));
}
measurePerformance(() => mergeSort(createRandomArray()));
const quickSort = (a) => {
if (a.length <= 1) {
return a;
}
let pivot = a[a.length - 1];
let left = [];
let right = [];
for (ele of a.slice(0, a.length - 1)) {
ele < pivot ? left.push(ele) : right.push(ele);
}
return [...quickSort(left), pivot, ...quickSort(right)];
};
measurePerformance(() => quickSort(createRandomArray()));