Perl Program to Implement Merge Sort

Perl Program to Implement Merge Sort

Merge Sort is a powerful and efficient sorting algorithm that works much faster than simple algorithms like Bubble Sort or Insertion Sort when the data becomes large. The main idea behind Merge Sort is to divide a list into smaller parts, sort those parts, and then merge them back together in the correct order. Because it follows a clear divide-and-conquer approach, it is both reliable and predictable in performance.

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 how to implement Merge Sort in Perl is important because it introduces you to thinking in terms of recursion and problem breakdown. Merge Sort is widely used in real-world systems, database engines, and large-scale applications where speed matters. Even if you are a beginner, understanding Merge Sort will help you move from basic sorting ideas to more advanced algorithmic thinking.

Program 1: Basic Recursive Merge Sort in Perl

This first program shows the classic recursive implementation of Merge Sort. It splits the array into smaller halves, sorts each half, and then merges them back together. This is the most common way Merge Sort is taught.

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

sub merge_sort {

    my ($arr) = @_;
    return $arr if @$arr <= 1;

    my $mid = int(@$arr / 2);

    my $left  = merge_sort([ @$arr[0 .. $mid - 1] ]);
    my $right = merge_sort([ @$arr[$mid .. $#$arr] ]);

    return merge($left, $right);

}

sub merge {

    my ($left, $right) = @_;
    my @result;

    while (@$left && @$right) {

        if ($left->[0] <= $right->[0]) {
            push @result, shift @$left;
        } else {
            push @result, shift @$right;
        }

    }

    return [ @result, @$left, @$right ];

}

my @numbers = (38, 27, 43, 3, 9, 82, 10);
my $sorted = merge_sort(\@numbers);

print "Sorted array: @$sorted\n";

This program keeps dividing the array until each part has only one element. Then it merges those parts back together in sorted order. Beginners can focus on understanding the flow rather than memorizing every detail, since the idea of splitting and merging is the heart of Merge Sort.

Program 2: Merge Sort Using Array References

This version uses array references instead of passing full arrays around. It is useful for beginners who want to understand how references work in Perl.

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

sub merge_sort_ref {

    my ($arr_ref) = @_;
    return $arr_ref if @$arr_ref <= 1;

    my $mid = int(@$arr_ref / 2);
    my @left  = @$arr_ref[0 .. $mid - 1];
    my @right = @$arr_ref[$mid .. $#$arr_ref];

    my $left_ref  = merge_sort_ref(\@left);
    my $right_ref = merge_sort_ref(\@right);

    return merge_ref($left_ref, $right_ref);

}

sub merge_ref {

    my ($left, $right) = @_;
    my @result;

    while (@$left && @$right) {

        if ($left->[0] <= $right->[0]) {
            push @result, shift @$left;
        } else {
            push @result, shift @$right;
        }

    }

    push @result, @$left, @$right;
    return \@result;

}

my @numbers = (12, 11, 13, 5, 6, 7);
my $sorted_ref = merge_sort_ref(\@numbers);

print "Sorted array: @$sorted_ref\n";

This program behaves like the first one but uses references to manage memory more clearly. Beginners can learn how Perl handles references while still focusing on sorting logic. This approach is common in larger Perl applications.

Program 3: Merge Sort Wrapped in a Subroutine for Reuse

This version keeps everything clean and reusable by wrapping the full logic in a single callable subroutine. It is ideal for beginners writing modular code.

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

sub merge_sort_wrapper {

    my @data = @_;
    return @data if @data <= 1;

    my $mid = int(@data / 2);
    my @left = merge_sort_wrapper(@data[0 .. $mid - 1]);
    my @right = merge_sort_wrapper(@data[$mid .. $#data]);

    my @sorted;

    while (@left && @right) {
        push @sorted, ($left[0] < $right[0]) ? shift @left : shift @right;
    }

    return (@sorted, @left, @right);

}

my @numbers = (20, 18, 12, 8, 5, -2);
my @sorted = merge_sort_wrapper(@numbers);

print "Sorted array: @sorted\n";

This program highlights how Merge Sort can be written in a compact and readable way. Beginners can reuse this function in different programs without rewriting the logic. It also shows that negative numbers work naturally with Merge Sort.

Program 4: Bottom-Up Merge Sort Using Loops

This version avoids recursion and uses loops instead. It is helpful for beginners who are not yet comfortable with recursive thinking.

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

sub merge_arrays {

    my ($left, $right) = @_;
    my @result;

    while (@$left && @$right) {

        push @result, ($left->[0] <= $right->[0]) ? shift @$left : shift @$right;

    }

    push @result, @$left, @$right;
    return \@result;

}

my @numbers = (7, 6, 5, 4, 3, 2, 1);
my @lists = map { [$_] } @numbers;

while (@lists > 1) {

    my @merged;

    while (@lists) {

        my $left = shift @lists;
        my $right = shift @lists || [];
        push @merged, merge_arrays($left, $right);

    }

    @lists = @merged;

}

print "Sorted array: @{$lists[0]}\n";

This program starts by treating each element as a sorted list, then merges them step by step. It helps beginners understand that Merge Sort does not always require recursion. The logic remains the same even when the structure changes.

Program 5: Merge Sort for Nearly Sorted Data

This version shows that Merge Sort performs consistently even when data is almost sorted. Unlike simpler algorithms, its speed does not change much.

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

my @numbers = (1, 2, 3, 5, 4, 6, 7);

sub merge_sort_simple {

    my @arr = @_;
    return @arr if @arr <= 1;

    my $mid = int(@arr / 2);
    my @left = merge_sort_simple(@arr[0 .. $mid - 1]);
    my @right = merge_sort_simple(@arr[$mid .. $#arr]);

    my @merged;

    while (@left && @right) {
        push @merged, ($left[0] < $right[0]) ? shift @left : shift @right;
    }

    return (@merged, @left, @right);

}

my @sorted = merge_sort_simple(@numbers);
print "Sorted array: @sorted\n";

This program behaves the same way regardless of input order. Beginners can learn that Merge Sort is predictable and reliable, which is one of its biggest strengths in real-world systems.

Program 6: Merge Sort with Negative and Floating-Point Numbers

Merge Sort works perfectly with negative and floating-point numbers in Perl. This final program shows that no extra changes are needed.

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

my @numbers = (3.14, -2.5, 0, 1.1, -9.8, 4.6);

sub merge_sort_numbers {

    my @arr = @_;
    return @arr if @arr <= 1;

    my $mid = int(@arr / 2);
    my @left = merge_sort_numbers(@arr[0 .. $mid - 1]);
    my @right = merge_sort_numbers(@arr[$mid .. $#arr]);

    my @result;

    while (@left && @right) {
        push @result, ($left[0] <= $right[0]) ? shift @left : shift @right;
    }

    return (@result, @left, @right);

}

my @sorted = merge_sort_numbers(@numbers);
print "Sorted array: @sorted\n";

This program confirms that Perl handles numeric comparisons correctly. Beginners can confidently sort integers, decimals, and negative values using the same Merge Sort logic.

Frequently Asked Questions (FAQ)

This section answers common beginner questions about Merge Sort in Perl and helps clear up confusion.

Q1: Is Merge Sort better than Bubble Sort and Insertion Sort?
Merge Sort is much faster for large data sets and has predictable performance. It is usually preferred in real applications.

Q2: Why does Merge Sort use recursion so often?
Recursion makes it easier to divide the problem into smaller parts. It closely matches the natural idea behind Merge Sort.

Q3: Does Perl have built-in sorting already?
Yes, Perl has a built-in sort function that is optimized and recommended for everyday use. Merge Sort is mainly for learning.

Q4: Is Merge Sort stable?
Yes, Merge Sort is a stable sorting algorithm, which means it keeps the original order of equal elements.

Q5: Should beginners learn Merge Sort early?
Yes, learning Merge Sort helps beginners understand efficient algorithms and prepares them for more advanced topics.

Conclusion

Merge Sort is an important sorting algorithm that every beginner should understand, especially when learning Perl. It introduces powerful ideas like divide and conquer, recursion, and efficient data handling. Even though it is more complex than basic sorts, its reliability and speed make it very valuable.

By practicing these Perl Merge Sort programs, you will improve your confidence with arrays, functions, and algorithmic thinking. Once you understand Merge Sort, many other advanced algorithms will feel much easier. Keep practicing, stay curious, and enjoy growing your Perl programming skills.

Scroll to Top