Perl Program to Implement Binary Search

Perl Program to Implement Binary Search

Binary Search is a fast and efficient algorithm for finding an element in a sorted array. Unlike Linear Search, which checks each element one by one, Binary Search divides the array in half at every step, quickly narrowing down where the target might be. This makes it extremely useful for large datasets, as it can find values much faster than simple searching methods. Binary Search is widely used in applications such as searching in databases, looking up records, and even in coding challenges or algorithm-intensive programs.

For beginners in Perl, learning Binary Search is an important milestone. It introduces key concepts like array indexing, loops, recursion, and the power of the “divide and conquer” approach. By understanding Binary Search, programmers can build a strong foundation for more advanced algorithms and appreciate how efficiency in programming can make a big difference.

Program 1: Iterative Binary Search

This first program demonstrates Binary Search using a simple loop. It searches for a target value in a predefined sorted array.

use strict;
use warnings;

my @arr = (10, 20, 30, 40, 50, 60, 70);
my $target = 40;
my ($low, $high) = (0, $#arr);
my $found_index = -1;

while ($low <= $high) {

    my $mid = int(($low + $high) / 2);

    if ($arr[$mid] == $target) {
        $found_index = $mid;
        last;
    } elsif ($arr[$mid] < $target) {
        $low = $mid + 1;
    } else {
        $high = $mid - 1;
    }

}

if ($found_index != -1) {
    print "Element $target found at index $found_index\n";
} else {
    print "Element $target not found\n";
}

This iterative approach divides the search space in half each time. Beginners can see how adjusting the low and high pointers reduces the number of comparisons dramatically compared to checking every element.

Program 2: Recursive Binary Search

Binary Search can also be implemented recursively, which can be an elegant way to express the algorithm.

use strict;
use warnings;

sub binary_search {

    my ($arr_ref, $target, $low, $high) = @_;
    return -1 if $low > $high;

    my $mid = int(($low + $high) / 2);

    if ($arr_ref->[$mid] == $target) {
        return $mid;
    } elsif ($arr_ref->[$mid] < $target) {
        return binary_search($arr_ref, $target, $mid + 1, $high);
    } else {
        return binary_search($arr_ref, $target, $low, $mid - 1);
    }

}

my @arr = (5, 15, 25, 35, 45, 55);
my $target = 25;
my $index = binary_search(\@arr, $target, 0, $#arr);

if ($index != -1) {
    print "Element $target found at index $index\n";
} else {
    print "Element $target not found\n";
}

This recursive approach works by calling the same function with a smaller section of the array until the element is found or the search space is empty. Beginners can appreciate recursion and see how the “divide and conquer” principle works naturally in code.

Program 3: Binary Search as a subroutine with user-friendly input

In this program, Binary Search is wrapped in a subroutine that can be reused with any array or target value.

use strict;
use warnings;

sub binary_search {

    my ($arr_ref, $target) = @_;
    my ($low, $high) = (0, $#$arr_ref);

    while ($low <= $high) {

        my $mid = int(($low + $high) / 2);

        if ($arr_ref->[$mid] == $target) {
            return $mid;
        } elsif ($arr_ref->[$mid] < $target) {
            $low = $mid + 1;
        } else {
            $high = $mid - 1;
        }

    }

    return -1;

}

my @arr = (1, 3, 5, 7, 9, 11, 13);
my $target = 7;
my $result = binary_search(\@arr, $target);

if ($result != -1) {
    print "Element $target found at index $result\n";
} else {
    print "Element $target not found\n";
}

By creating a subroutine, the search logic becomes reusable and organized. Beginners can experiment with different arrays and targets without rewriting the loop or recursive code.

Program 4: Binary Search for negative numbers

Binary Search works naturally with negative numbers as long as the array is sorted. This example demonstrates searching for negative values.

use strict;
use warnings;

my @arr = (-50, -20, -10, 0, 10, 20, 30);
my $target = -10;
my ($low, $high) = (0, $#arr);
my $found_index = -1;

while ($low <= $high) {

    my $mid = int(($low + $high) / 2);

    if ($arr[$mid] == $target) {
        $found_index = $mid;
        last;
    } elsif ($arr[$mid] < $target) {
        $low = $mid + 1;
    } else {
        $high = $mid - 1;
    }

}

if ($found_index != -1) {
    print "Element $target found at index $found_index\n";
} else {
    print "Element $target not found\n";
}

Beginners can see that negative numbers do not affect the logic, as the algorithm relies only on comparisons between elements.

Program 5: Binary Search with floating-point numbers

This program demonstrates that Binary Search can also handle decimal values in a sorted array.

use strict;
use warnings;

my @arr = (0.5, 1.2, 2.8, 3.5, 4.9, 5.1);
my $target = 3.5;
my ($low, $high) = (0, $#arr);
my $found_index = -1;

while ($low <= $high) {

    my $mid = int(($low + $high) / 2);

    if ($arr[$mid] == $target) {
        $found_index = $mid;
        last;
    } elsif ($arr[$mid] < $target) {
        $low = $mid + 1;
    } else {
        $high = $mid - 1;
    }

}

if ($found_index != -1) {
    print "Element $target found at index $found_index\n";
} else {
    print "Element $target not found\n";
}

Binary Search works with floating-point numbers just like integers, as long as the array remains sorted. Beginners can experiment with decimals to understand numeric comparisons in Perl.

Frequently Asked Questions (FAQ)

This section answers common beginner questions about Binary Search in Perl.

Q1. What is the time complexity of Binary Search?
Binary Search has a time complexity of O(log n), which makes it much faster than Linear Search for large sorted arrays.

Q2. Can Binary Search handle unsorted arrays?
No, Binary Search requires the array to be sorted. For unsorted arrays, Linear Search is appropriate.

Q3. Is iterative or recursive Binary Search better?
Both are valid. Iterative is slightly more efficient in terms of memory, while recursive can be easier to understand for beginners.

Q4. Can Binary Search work with negative and floating-point numbers?
Yes, as long as the array is sorted, Binary Search works naturally with any numeric type.

Q5. When should I use Binary Search over Linear Search?
Use Binary Search for large, sorted datasets when speed is important. Linear Search is simpler but slower for large arrays.

Conclusion

Binary Search is a powerful and efficient searching algorithm that every beginner in Perl should learn. By repeatedly dividing the array in half, it finds elements quickly, making it ideal for large datasets. The programs in this article demonstrate multiple approaches, including iterative, recursive, subroutine-based, and support for negative and floating-point numbers.

Practicing these examples helps beginners understand both the logic behind searching algorithms and the importance of sorting in programming. With Binary Search, you gain a strong foundation for efficient coding, which can be applied to real-world applications and more advanced data structures.

Scroll to Top