Perlで二分探索
ねむいです。
#!/usr/bin/env perl use strict; use warnings; my @array = qw/1 3 5 11 12 13 17 22 25 28/; print bs($_, \@array), "\n" for qw/25 4 29/; if(@ARGV){ print "search for ", join(', ', @array), "\n"; for my $n (@ARGV){ printf "%d is %s.\n", $n, bs($n, \@array) ? 'found' : 'not found'; } } sub bs { my ($search_number, $list) = @_; my ($start, $end) = (0, $#{$list}); return 0 if $search_number < $list->[$start]; return 0 if $search_number > $list->[$end]; while(1){ my $center = ($start + $end) >> 1; if($list->[$center] == $search_number){ return 1; #found } $start = $center + 1 if $list->[$center] < $search_number; $end = $center - 1 if $list->[$center] > $search_number; last if $start > $end; last if $end < $start; } return 0; }