我正在尝试实现二进制搜索。这是我的代码:
#!/usr/bin/perl
#use strict;
use warnings;
@array = (1..100);
$number = <STDIN>;
$low = 0;
$high = $#array;
while($low < $high){
print "Searcing $low ---- $high \n";
$mid = $low + ($high - $low)/2;
if($array[$mid] == $number){
print "Found in index:" . $mid;
last;
}
elsif($array[$mid] < $number){
$low = $mid + 1;
}
else{
$high = $mid - 1;
}
}
但它不起作用,尽管它是一个直接的实现(至少它会在 Java 中)。
似乎我在划分时得到浮点值并且无法搜索。如果我提供作为输入5
,我会得到垃圾:
5
Searcing 0 ---- 99
Searcing 0 ---- 48.5
Searcing 0 ---- 23.25
Searcing 0 ---- 10.625
Searcing 0 ---- 4.3125
Searcing 3.15625 ---- 4.3125
我怎样才能使它使用整数,以便我可以索引数组?
此外,如果我取消注释use strict
,我会收到以下错误。他们的意思是什么?
Global symbol "@array" requires explicit package name at D:\Development\Perl\chapter3\binarySearch.pl line 6.
Global symbol "$number" requires explicit package name at D:\Development\Perl\chapter3\binarySearch.pl line 9.
Global symbol "$low" requires explicit package name at