-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.js
49 lines (39 loc) · 1.09 KB
/
main.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
45
46
47
48
49
function merge_sort(arr) {
if (arr.length < 2)
return arr;
const mid = Math.floor(arr.length / 2);
let left = arr.slice(0, mid);
let right = arr.slice(mid);
return merge(merge_sort(left), merge_sort(right));
}
function merge(left, right) {
let result = [];
while (left.length > 0 && right.length > 0) {
if (left[0] < right[0])
result.push(left.shift());
else
result.push(right.shift());
}
if (left.length) result.push(...left)
if (right.length) result.push(...right)
return result;
}
function generateRandomArray(num, rangeFrom, rangeTo) {
if (rangeTo < rangeFrom) {
return;
}
const arr = new Array(num);
const range = rangeTo - rangeFrom + 1;
for (let i = 0; i < num; ++i) {
arr[i] = Math.floor(Math.random() * range + rangeFrom);
}
return arr;
}
const num = 20;
const rangeFrom = 1;
const rangeTo = 10000;
const arr = generateRandomArray(20, 1, 1000)
console.log("Original array:");
console.log(arr);
console.log("Sorted array:");
console.log(merge_sort(arr));