Created
February 27, 2017 22:05
-
-
Save earlonrails/bd059727fb1722b96864bddef27b67f4 to your computer and use it in GitHub Desktop.
quicksort in ES6 adapted from https://www.nczonline.net/blog/2012/11/27/computer-science-in-javascript-quicksort/
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
#!/usr/bin/env node | |
"use strict" | |
class Quicksort extends Array { | |
// swap the value in the leftIdx with the value in the rightIdx | |
swap(leftIdx, rightIdx) { | |
let old = this[leftIdx] | |
this[leftIdx] = this[rightIdx] | |
this[rightIdx] = old | |
} | |
// Find the pivot point of which we will compare the left and right values with and | |
// then either move the pointer towards the pivot or swap the left and right values | |
partition(leftIdx, rightIdx) { | |
let pivot = this[Math.floor((rightIdx + leftIdx) / 2)] // middle number | |
let left = leftIdx | |
let right = rightIdx | |
// left point has not crossed the right pointer | |
while (left <= right) { | |
// the value at the left pointer is less than the pivot then increase the index | |
// moving it towards the pivot point | |
while (this[left] < pivot) { | |
left++ | |
} | |
// the value at the right pointer is greater than the pivot then decrease the index | |
// moving it towards the pivot point | |
while (this[right] > pivot) { | |
right-- | |
} | |
// if the left index is less than the right as it should be then | |
// then swap the values | |
if (left <= right) { | |
this.swap(left, right) | |
left++ | |
right-- | |
} | |
} | |
return left; | |
} | |
// default the sort command to use the length of the array | |
sort(left = 0, right = this.length - 1) { | |
let index | |
// this will recursively call until the partition is less than the index - 1 | |
// and the index is greater than right | |
if (this.length > 1) { | |
index = this.partition(left, right); | |
if (left < index - 1) { | |
this.sort(left, index - 1); | |
} | |
if (index < right) { | |
this.sort(index, right); | |
} | |
} | |
return this | |
} | |
} | |
var items = [4, 2, 6, 5, 3, 9, 10, 99, 8, 42, 36, 22, 21, 7, 12, 85, 87] | |
var q = new Quicksort(...items) | |
console.log(q.sort()) | |
// Quicksort [ 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 21, 22, 36, 42, 85, 87, 99 ] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment