diff --git a/algorithms/JavaScript/README.md b/algorithms/JavaScript/README.md index 799a7306..430e8639 100644 --- a/algorithms/JavaScript/README.md +++ b/algorithms/JavaScript/README.md @@ -15,6 +15,7 @@ 1. [Bubble Sort](src/sorting/bubble-sort.js) 2. [Insertion Sort](src/sorting/insertion-sort.js) 3. [Selection Sort](src/sorting/selection-sort.js) +4. [Merge Sort](src/sorting/merge-sort.js) ## Strings 1. [Palindrome](src/strings/palindrome.js) diff --git a/algorithms/JavaScript/src/sorting/merge-sort.js b/algorithms/JavaScript/src/sorting/merge-sort.js new file mode 100644 index 00000000..9b69bb6a --- /dev/null +++ b/algorithms/JavaScript/src/sorting/merge-sort.js @@ -0,0 +1,32 @@ +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)) +} + +//testing +array = [4, 8, 7, 2, 11, 1, 3]; +console.log(mergeSort(array)); \ No newline at end of file