Created
April 26, 2017 17:08
-
-
Save pawarvijay/e16b41073ec7e78194767d0e3a4f03e0 to your computer and use it in GitHub Desktop.
Merge sort in javascript
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
function mergeSort(arr) | |
{ | |
if (arr.length < 2){ | |
return arr; | |
} | |
var middle = parseInt(arr.length / 2); | |
var left = arr.slice(0, middle); | |
var right = arr.slice(middle, arr.length); | |
return merge(mergeSort(left), mergeSort(right)); | |
} | |
function merge(left, right) | |
{ | |
var result = []; | |
while (left.length && right.length) { | |
if (left[0] <= right[0]) { | |
result.push(left.shift()); | |
} else { | |
result.push(right.shift()); | |
} | |
} | |
while (left.length){ | |
result.push(left.shift()); | |
} | |
while (right.length){ | |
result.push(right.shift()); | |
} | |
console.log(result); | |
return result; | |
} | |
var a = [34, 203, 3, 746, 200, 984, 198, 764, 9]; | |
console.log(mergeSort(a)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment