teaflavored - 10 months ago 40

Ruby Question

I'm trying to do array practice problems and I'm working on insertion sort right now. I'm wondering whether this code is clear and readable. To me it looks kind of confusing, if anyone has a cleaner way(easier to understand) to implement this can you help me please?

`def insertion_sort(arr)`

(1...arr.length).each do |i| #iterate through array go through every element

j=i-1 #to check all elements behind i

while(j>=0&&arr[i]<arr[j]) #while not out bounds and current element is less than previous

temp=arr[i] #3 lines to switch arr[i] and arr[j]

arr[i]=arr[j]

arr[j]=temp

i=j #keep track of where i is

j-=1 #decrease j by 1 to check the previous element

end

end

return arr

end

Answer

This probably has its own issues, but you can see a couple simplifications here to *hopefully* make the code more readable.

```
class Array
def swap(a, b)
self[a], self[b] = self[b], self[a]
end
end
def insertion_sort(arr)
(1...arr.size).each do |i|
i.downto(1).each do |j|
break if arr[j] >= arr[j - 1]
arr.swap(j, j - 1)
end
end
arr
end
```

Source (Stackoverflow)