I have an exercise in my programming book asking me to sort an array of strings in Ruby without using any of the built in sorting. What I have sorts the top 5 correctly but then just stops and I haven’t been able to figure out why. Here is what I have so far:
numbers = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']
def sortArray myArray
recursiveSort myArray, []
end
def recursiveSort myArray, sortedArray
trashArray = myArray
myArray.each do |num|
largest = num
trashArray.each do |comp|
if comp > largest
largest = comp
end
end
sortedArray.push(largest)
trashArray.delete_at(trashArray.index(largest))
end
puts sortedArray
end
sortArray numbers
Here’s an example of what’s happening. From my terminal:
Your variables
trashArrayandmyArrayare references to the same object in memory, so you’re removing items from myArray on the line:trashArray.delete_at(trashArray.index(largest)).