How would you sort list in Python and array in Ruby like:
["car", "z", "9", "bus", "3"]
to have this array in return:
["bus", "car", "3", "z", "9"]
I've started building it in Ruby, because I know it better. I tried .sort with no parameters. Then I started writing Insertion sort with hopes I will rebuild it to my order and wrote this method.
def sort
@array.each do |value|
index = @array.index(value)
i = index - 1
while i >= 0
if value < @array[i]
@array[i + 1] = @array[i]
@array[i] = value
elsif (value =~ /\d/) == 0
# I wanted to do something here, whenever it stops at number to word comparison but didn't come up with anything workable
else
break
end
end
end
end
All I can get is ["3", "9", "bus", "car", "z"] But that's a code challenge I have to complete and the goal is to sort the array of strings in alphabetical and numerical order keeping keeping numeric strings indexes as in original array, just putting them in ascending order. I was thinking to create 2 hashes for numbers with and words having their keys as indexes in original array and sort just the values, and then inject them in correct order in a new array, but wasn't able to write the code for it and still not sure if that would be the best idea.
"3"
should be sorted before"z"
, but"9"
comes after. I see no logical progression here. – Martijn Pieters Nov 5 '14 at 11:54partition
the array. 3. Sort each partition. 4.insert
numeric elements back in. – Mark Thomas Nov 5 '14 at 15:17