Skip to content

Instantly share code, notes, and snippets.

@earlonrails
Created July 24, 2017 21:56
Show Gist options
  • Save earlonrails/5a6b1fbe45fdb0267801516a878188b5 to your computer and use it in GitHub Desktop.
Save earlonrails/5a6b1fbe45fdb0267801516a878188b5 to your computer and use it in GitHub Desktop.
MergeSort in es6!
#!/usr/bin/env node
"use strict"
const expect = require('expect.js')
class MergeSort {
static sort(array) {
let mid = array.length / 2
let left = array.slice(0, mid)
let right = array.slice(mid)
if (array.length === 1) {
return array
}
return this.merge(this.sort(left), this.sort(right))
}
static merge(left, right) {
var results = []
while(left.length || right.length) {
if (left.length && right.length) {
if (left[0] < right[0]) {
results.push(left.shift())
} else {
results.push(right.shift())
}
} else if (left.length) {
results.push(left.shift())
} else if (right.length) {
results.push(right.shift())
}
}
return results
}
}
var results = MergeSort.sort([5,7,2,1,3,4,9,10,12,15,11,1,2,3,15,4])
expect(results).to.eql([1, 1, 2, 2, 3, 3, 4, 4, 5, 7, 9, 10, 11, 12, 15, 15])
var results = MergeSort.sort([2,1])
expect(results).to.eql([1,2])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment