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!


In reply to binary search closest element index by etheral

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.