Last active
August 29, 2015 14:23
-
-
Save StephanieSunshine/8fdb040dda9640632e94 to your computer and use it in GitHub Desktop.
A Quicksort in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I wrote this as practice to a Google exam