-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmergeSort.ts
More file actions
40 lines (34 loc) · 829 Bytes
/
Copy pathmergeSort.ts
File metadata and controls
40 lines (34 loc) · 829 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
export var diff = 0, swap = 0
export function mergeSort(array: number[]) {
if (array.length < 2) {
return array;
}
const k = Math.round(array.length / 2);
const arrL = mergeSort(array.concat().slice(0, k))
const arrR = mergeSort(array.concat().slice(k))
return merge(arrL, arrR)
}
function merge(arrL: number[], arrR: number[]) {
const res = [];
let i = 0, j = 0;
while (i < arrL.length && j < arrR.length) {
diff++
if (arrL[i] <= arrR[j]) {
res.push(arrL[i])
i++
} else {
res.push(arrR[j])
j++
swap += arrL.length - i
}
}
if (i === arrL.length) {
res.push(...arrR.slice(j))
}
if (j === arrR.length) {
res.push(...arrL.slice(i))
}
return res;
}
// console.log(mergeSort([3, 8, 6, 2, 4, 11, 7, 9, 5]), diff)
export default { mergeSort }