-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmerge-sort.js
More file actions
28 lines (26 loc) · 795 Bytes
/
merge-sort.js
File metadata and controls
28 lines (26 loc) · 795 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
// implemenation of quick sort algorithm.
function merger(leftArr, rightArr) {
let i = 0;
let j = 0;
const mergedArr = [];
while (i < leftArr.length && j < rightArr.length) {
if (leftArr[i] > rightArr[j]) mergedArr.push(rightArr[j++]);
else mergedArr.push(leftArr[i++]);
}
while (i < leftArr.length) {
mergedArr.push(leftArr[i++]);
}
while (j < rightArr.length) {
mergedArr.push(rightArr[j++]);
}
return mergedArr;
}
function mergeSort(arr) {
if (arr.length === 1) return arr;
const middle = Math.floor(arr.length / 2);
const left = mergeSort(arr.slice(0, middle));
const right = mergeSort(arr.slice(middle));
return merger(left, right);
}
console.log(mergeSort([4, 2, 4, 2, 8, 5, 3, 9, 0]));
console.log(mergeSort([6, 9, 1, 3, 5, 8, 0, 2, 10]));