-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmergeSort.js
More file actions
37 lines (34 loc) · 993 Bytes
/
Copy pathmergeSort.js
File metadata and controls
37 lines (34 loc) · 993 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
34
35
36
37
function mergeSort(arr) {
if (arr.length === 1) {
return arr;
}
const middleIndex = Math.floor(arr.length / 2);
const leftSlice = arr.slice(0, middleIndex);
const rightSlice = arr.slice(middleIndex, arr.length);
return merge(mergeSort(leftSlice), mergeSort(rightSlice));
}
function merge(leftSlice, rightSlice) {
const result = [];
let leftPointer = 0;
let rightPointer = 0;
while (leftPointer < leftSlice.length && rightPointer < rightSlice.length) {
if (leftSlice[leftPointer] < rightSlice[rightPointer]) {
result.push(leftSlice[leftPointer]);
leftPointer++;
} else {
result.push(rightSlice[rightPointer]);
rightPointer++;
}
}
while (leftPointer < leftSlice.length) {
result.push(leftSlice[leftPointer]);
leftPointer++;
}
while (rightPointer < rightSlice.length) {
result.push(leftSlice[rightPointer]);
rightPointer++;
}
return result;
}
const arr = [10, 9, 8, 7, 6, 5];
console.log(mergeSort(arr));