kanwei / algorithms

Ruby algorithms and data structures. C extensions
http://kanwei.github.io/algorithms/
MIT License
2.67k stars 352 forks source link

Explicit return not required for containers containing < 2 elements for insertion sort #29

Closed Amit-Thawait closed 8 years ago

Amit-Thawait commented 8 years ago

If there are less than 2 elements then,

(1..container.size-1)

will resolve to either 1..1 or 1..0 which will cause the loop to not even execute, hence will return the container itself.

kanwei commented 8 years ago

(1..1).each { |x| puts "Hello" } does print Hello, so it would run in the case of size==1.

Amit-Thawait commented 8 years ago

Sorry @kanwei , my comment was slightly misleading. But my PR is still correct.

The statement return container if container.size < 2 will only return true for the case when container.size is either 0 or 1.

In those two case (1..container.size-1) will evaluate to 1..-1 & 1..0 which will cause the loop to not even execute, hence will return the container itself.

For container.size = 2, the code (1..container.size-1) will evaluate to 1..1 for which the loop will run once, and it is correct.