Wednesday, August 27, 2014

Quicksort in Ruby

Just wanted to open up some code for examination and/or (hopefully) ridicule. Here's a recent quicksort implementation in Ruby that I threw together:

class Array
  def quick_sort
    return self if count < 2

    pivot = pop
    parts = partition { |x| x < pivot }

    [*parts.first.quick_sort, pivot, *parts.last.quick_sort]
  end
end

It's pretty straight-forward and Ruby's expressiveness really does cause the code to closely resemble the algorithm.

No comments:

Post a Comment