Skip to content

Instantly share code, notes, and snippets.

@paul-ylz
Last active April 29, 2018 09:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paul-ylz/f1d501da01471190cd4caf4a863715d5 to your computer and use it in GitHub Desktop.
Save paul-ylz/f1d501da01471190cd4caf4a863715d5 to your computer and use it in GitHub Desktop.
Quicksort in ruby
# Quicksort is a ruby implementation of the well-known algorithm
# https://en.wikipedia.org/wiki/Quicksort
class Quicksort
# sort will recursively run the partition function
# lo and hi identify the index range to be sorted
def sort(arr, lo, hi)
return unless lo < hi
pidx = partition(arr, lo, hi)
sort(arr, lo, pidx - 1)
sort(arr, pidx + 1, hi)
end
private
# partition rearranges the array so that all elements less than a pivot
# are on the left of it, and elements greater than the pivot are on the
# right. The pivot choice is arbitrary. This implementation uses the
# high index for a pivot.
def partition(arr, lo, hi)
pivot = arr[hi]
pidx = lo
(lo...hi).to_a.each do |i|
if arr[i] < pivot
arr[i], arr[pidx] = arr[pidx], arr[i]
pidx += 1
end
end
arr[pidx], arr[hi] = arr[hi], arr[pidx]
pidx
end
end
require "minitest/autorun"
class TestQuicksort < MiniTest::Test
def setup
@sort = Quicksort.new
end
def test_sorts_correctly
nums = [10, 9, 5, 9, 2.5, 2.6, 6]
sorted_nums = nums.sort
@sort.sort(nums, 0, nums.length - 1)
assert_equal sorted_nums, nums
end
def test_raises_when_array_is_frozen
nums = [10, 9, 5, 9, 2.5, 2.6, 6].freeze
assert_raises FrozenError do
@sort.sort(nums, 0, nums.length - 1)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment