Created
April 21, 2010 00:10
-
-
Save cowens/373254 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
use strict; | |
use warnings; | |
sub bsearch { | |
my $item = shift; | |
my @a = @_; | |
my $offset = 0; | |
while (@a) { | |
my $mid = int(@a/2); | |
return $mid + $offset if $item == $a[$mid]; | |
if ($item < $a[$mid]) { | |
@a = @a[0 .. ($mid - 1)]; | |
} else { | |
$offset += $mid + 1; | |
@a = @a[($mid + 1) .. $#a]; | |
} | |
} | |
return undef; | |
} | |
my @a = sort { $a <=> $b } map { int rand 100 } 1 .. 0; | |
print join(", ", @a), "\n"; | |
while (my $num = <>) { | |
chomp $num; | |
my $pos = bsearch $num, @a; | |
print defined $pos ? | |
"found $num at $pos: $a[$pos]\n" : | |
"didn't find $num\n"; | |
} | |
#for my $i (0 .. $#a) { | |
# my $j = bsearch $a[$i], @a; | |
# die "oops at $i (got $j)" if $a[$i] != $a[$j]; | |
#} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment