-
Notifications
You must be signed in to change notification settings - Fork 96
/
Copy pathmergeSort.js
35 lines (29 loc) · 809 Bytes
/
mergeSort.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
function mergeSort(arr) {
if (arr.length <= 1) {
return arr;
}
const mid = Math.floor(arr.length / 2);
const left = mergeSort(arr.slice(0, mid));
const right = mergeSort(arr.slice(mid));
return merge(left, right);
}
function merge(left, right) {
let result = [];
let leftIndex = 0;
let rightIndex = 0;
while (leftIndex < left.length && rightIndex < right.length) {
if (left[leftIndex] < right[rightIndex]) {
result.push(left[leftIndex]);
leftIndex++;
} else {
result.push(right[rightIndex]);
rightIndex++;
}
}
// Concat remaining elements
return result.concat(left.slice(leftIndex)).concat(right.slice(rightIndex));
}
// Example usage
const arr = [38, 27, 43, 3, 9, 82, 10];
const sortedArray = mergeSort(arr);
console.log(sortedArray);