I'm trying to create a sorting algorithm without the sorting function in Ruby. I've based it of the idea of insertion sort. The idea is that the function checks whether the nth value of each two words are same, and if so n increases by one until one value is larger than the other. In that case the words might get switched. However, my function keeps freezing. Any ideas why?
words = ["my","favorite","animal", "are", "the", "elephant", "and", "the", "antelope", "and", "the", "favela"]
#Convert all letters into numbers. Output individual words as arrays.
converted_words = words.map(&:chars).map { |letters| letters.map { |letter| letter.to_i 36 } }
puts converted_words.to_s
i = 1
x = 0
while i < converted_words.length
if converted_words[i][x] == converted_words[i-1][x]
x = x + 1
else
if converted_words[i][x] < converted_words[i-1][x]
converted_words[i], converted_words[i-1] = converted_words[i-1], converted_words[i]
i = 0
x = 0
else
i = i + 1
end
end
end
puts converted_words.to_s
i, the function loops forever.i. And, yes, you have problems withx. Whenever you changei, you must resetx. Also, if you seti=0and then try to accessconverted_words[i-1][0], you're going off back end of the array. And you don't have a termination condition to stop at the end of a word. You need to fire up your debugger and single-step through your code to see where it's going off the rails.npasses over the array. That makes for an O(n^3) algorithm. Given a sufficiently large array, it wouldn't actually go into an infinite loop; it would just seem like an infinite loop.