Perl Program to Implement Bubble Sort

Perl Program to Implement Bubble Sort

Bubble Sort is one of the simplest sorting algorithms you can learn as a beginner. It works by comparing two nearby values and swapping them if they are in the wrong order. This process repeats again and again until the entire list becomes sorted. Because of this repeated swapping, the biggest values slowly move to the end, just like bubbles rising to the top of water. This simple idea makes Bubble Sort very easy to understand, even if it is not the fastest algorithm.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

Learning Bubble Sort in Perl is useful because Perl is still widely used for text processing, system scripts, and quick automation tasks. Understanding how sorting works at a basic level helps you think clearly about data, loops, and comparisons. Even though Bubble Sort is rarely used in real-world large systems, it is often taught first because it builds a strong foundation for learning better algorithms later.

Program 1: Basic Bubble Sort Using Nested Loops

This first program shows the most common and straightforward way to implement Bubble Sort in Perl. It uses two loops to repeatedly compare and swap values in an array. This approach is perfect for beginners who want to clearly see how the algorithm works step by step.

#!/usr/bin/perl
use strict;
use warnings;

my @numbers = (5, 1, 4, 2, 8);

my $n = scalar @numbers;

for (my $i = 0; $i < $n; $i++) {

    for (my $j = 0; $j < $n - $i - 1; $j++) {

        if ($numbers[$j] > $numbers[$j + 1]) {

            my $temp = $numbers[$j];
            $numbers[$j] = $numbers[$j + 1];
            $numbers[$j + 1] = $temp;

        }

    }

}

print "Sorted array: @numbers\n";

This program works by looping over the array many times and comparing two neighboring values. If the left value is bigger than the right one, they are swapped. Each pass pushes the largest unsorted number to the end. Beginners can easily follow this logic and understand how loops and conditions work together to sort data.

Program 2: Bubble Sort Using a While Loop

This version of Bubble Sort uses a while loop instead of a fixed number of passes. It keeps running until no swaps are needed anymore. This approach helps beginners understand how loops can depend on conditions instead of counters.

#!/usr/bin/perl
use strict;
use warnings;

my @numbers = (10, 3, 6, 2, 7);
my $swapped = 1;

while ($swapped) {

    $swapped = 0;

    for (my $i = 0; $i < $#numbers; $i++) {

        if ($numbers[$i] > $numbers[$i + 1]) {

            ($numbers[$i], $numbers[$i + 1]) = ($numbers[$i + 1], $numbers[$i]);

            $swapped = 1;

        }

    }

}

print "Sorted array: @numbers\n";

Here, the loop continues as long as swaps keep happening. Once the array is sorted, no swaps occur and the loop stops. This method is useful because it avoids unnecessary passes and shows beginners how a flag variable can control program flow.

Program 3: Bubble Sort Using Subroutines

This program moves the Bubble Sort logic into a subroutine. Using subroutines is an important skill in Perl because it helps keep code clean and reusable.

#!/usr/bin/perl
use strict;
use warnings;

sub bubble_sort {

    my @arr = @_;
    my $n = scalar @arr;

    for (my $i = 0; $i < $n; $i++) {

        for (my $j = 0; $j < $n - $i - 1; $j++) {

            if ($arr[$j] > $arr[$j + 1]) {
                ($arr[$j], $arr[$j + 1]) = ($arr[$j + 1], $arr[$j]);
            }

        }

    }

    return @arr;

}

my @numbers = (9, 4, 1, 7, 3);
my @sorted = bubble_sort(@numbers);

print "Sorted array: @sorted\n";

The main program sends data to the subroutine, and the subroutine returns the sorted result. This makes the code easier to read and reuse in other programs. Beginners learn how to break a problem into smaller parts, which is a very important programming habit.

Program 4: Recursive Bubble Sort in Perl

This version uses recursion, where a function calls itself. While recursion is not the best choice for Bubble Sort, it is useful for learning how recursive thinking works.

#!/usr/bin/perl
use strict;
use warnings;

