File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -822,6 +822,52 @@ function reverse(head) {
822822

823823
![](https://i.imgur.com/wozvfAe.png)
824824

825+
<div class="codepen" data-height="300" data-theme-id="dark" data-default-tab="js" data-slug-hash="WNjegBp" data-user="roopkt" data-prefill='{"title":"Merge Sort Algorithm","tags":[],"scripts":[],"stylesheets":[]}'>
826+
<pre data-lang="js">// O(n log(n)) time | O(1) space where n = length of the array.
827+
function mergeSort(array) {
828+
const length = array.length;
829+
if (length &lt; 2) {
830+
return;
831+
}
832+
const mid = length / 2;
833+
const left = array.slice(0, mid);
834+
const right = array.slice(mid, length);
835+
mergeSort(left);
836+
mergeSort(right);
837+
stitch(left, right, array);
838+
}
839+
840+
function stitch(left, right, array) {
841+
let leftIdx = 0;
842+
let rightIdx = 0;
843+
let arrayIdx = 0;
844+
let leftLength = left.length;
845+
let rightLength = right.length;
846+
847+
while (leftIdx &lt; leftLength && rightIdx &lt; rightLength) {
848+
if (left[leftIdx] &lt;= right[rightIdx]) {
849+
array[arrayIdx] = left[leftIdx];
850+
leftIdx++;
851+
} else {
852+
array[arrayIdx] = right[rightIdx];
853+
rightIdx++;
854+
}
855+
arrayIdx++;
856+
}
857+
858+
while (leftIdx &lt; leftLength) {
859+
array[arrayIdx] = left[leftIdx];
860+
leftIdx++;
861+
arrayIdx++;
862+
}
863+
while (rightIdx &lt; rightLength) {
864+
array[arrayIdx] = right[rightIdx];
865+
rightIdx++;
866+
arrayIdx++;
867+
}
868+
}</pre></div>
869+
870+
825871

826872
## Coding Interview Question and Answers
827873

0 commit comments

Comments
 (0)