#!/usr/bin/perl -w

# Binary search of an array

# Note that if you later on want to search for something from a
# list of values, you shouldn't have used an array in the first 
# place.

# Generating 100 integers
$NUM = 100;
$MAXINT = 5000;		# 1 + the maximum integer generated

srand();		# initialize the randomize seed

print "Numbers Generated:\n(";
for $i (1 .. $NUM) {
	push @array, sprintf("%d", rand(1) * $MAXINT);
	print $array[$i-1];
	print ", " unless ($i == $NUM);
}
print ")\n\n";

print "Please enter the number to search for >> ";
chomp($toSearch = <STDIN>);

# First sort it in ascending numerical order
@sortedArray = sort {$a <=> $b} @array;

# Binary search here
$counter = 0;
$start = 0; $end = $#sortedArray; $mid = 0; $hit = 0;
$mid = sprintf("%d", ($start + $end)/2);
while ($start <= $end) {
	$counter++;
	print "Searched: ", $sortedArray[$mid];		# which element is being searched
	print " in #[$start, $end] [";		# the subscript range
	print $sortedArray[$start], ", ", $sortedArray[$end], "] \n";
	if ($sortedArray[$mid] == $toSearch) {
		# a hit!
		print "\n\"$toSearch\" found!\n";
		$hit = 1;
		last;
	} elsif ($sortedArray[$mid] > $toSearch) {
		# decrease upper boundary -> mid value
		$end = $mid - 1;
	} else {
		# update lower boundary -> mid value
		$start = $mid + 1;
	}
	$mid = sprintf("%d", ($start + $end)/2);
}

if ($hit == 0) { print "\n\"$toSearch\" not found in array.\n"; }
print "Number of comparisons: ", $counter, "/", scalar(@sortedArray), "\n";

