Skip to content
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

Merge Sort in JavaScript #1748

Merged
merged 4 commits into from
Jan 7, 2021
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 2 additions & 0 deletions JavaScript/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
# Codes in the Javascript language

## Algorithms

- [Russian Peasant Algorithm](Algorithms/RussianPeasant.js)
- [Z Algorithm](Algorithms/ZAlgorithm.js)
- [Boyer Moore's Majority Vote Algorithm](Algorithms/BoyerMooreAlgorithm.js)
Expand All @@ -36,6 +37,7 @@
- [Insertion Sort](./sort/insertion_sort.js)
- [Sleep Sort](./sort/sleepSort.js)
- [Quick Sort](./sort/quicksort.js)
- [Merge Sort](./sort/MergeSort.js)

## Machine Learning

Expand Down
51 changes: 51 additions & 0 deletions JavaScript/sort/MergeSort.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/**
*
* Merge sort uses the concept of divide-and-conquer to sort the given list of elements.
* It breaks down the problem into smaller subproblems until they become simple enough to solve directly.
*
* Time Complexity: O(nlogn)
*
* Space Complexity: O(n)
*/
function merge(left, right) {
let arr = [];
// Break out of loop if any one of the array gets empty
while (left.length && right.length) {
// Pick the smaller among the smallest element of left and right sub arrays
if (left[0] < right[0]) {
arr.push(left.shift());
} else {
arr.push(right.shift());
}
}

// Concatenating the leftover elements
// (in case we didn't go through the entire left or right array)
return [...arr, ...left, ...right];
}

function mergeSort(array) {
const half = array.length / 2;

// Base case or terminating case
if (array.length < 2) {
return array;
}

const left = array.splice(0, half);
return merge(mergeSort(left), mergeSort(array));
}

var array = prompt("Enter Numbers to Sort (Comma Separated) : ").split(",");
// You Can also give static input if prompt() not works for you. like this :
// array = [4, 8, 7, 2, 11, 1, 3];

console.log(mergeSort(array));

/*
* Sample Input:
* 96,56,53,85,115,20
*
* Sample Output:
* 20,53,56,85,96,115
*/