in reply to Re^2: Insert Into a Sorted Array
in thread Insert Into a Sorted Array

Here's your bin search. Worst case time for the search (not counting the splicing): O(log N)
sub compare { $a cmp $b } sub binsearch { # Returns the index of the position before # the one where $s would be found, when $s # is not found. my ($f, $s, $list) = @_; my $i = 0; my $j = $#$list; my $k; my $c; $a = $s; for (;;) { $k = int(($j-$i)/2) + $i; $b = $list->[$k]; $c = &$f(); return $k if ($c == 0); if ($c < 0) { $j = $k-1; return $j if ($i > $j); } else { $i = $k+1; return $k if ($i > $j); } } } @a = qw( z b x c y a ); @b = qw( o m n ); @a = sort compare @a; @b = sort compare @b; splice(@a, binsearch(\&compare, $b[0], \@a)+1, 0, @b); print(@a); # abcmnoxyz

Of course, in your case, it will be
splice(@known, binsearch(\&byIndex, $newValue, \@known)+1, 0, $newValue);

Update: Passing array to binsearch using a reference now. oops!

Replies are listed 'Best First'.
Re^4: Insert Into a Sorted Array
by tachyon (Chancellor) on Sep 29, 2004 at 04:03 UTC

    Passing @a not \@a means that perl copies the entire array to the function for no reason, and thus loses a lot of the potential efficiency.

Re^4: Insert Into a Sorted Array
by ketema (Scribe) on Sep 29, 2004 at 03:33 UTC
    This is the fastest, especially on a 10,000 record file.
    Oh I wanted to give thanks to all of you who helped me earlier on Figuring out how to embed c into PERL. Still not perfect at it, but i got it to work for what I need. Thanks Again to all you Wise monks. Ketema