[Shootout-list] Ruby heapsort correction

Jabari Zakiya jzakiya@mail.com
Wed, 06 Apr 2005 23:10:45 -0500


Correction for Ruby heapsort benchmark.

Problem:

The listed Ruby heapsort code crashed because in Ruby arrays
are zero-index based. For array.length=3DN, indices are 0--(N-1).

heapsort(N, ary) caused internal reference to ary[N], which
doesn't exist for array of length N, producing a 'nil' value.

Also in print line: printf "%.10f\n", ary.at(N)
ary.at(N) returns 'nil', again, because ary[N] doesn't exist.

Solutions:

1)Simplest solution, without touching heapsort code, do:

heapsort(N-1, ary)
printf "%.10f\n", ary.at(N-1): or more generic and Rubyish:
printf "%.10f\n", ary.last

2)Or in heapsort code, change ir=3Dn to ir=3Dn-1, and then can do:
heapsort(N, ary)
printf "%.10f\n", ary.last
(This is my preference)

Will now produce correct results when run from command line:

ruby heapsort.rb 1000
0.9990640718

ruby heapsort.rb 100_000
0.9999928555

Jabari Zakiya

--=20
___________________________________________________________
Sign-up for Ads Free at Mail.com
http://promo.mail.com/adsfreejump.htm