I suspect you're var is getting incremented past the size of the array

You should add some puts statements around lines 14-15
and see how the value of var changes, and how it compares to the length
of unsorted.

cheers