Skip to content

Commit 6f701cb

Browse files
authored
Add Binary Search in Perl (#5086)
1 parent ba8ad8d commit 6f701cb

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed

archive/p/perl/binary-search.pl

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
#!/usr/bin/env perl
2+
use strict;
3+
use warnings;
4+
5+
sub handle_error {
6+
print "Usage: please provide a list of sorted integers (\"1, 4, 5, 11, 12\") and the integer to find (\"11\")\n";
7+
exit(0);
8+
}
9+
10+
sub check {
11+
my ($s) = @_;
12+
13+
# Trim leading and trailing spaces
14+
$s =~ s/^\s+//;
15+
$s =~ s/\s+$//;
16+
17+
# Check if there are spaces in the middle
18+
if ($s =~ /\s/) {
19+
handle_error();
20+
}
21+
22+
# Check if it's a valid integer
23+
if ($s !~ /^-?\d+$/) {
24+
handle_error();
25+
}
26+
27+
return int($s);
28+
}
29+
30+
sub convert {
31+
my ($s) = @_;
32+
33+
if (length($s) == 0) {
34+
handle_error();
35+
}
36+
37+
my @v;
38+
my @parts = split(',', $s);
39+
40+
foreach my $part (@parts) {
41+
push @v, check($part);
42+
}
43+
44+
return @v;
45+
}
46+
47+
# Main program
48+
if (@ARGV < 2) {
49+
handle_error();
50+
}
51+
52+
my @v = convert($ARGV[0]);
53+
my $num = check($ARGV[1]);
54+
55+
# Check if array is sorted
56+
for (my $i = 0; $i < @v - 1; $i++) {
57+
if ($v[$i] > $v[$i + 1]) {
58+
handle_error();
59+
}
60+
}
61+
62+
# Binary search
63+
my $start = 0;
64+
my $end = scalar(@v);
65+
my $ans = "false";
66+
67+
while ($start < $end) {
68+
my $mid = int(($start + $end) / 2);
69+
70+
if ($num < $v[$mid]) {
71+
$end = $mid;
72+
}
73+
elsif ($v[$mid] < $num) {
74+
$start = $mid + 1;
75+
}
76+
elsif ($v[$mid] == $num) {
77+
$ans = "true";
78+
last;
79+
}
80+
}
81+
82+
print "$ans\n";

0 commit comments

Comments
 (0)