sub bubble_sort_recursive {

    my ($arr_ref, $n) = @_;

    return if $n == 1;

    for (my $i = 0; $i < $n - 1; $i++) {

        if ($arr_ref->[$i] > $arr_ref->[$i + 1]) {
            ($arr_ref->[$i], $arr_ref->[$i + 1]) = ($arr_ref->[$i + 1], $arr_ref->[$i]);
        }

    }

    bubble_sort_recursive($arr_ref, $n - 1);

}

my @numbers = (6, 2, 8, 1, 5);
bubble_sort_recursive(\@numbers, scalar @numbers);

print "Sorted array: @numbers\n";

This program reduces the problem size each time the function runs. After pushing the largest value to the end, it sorts the remaining part of the array. Beginners should see this as a learning exercise to understand recursion rather than a practical sorting method.

Program 5: Optimized Bubble Sort with Early Exit

This program improves performance slightly by stopping early when the array is already sorted. This is a common optimization taught alongside Bubble Sort.

#!/usr/bin/perl
use strict;
use warnings;

my @numbers = (1, 2, 3, 4, 5);
my $n = scalar @numbers;

for (my $i = 0; $i < $n; $i++) {

    my $swapped = 0;

    for (my $j = 0; $j < $n - $i - 1; $j++) {

        if ($numbers[$j] > $numbers[$j + 1]) {

            ($numbers[$j], $numbers[$j + 1]) = ($numbers[$j + 1], $numbers[$j]);
            $swapped = 1;

        }

    }

    last if $swapped == 0;

}

print "Sorted array: @numbers\n";

If no swaps happen during a pass, the program stops immediately. This makes Bubble Sort faster for already sorted or nearly sorted data. Beginners can see how small changes can improve efficiency without changing the core idea.

Program 6: Bubble Sort Handling Negative and Floating-Point Numbers

Bubble Sort itself works with negative and floating-point numbers, but beginners often worry about comparisons. This program shows clearly that Perl handles these values correctly.

#!/usr/bin/perl
use strict;
use warnings;

my @numbers = (3.5, -2, 4.1, 0, -1.8);

my $n = scalar @numbers;

for (my $i = 0; $i < $n; $i++) {

    for (my $j = 0; $j < $n - $i - 1; $j++) {

        if ($numbers[$j] > $numbers[$j + 1]) {
            ($numbers[$j], $numbers[$j + 1]) = ($numbers[$j + 1], $numbers[$j]);
        }

    }

}

print "Sorted array: @numbers\n";

This program proves that Bubble Sort in Perl works the same way for integers, negative numbers, and decimals. Perl’s comparison operators handle these values naturally, so beginners do not need special logic.

Frequently Asked Questions (FAQ)

Below are some common questions beginners often ask when learning Bubble Sort in Perl. These answers are meant to clear confusion and build confidence.

Q1: Is Bubble Sort used in real applications?
Bubble Sort is rarely used in real systems because it is slow for large data. However, it is very popular in teaching because it is easy to understand and explain.

Q2: Why should I learn Bubble Sort if it is inefficient?
Bubble Sort teaches you how sorting works at a basic level. Once you understand it, learning faster algorithms like Quick Sort becomes much easier.

Q3: Does Perl have built-in sorting?
Yes, Perl has a built-in sort function that is much faster and more powerful. Bubble Sort is mainly for learning purposes, not replacement.

Q4: Can Bubble Sort sort strings in Perl?
Yes, it can sort strings if you change the comparison logic. However, Perl’s built-in sort is better for real string sorting.

Q5: Is recursion necessary for Bubble Sort?
No, recursion is not required. It is shown only as a learning exercise to understand recursive thinking.

Conclusion

Bubble Sort is a simple and friendly way to learn sorting algorithms, especially for beginners working with Perl. Through different programs, you can see how loops, conditions, subroutines, and recursion all solve the same problem in slightly different ways. Even though Bubble Sort is not the fastest option, it plays an important role in building strong programming basics.

By practicing these Perl programs and tweaking them, you will gain confidence in handling arrays, comparisons, and logic flow. Once you are comfortable with Bubble Sort, moving on to more advanced sorting algorithms will feel much easier. Keep experimenting, keep coding, and enjoy the learning journey.

Scroll to Top