-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathMergeSort.js
More file actions
52 lines (28 loc) · 873 Bytes
/
Copy pathMergeSort.js
File metadata and controls
52 lines (28 loc) · 873 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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 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++;
}
}
return result.concat(left.slice(leftIndex),right.slice(rightIndex));
}
let arr = [10, 7, 8, 9, 1, 5];
console.log("Original array:", arr);
let sortedArr = mergeSort(arr);
console.log("Sorted array:", sortedArr);