The above comments are spot on, but it may still be instructive to see why your
rand method gave such poor results. The reason is that
sort wants a comparison result that's -1 (less than), 0 (equal), or 1 (greater than). In your program, only 0 and 1 can result from the comparison. If you substitute the three-way comparison operator
<=> for the
>=, you'll see a big improvement in the rearranging. (Granted,
rand(1) <=> 0.5 won't yield 0 very often, but that doesn't matter. What's important is that -1 and 1 occur with roughly equal preponderance.)
Update: Looks like belg4mit beat me to it!