-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmerge.ts
56 lines (49 loc) · 1.73 KB
/
merge.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
46
47
48
49
50
51
52
53
54
55
56
import { compare } from '../../utils'
/**
* Merge Sort is a divide-and-conquer algorithm that divides the array into
* smaller pieces, sorts each piece, and then merges them back together.
*
* Time Complexity
* - Best Case: O(n log n) - Even in the best case, the array needs to be split
* down and merged back, requiring n log n operations.
*
* - Average Case: O(n log n) - This is the standard time complexity for merge
* sort, as each split divides the array in half.
*
* - Worst Case: O(n log n) - The worst case time complexity remains the same,
* as the divide and merge operations are consistent regardless of the
* input distribution.
*
* Space Complexity: O(n) - This is because merge sort requires additional space
* to store the temporary arrays used during the merge step. The space is used
* to hold the two halves that are being merged, and this space adds up to n for
* all levels of the recursion.
*
* @param arr unsorted array
* @returns sorted array
*/
export function mergeSort<TElement extends number | string>(arr: TElement[]): TElement[] {
if (arr.length <= 1) {
return arr
}
const middle = Math.floor(arr.length / 2)
const left = arr.slice(0, middle)
const right = arr.slice(middle)
return merge(mergeSort(left), mergeSort(right))
}
function merge<TElement extends number | string>(left: TElement[], right: TElement[]): TElement[] {
const resultArray: TElement[] = []
let i = 0
let j = 0
while (i < left.length && j < right.length) {
if (compare(left[i], right[j]) <= 0) {
resultArray.push(left[i])
i++
} else {
resultArray.push(right[j])
j++
}
}
return resultArray.concat(left.slice(i)).concat(right.slice(j))
}
export type MergeSortFn = typeof mergeSort