etheral has asked for the wisdom of the Perl Monks concerning the following question:
I have this code:
#################################################################### ## MAIN #################################################################### my @array = (1, 4, 4, 65, 100, 102); my $closest_element = @{closest_element(\@array)}[0]; print "The closest element to the element $element in the array (@arra +y) is the element $closest_element\n"; #################################################################### ## SUBS #################################################################### sub closest_element { #to execute a binary search on the closest eleme +nt of an input array my ($array) = @_; my $end = @$array; my $not_middle = int(($end-1) / 2); #compute $not_middle my $try = @$array[$not_middle]; #try an element return $try <= $element ? #return the closest element after having c +hecked the below statements (abs($try-$element)<abs(@$array[$not_middle+1]-$element) ? [$try] : $element <= @$array[$not_middle+1] ? [@$array[$not_middle+1]] : closest_element([@$array[$not_middle+1 .. $end-1]])) : (abs($try-$element)<abs(@$array[$not_middle-1]-$element) ? [$try] : $element >= @$array[$not_middle-1] ? [@$array[$not_middle-1]] : closest_element([@$array[0 .. $not_middle]])); }
It works perfectly, but instead of returning a value (for eg. element closest to 35 is 65 - that's what the program returns right now) I'd like to return an index (so if my search element is 35, the program should return an index of an element 65, which is 3). I can't do that by any means possible, please help me:) Thanks!
ps
Perhaps I should write this: I'm quite blue with perl (the above code took me 2 days to write). Guide me if you can step by step, thanks!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: binary search closest element index
by ikegami (Patriarch) on Sep 24, 2011 at 16:18 UTC |