Last active
October 15, 2018 10:09
-
-
Save sharmaabhinav/acbe99d0178e1049030adf2911e89735 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
var arr = [2,1,3,4,2,5,6,3,7] | |
mergeSort(arr, 0, arr.length - 1) | |
function mergeSort (arr, low, high) { | |
if (low == high) { | |
return [arr[low]] | |
} | |
var middle = Math.floor((low + high) / 2) | |
var leftArr = mergeSort(arr, low, middle) | |
var rightArr = mergeSort(arr, middle+1, high) | |
var newArr = merge(leftArr, rightArr) | |
return newArr | |
} | |
function merge (arr1, arr2) { | |
var newArr = [] | |
var start1 = 0 | |
var start2 = 0 | |
while(start1 < arr1.length && start2 < arr2.length) { | |
if (arr1[start1] <= arr2[start2]) { | |
newArr.push(arr1[start1]) | |
start1 += 1 | |
} else { | |
newArr.push(arr2[start2]) | |
start2 += 1 | |
} | |
} | |
while(start1 < arr1.length) { | |
newArr.push(arr1[start1]) | |
start1 += 1 | |
} | |
while(start2 < arr2.length) { | |
newArr.push(arr2[start2]) | |
start2 += 1 | |
} | |
return newArr | |
} | |
(9) [1, 2, 2, 3, 3, 4, 5, 6, 7] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment