Yes you can do a binary search. Yet is will find the correct placement faster for large lists. In fact I have a module on cpan called File::SortedSeek that implements binary searches in large files so I appreciate the algorithm :-) However in this scenario having found the index you then have a practical problem. It is not possible to insert a value into the middle of an array, which is really just a contiguous sequence of SV* What you have to do is make space for it. Splice does that by moving a large chunk (or the entire array). The bubble algorithm also does it and is (in past testing) about twice as fast as just calling sort. Here is a binary search implementation. Benchmarking the options is left to you.

my @ary = (1..4, 6..10); for my $val( 0, 5, 11, 0, 5, 11 ) { binary( \@ary, $val ); print "@ary\n"; } sub binary { my ( $ary, $val ) = @_; my ( $min, $max, $last, $i ) = ( 0, scalar @{$ary}, 0, 0 ); while ( 1 ) { $i = int( ($min+$max)/2 ); # print "i=$i\n"; last if $last == $i; $last = $i; if ( $ary->[$i] < $val ) { $min = $i; } elsif ( $ary->[$i] > $val ) { $max = $i; } else { # values are equal so we have a valid index last; } } $i++ if $i; # for index 0 we want that, otherwise we want next p +osition splice @$ary, $i, 0, $val; } __DATA__ 0 1 2 3 4 6 7 8 9 10 0 1 2 3 4 5 6 7 8 9 10 0 1 2 3 4 5 6 7 8 9 10 11 0 0 1 2 3 4 5 6 7 8 9 10 11 0 0 1 2 3 4 5 5 6 7 8 9 10 11 0 0 1 2 3 4 5 5 6 7 8 9 10 11 11

cheers

tachyon


In reply to Re^3: Insert Into a Sorted Array by tachyon
in thread Insert Into a Sorted Array by ketema

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.