Skip to content

Instantly share code, notes, and snippets.

@cnocon
Created September 12, 2013 12:47
Show Gist options
  • Save cnocon/6536738 to your computer and use it in GitHub Desktop.
Save cnocon/6536738 to your computer and use it in GitHub Desktop.
My recursive sort exercise. I updated it to display the end result slightly neater than was asked for in the book.
start_array = []
puts "Enter as many words as you like, pressing Enter after each word has been input. type 'stop' to finish entering words."
while true
x = gets.chomp #had to put this within the while loop for code to work, not outside while loop
if x != "stop"
start_array.push x
else
def sort start_array # This "wraps" recursive_sort.
recursive_sort start_array, []
end
def recursive_sort unsorted, sorted
if unsorted.length <= 0 #if there's nothing left to sort
return sorted
end
smallest = unsorted.pop
still_unsorted = [] #a place for rejects to go
unsorted.each do |test_word|
if test_word < smallest
still_unsorted.push smallest
smallest = test_word
else
still_unsorted.push test_word
end
end
#now smallest points to the smallest word from the group of start array items left to sort
sorted.push smallest #remove the smallest from the recursive process and put it in its place in the sorted array
recursive_sort still_unsorted, sorted #now we pass the still unsorted numbers back to the method in the same way
end
puts "Your sorted array:"
final_array = sort(start_array)
final_array.each do |y|
if y == final_array[-1]
puts y
break
else
print y + ', '
end
end
break
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment