|
| 1 | +/** |
| 2 | + * @function mergeSort |
| 3 | + * @description keeps on dividing the list into equal halves until it can no more be divided. By definition, if it is only one element in the list, it is sorted. |
| 4 | + * @see [Merge Sort](https://www.javatpoint.com/merge-sort) |
| 5 | + * @example MergeSort([8, 3, 5, 1, 4, 2]) = [1, 2, 3, 4, 5, 8] |
| 6 | + * @Complexity_Analysis |
| 7 | + * Space complexity - O(n) |
| 8 | + * Time complexity |
| 9 | + * Best case - O(nlogn) |
| 10 | + * Worst case - O(nlogn) |
| 11 | + * Average case - O(nlogn) |
| 12 | + * |
| 13 | + * Merge Sort is a recursive algorithm and time complexity can be expressed as following recurrence relation. |
| 14 | + * T(n) = 2T(n/2) + O(n) |
| 15 | + * The solution of the above recurrence is O(nLogn). |
| 16 | + */ |
| 17 | + |
| 18 | + export const MergeSort = (items: number[]): number[] => { |
| 19 | + var halfLength = Math.ceil(items.length / 2); |
| 20 | + var low = items.slice(0, halfLength); |
| 21 | + var high = items.slice(halfLength); |
| 22 | + if (halfLength > 1) { |
| 23 | + low = MergeSort(low); |
| 24 | + high = MergeSort(high); |
| 25 | + } |
| 26 | + return merge(low, high); |
| 27 | +}; |
| 28 | + |
| 29 | +export const merge = (low: number[], high: number[]): number[] => { |
| 30 | + let indexLow = 0; |
| 31 | + let indexHigh = 0; |
| 32 | + let curIndex = 0; |
| 33 | + let merged = Array<number>(low.length + high.length); |
| 34 | + |
| 35 | + while (indexLow < low.length && indexHigh < high.length) { |
| 36 | + |
| 37 | + if (low[indexLow] <= high[indexHigh]) { |
| 38 | + merged[curIndex++] = low[indexLow]; |
| 39 | + indexLow++; |
| 40 | + } else { |
| 41 | + merged[curIndex++] = high[indexHigh]; |
| 42 | + indexHigh++; |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + while (indexLow < low.length) { |
| 47 | + merged[curIndex++] = low[indexLow]; |
| 48 | + indexLow++; |
| 49 | + } |
| 50 | + |
| 51 | + while (indexHigh < high.length) { |
| 52 | + merged[curIndex++] = high[indexHigh]; |
| 53 | + indexHigh++; |
| 54 | + } |
| 55 | + return merged; |
| 56 | +}; |
0 commit comments