Skip to content

Instantly share code, notes, and snippets.

@prestonp
Last active August 29, 2015 13:56
Show Gist options
  • Save prestonp/9010789 to your computer and use it in GitHub Desktop.
Save prestonp/9010789 to your computer and use it in GitHub Desktop.
underscore quicksort

Save and run as sort.js with a list of integers as arguments

node sort.js 1 3 2 9 3 22

output

[ 1, 2, 3, 3, 9, 22 ]

source

var _ = require('underscore');

var quicksort = function(list) {
  if (list.length === 0)
    return [];
  var p = list[0]; // pivot
  var rest = list.slice(1);

  var lesser = _.filter(rest, function(x) {
    return x<p;
  });

  var greater = _.filter(rest, function(x) {
    return x>=p;
  });
  return quicksort(lesser).concat(p, quicksort(greater));
};

var list = Array.prototype.slice.call(process.argv, 2)
            .map(function(num) {
              return parseInt(num);
            });

console.log(quicksort(list));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment