Skip to content

Instantly share code, notes, and snippets.

@bil-bas
Last active May 6, 2019 01:51
Show Gist options
  • Save bil-bas/6107183 to your computer and use it in GitHub Desktop.
Save bil-bas/6107183 to your computer and use it in GitHub Desktop.
Ruby quicksort
module Enumerable
def quicksort()
if size <= 1
self
else
pivot = shift
lower, greater = partition {|x| x < pivot }.map(&:quicksort)
lower.push(pivot).concat(greater)
end
end
end
@syntacticsugar
Copy link

hm, the following JS port does not work. it returns a strangely scrambled list with one member less.

function quicksort(list) {
  if (list.length <= 1) {
    return list;
  }
  else {
    var pivot = list.shift();
    var lower = list.filter(function(element) {
      return element < pivot;
    });
    var upper = list.filter(function(element) {
      return element > pivot;
    });
    lower.push(pivot) //.concat(upper);
    return lower.concat(upper);
  }
}

/* quicksort([23,74,2,8,21,2,9]) =>[ 2,
  8,
  21,
  2,
  9,
  23,
  74 ]

> quicksort([2,1,3])
[ 1, 2, 3 ]
> quicksort([4,1,3,2])
[ 1, 3, 2, 4 ]
*/

@bil-bas
Copy link
Author

bil-bas commented Jul 29, 2013

You need >= in the upper check, otherwise if the pivot is duplicated, then the other values that are the same will be dropped.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment