sub binary_search(@list, $item) {
my $low = 0; # low 和 high 用于跟踪要在其中查找的列表部分
my $high = @list.elems -1; #
while $low <= $high { # 只要范围没有缩小到只包含一个元素
my $mid = ($low + $high) / 2; # 就检查中间的元素
my $guess = @list[$mid];
return $mid if $guess == $item; # 找到了就返回
if $guess > $item { # 猜的数字大了
$high = $mid -1
} else { # 才的数字小了
$low = $mid + 1
}
}
}
my @list = [1, 3, 5, 7, 9];
say binary_search(@list, 3);
say binary_search(@list, -1);
comments powered by Disqus