Skip to content

Instantly share code, notes, and snippets.

@StephanieSunshine
Last active August 29, 2015 14:23
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 StephanieSunshine/8fdb040dda9640632e94 to your computer and use it in GitHub Desktop.
Save StephanieSunshine/8fdb040dda9640632e94 to your computer and use it in GitHub Desktop.
A Quicksort in Ruby
#!/usr/bin/env ruby
require 'pp'
#Variables
maxElements = 100
randomLowNumber = -10000
randomHighNumber = 10000
def quickSort( toSort )
sorted = Array.new
# If the length is greater than 3 then split and recurse
if toSort.length > 2
#puts 'Array is bigger than 2, we need to reduce'
#Find pivot using the list average number
myPivot = toSort.reduce(:+) / toSort.length
#puts 'Average of array is ' + myPivot.to_s + ' Size of Array ' + toSort.length.to_s
myLowerArray = Array.new
myHigherArray = Array.new
toSort.each do |ele|
if ele > myPivot
myHigherArray.push ele
else
myLowerArray.push ele
end #end if
end #end do
#puts "Original: " + toSort.to_s
#puts "Lower: " + myLowerArray.to_s + " Higher: " + myHigherArray.to_s
return quickSort(myLowerArray) + quickSort(myHigherArray)
else
# Throw out the oddball
return toSort if toSort.length.eql?(1)
# Is the low number bigger than the higher?
return toSort.reverse if toSort[0] > toSort[1]
# If we haven't left yet, we don't need to do anything here
return toSort
end
end
# Generate test data
sortMe = Array.new(maxElements){ |i| Random.rand(randomLowNumber..randomHighNumber) }
pp quickSort( sortMe )
@StephanieSunshine
Copy link
Author

I wrote this as practice to a Google exam

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