#!/usr/bin/perl -w

package Search;

local $Search::numSteps = 0;

sub binarySearch(@$);
sub search(@$);

# binary search
sub binarySearch(@$) {
	my @array = @_;
	my $itemToFind = pop(@array);

	# First sort it
	my @sorted = sort { $a <=> $b } @array;

	return search(@sorted, $itemToFind);
}

sub search(@$) {
	my @array = @_;
	my $itemToFind = pop(@array);

	my $midpt = int(@array/2);
	@array or return undef; 
	++$Search::numSteps;
	my $comp = $array[$midpt] <=> $itemToFind;
	if ($comp < 0) {
		return search(@array[$midpt+1..$#array], $itemToFind);
	} elsif ($comp == 0) {
		return 1;
	} else {	# > 0
		return search(@array[0..$midpt-1], $itemToFind);
	}
}

sub getNumberOfComparisons() {
	return $Search::numSteps;
}

1;
