Created
September 16, 2015 22:04
-
-
Save raymonstah/283d2a9cb74c4597e80e to your computer and use it in GitHub Desktop.
Quicksort in JS using FP & Recursion
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
// Raymond Ho | |
// This small script is just to demonstrate some functional programming feautures of Javascript. | |
// Quicksort! | |
// Anon function helper, will return a random number. | |
var randomNumber = function() { | |
return Math.floor(Math.random()*101); | |
} | |
// Create an array of 100 random numbers. | |
var numberArray = Array.apply(null, Array(100)).map(randomNumber); | |
var qs = function(list) { | |
// Edge condition (empty list) | |
if (list.length === 0) { | |
return []; | |
} | |
var smallerHalf = qs(list.slice(1,list.length).filter(function(value) { | |
return value <= list[0]; | |
})); | |
var biggerHalf = qs(list.slice(1,list.length).filter(function(value) { | |
return value > list[0]; | |
})); | |
return smallerHalf.concat([list[0]].concat(biggerHalf)); | |
} | |
// Makes sure our sorted array is actually the same as sort() | |
var ourSorted = qs(numberArray); | |
var jsSorted = numberArray.sort(function(a,b) { return a - b;} ); | |
var isSame = ourSorted.every(function(element,index){ | |
return element === jsSorted[index]; | |
}); | |
console.log('Our list is sorted:', isSame); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment