This repository has been archived by the owner on Feb 21, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* Merge sort in js * Added test case of merge sort * Restyled by clang-format * Restyled by prettier Co-authored-by: kheenvraj <[email protected]> Co-authored-by: Restyled.io <[email protected]>
- Loading branch information
1 parent
3d0522c
commit f9a5b9c
Showing
2 changed files
with
41 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
/** | ||
* @param {Array} arr Input array. | ||
* @return {Array} Sorted array. | ||
* @description Merge sort algorithm in JS. | ||
*/ | ||
|
||
module.exports = { | ||
mergeSort: (arr) => { | ||
var len = arr.length; | ||
if (len < 2) return arr; | ||
var mid = Math.floor(len / 2), | ||
left = arr.slice(0, mid), | ||
right = arr.slice(mid); | ||
// send left and right to the mergeSort to broke it down into pieces | ||
// then merge those | ||
return merge(mergeSort(left), mergeSort(right)); | ||
}, | ||
}; | ||
|
||
function merge(left, right) { | ||
var result = [], | ||
lLen = left.length, | ||
rLen = right.length, | ||
l = 0, | ||
r = 0; | ||
while (l < lLen && r < rLen) { | ||
if (left[l] < right[r]) { | ||
result.push(left[l++]); | ||
} else { | ||
result.push(right[r++]); | ||
} | ||
} | ||
// remaining part needs to be addred to the result | ||
return result.concat(left.slice(l)).concat(right.slice(r)); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
// Test case of merge sort function. | ||
const merge_sort_test = require("./merge_sort.js"); | ||
|
||
const input = [5345, 55, 3423, 5346, 33]; | ||
const sorted = merge_sort_test.mergeSort(input); | ||
console.log("Merge sort", sorted); |