Ruby- sort without using sort method


#1

Hi everyone,

I finished the exercise in fundamentals 101 where you need to sort strings without using the sort method in ruby.

Even thought I got it to work through trial and error, I’m still a bit fuzzy on the logic. Code is below.

> while (i < array.length)
>     sorted_array.each do |ele|
>         if (array[i] < ele)
>             sorted_array.insert(sorted_array.find_index(ele), array[i])
>             break if array[i] <= ele
>         else
>             if (array[i] > sorted_array[j])
>                 sorted_array.insert(j, array[i])
>                 break if array[i] > sorted_array[j]
>             end
>         end
>     end
>     i += 1
> end

Under the 1st if condition, I originally had it at “if (array[i] <= ele)”. This caused the last string in the array to be repeated. Looked through the logic and can’t see why this is. Can anyone shed light on this. Would be much appreciated.


#2

Hi @fffear

Happy to have a look at you. What would be really helpful is if you could get the broken code up and running in https://repl.it/ or similar and then share that as then we can see the code running live.


#3

Hi @CouchofTomato,

Link attached.


#4

I think it’s because you are iterating sorted_array using each but also pushing to it during that iteration which is messing up the internal indexing it uses. You shouldn’t both iterate something and change it during the iteration.