Skip to content

Instantly share code, notes, and snippets.

@yoshikischmitz
Last active January 1, 2016 23:08
Show Gist options
  • Save yoshikischmitz/8214226 to your computer and use it in GitHub Desktop.
Save yoshikischmitz/8214226 to your computer and use it in GitHub Desktop.
Simple quicksort in Ruby, just as an exercise.
def quicksort(array, first = true)
if first == true
# if this is the first time quicksort is invoked
# we have to de-reference the array, as we use the
# destructive method delete_at
array = array.dup
end
if array.size <= 1
return array
end
pivot = array[rand(array.size)]
array.delete_at(array.index(pivot))
less, greater = [], []
array.each do |x|
if x <= pivot
less << x
else
greater << x
end
end
return [quicksort(less, false), pivot, quicksort(greater, false)].flatten
end
@array = Array.new(9).map { rand(99) }
puts "Unsorted array:\t#{@array}"
@sorted_array = quicksort(@array)
puts "Sorted array:\t\t#{@sorted_array}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment