forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMerge_Sort.ts
46 lines (40 loc) · 1.06 KB
/
Merge_Sort.ts
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
export function mergeSort(array: number[]): number[] {
if (array.length <= 1) {
return array;
}
const middle = Math.floor(array.length / 2);
const left = array.slice(0, middle);
const right = array.slice(middle);
return merge(mergeSort(left), mergeSort(right));
}
function merge(left: number[], right: number[]): number[] {
const array: number[] = [];
let lIndex = 0;
let rIndex = 0;
while (lIndex + rIndex < left.length + right.length) {
const lItem = left[lIndex];
const rItem = right[rIndex];
if (lItem == null) {
array.push(rItem);
rIndex++;
}
else if (rItem == null) {
array.push(lItem);
lIndex++;
}
else if (lItem < rItem) {
array.push(lItem);
lIndex++;
}
else {
array.push(rItem);
rIndex++;
}
}
return array;
}
console.log(mergeSort([8, 7, 4, 30, 21, 12]));
/*
Input : [8, 7, 4, 30, 21, 12]
Output : [ 4, 7, 8, 12, 21, 30 ]
*/