Skip to content

Commit 66892d7

Browse files
authored
[Feat] : Added merge sort (#36)
1 parent ca9fd24 commit 66892d7

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed

Sorts/MergeSort.ts

+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
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+
};

Sorts/test/MergeSort.test.ts

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import { MergeSort } from "../MergeSort";
2+
3+
describe("Merge Sort", () => {
4+
it("generating array with variable length and comparing with sorted array", () => {
5+
let arrLenArr = [10, 200, 40000];
6+
7+
arrLenArr.forEach((arrLen: number) => {
8+
9+
let inBuiltSortArr = Array<number>(arrLen)
10+
for (let i = 0; i < arrLen; i++) { inBuiltSortArr[i] = Math.random() * 10000 }
11+
let mergeSortArray = inBuiltSortArr.slice();
12+
13+
inBuiltSortArr.sort((a, b) => a - b);
14+
expect(MergeSort(mergeSortArray)).toStrictEqual(inBuiltSortArr);
15+
16+
})
17+
});
18+
});
19+

0 commit comments

Comments
 (0)