Skip to content

[Feat] : Added merge sort #36

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Oct 8, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions Sorts/MergeSort.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/**
* @function mergeSort
* @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.
* @see [Merge Sort](https://www.javatpoint.com/merge-sort)
* @example MergeSort([8, 3, 5, 1, 4, 2]) = [1, 2, 3, 4, 5, 8]
* @Complexity_Analysis
* Space complexity - O(n)
* Time complexity
* Best case - O(nlogn)
* Worst case - O(nlogn)
* Average case - O(nlogn)
*
* Merge Sort is a recursive algorithm and time complexity can be expressed as following recurrence relation.
* T(n) = 2T(n/2) + O(n)
* The solution of the above recurrence is O(nLogn).
*/

export const MergeSort = (items: number[]): number[] => {
var halfLength = Math.ceil(items.length / 2);
var low = items.slice(0, halfLength);
var high = items.slice(halfLength);
if (halfLength > 1) {
low = MergeSort(low);
high = MergeSort(high);
}
return merge(low, high);
};

export const merge = (low: number[], high: number[]): number[] => {
let indexLow = 0;
let indexHigh = 0;
let curIndex = 0;
let merged = Array<number>(low.length + high.length);

while (indexLow < low.length && indexHigh < high.length) {

if (low[indexLow] <= high[indexHigh]) {
merged[curIndex++] = low[indexLow];
indexLow++;
} else {
merged[curIndex++] = high[indexHigh];
indexHigh++;
}
}

while (indexLow < low.length) {
merged[curIndex++] = low[indexLow];
indexLow++;
}

while (indexHigh < high.length) {
merged[curIndex++] = high[indexHigh];
indexHigh++;
}
return merged;
};
12 changes: 12 additions & 0 deletions Sorts/test/MergeSort.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { MergeSort } from "../MergeSort";

describe("Merge Sort", () => {
it("generating array and comparing with sorted array", () => {
let arrLen = 10;
let inBuiltSortArr = Array.from(Array(arrLen)).map(x=>Math.random());
let mergeSortArray = inBuiltSortArr;

inBuiltSortArr.sort((a,b) => a-b);
expect(MergeSort(mergeSortArray)).toStrictEqual(inBuiltSortArr);
});
});