-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmySort.js
More file actions
33 lines (27 loc) · 740 Bytes
/
Copy pathmySort.js
File metadata and controls
33 lines (27 loc) · 740 Bytes
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
/*
Implement your own sorting function.
*/
Array.prototype.mysort = function(){
const input = this;
function merge(left, right){
let results = [];
while(left.length && right.length) {
if(left[0] < right[0]){
results.push(left.shift());
} else {
results.push(right.shift());
}
}
return [...results, ...left, ...right];
}
function mergeSort(input){
if(input.length <= 1) return input;
const mid = Math.floor(input.length/2);
const left = input.slice(0, mid);
const right = input.slice(mid);
return merge(mergeSort(left), mergeSort(right));
}
return mergeSort(input);
}
let arr = [1,2,,23,3,12,3,2,56];
console.log(arr.mysort());