Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
use two methods that call each other to sort penguins with quicksort in an alternating fashion
##
# This is a demonstration of a valid reason for having two methods that call each other.
# It is part of a response to a queuestion online
# https://softwareengineering.stackexchange.com/questions/376333/is-2-methods-calling-each-other-code-smell/377660#377660
#
# See a video of me making this at https://youtu.be/YugJV21W91A
#
# we are using recursion to implement quicksort.
# The sort is implemented two slightly different ways
# and each way calls the other to do the next level down the tree.
#
# imagine we're sorting penguins by height
def quicksort_pop(penguins)
return penguins if penguins.length <= 1
pivot = penguins.pop
left = []
right = []
while penguins.any?
penguin = penguins.pop
(penguin < pivot) ? left << penguin : right << penguin
end
quicksort_shift(left) + [pivot] + quicksort_shift(right)
end
def quicksort_shift(penguins)
return penguins if penguins.length <= 1
pivot = penguins.shift
left = []
right = []
while penguins.any?
penguin = penguins.shift
(penguin < pivot) ? left << penguin : right << penguin
end
quicksort_pop(left) + [pivot] + quicksort_pop(right)
end
def get_penguin_heights
puts 'Those are nice penguins'
puts 'Please tell me each of their heights (comma seperated ints)...'
heights = gets.chomp
heights.split(',').map{ |height| height.to_i }
end
def give_sorted_penguins(penguins)
puts "thank you! That's an awesome collection of penguins!"
puts "BTW, I put them in height order for you:"
puts penguins
favourite_index = Random.rand(penguins.length)
puts "My favourite is the one that's #{penguins[favourite_index]}cm tall,"
puts 'can I keep him?'
end
init_penguins = get_penguin_heights
sorted_penguins = quicksort_pop(init_penguins)
give_sorted_penguins(sorted_penguins)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.