Created
April 18, 2017 12:02
-
-
Save dhonig/75b7a8fdb146aa79082608cfa4f8e8c5 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
class Mergesort{ | |
constructor(numbers){ | |
this.numbers=numbers; | |
} | |
merge(left, right){ | |
var result=[]; | |
console.log("Left:"+left); | |
console.log("Right"+right); | |
///Conquer | |
while (left.length && right.length ) { | |
if (left[0] <= right[0]) { | |
result.push(left.shift()); | |
} else { | |
result.push(right.shift()); | |
} | |
} | |
//Process into a result | |
while (left.length) | |
result.push(left.shift()); | |
while (right.length) | |
result.push(right.shift()); | |
return result; | |
} | |
mergesort(array){ | |
//If the array size is 0 or 1 return the array | |
if(array.length <2) | |
return array; | |
//Divide | |
var middle = parseInt(array.length /2); | |
console.log("Middle"+ middle); | |
var left = array.slice(0,middle); | |
var right= array.slice(middle,array.length) | |
return this.merge(this.mergesort(left),this.mergesort(right)); | |
} | |
sort(){ | |
return this.mergesort(this.numbers); | |
} | |
} | |
var numbers=[4,1,3,2,11,19,22,18,28,40,25] | |
sort=new Mergesort(numbers); | |
console.log(sort.sort()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment