Perl Program to Implement Heap Sort

Perl Program to Implement Heap Sort

Heap Sort is a powerful and efficient sorting algorithm that is commonly taught after beginners learn simpler sorting methods. The idea behind Heap Sort comes from a data structure called a heap, which is a special kind of binary tree. In Heap Sort, the largest or smallest value is always kept at the top, making it easy to place elements in the correct order one by one. Because of this structure, Heap Sort performs well even when the data set becomes large.

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 Heap Sort in Perl is important because it helps you understand how advanced sorting works without relying on recursion-heavy approaches like Merge Sort or Quick Sort. Heap Sort is used in systems where consistent performance is required, such as priority queues, scheduling systems, and memory management tasks. Even though it looks complex at first, breaking it down step by step makes it very manageable for beginners.

Program 1: Basic Heap Sort Using Loops in Perl

This first program shows the standard Heap Sort implementation using loops only. It builds a max heap and then repeatedly extracts the largest value to sort the array. This version is great for beginners who want to understand the core idea clearly.

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

sub heapify {

    my ($arr, $n, $i) = @_;
    my $largest = $i;
    my $left = 2 * $i + 1;
    my $right = 2 * $i + 2;

    if ($left < $n && $arr->[$left] > $arr->[$largest]) {
        $largest = $left;
    }

    if ($right < $n && $arr->[$right] > $arr->[$largest]) {
        $largest = $right;
    }

    if ($largest != $i) {
        ($arr->[$i], $arr->[$largest]) = ($arr->[$largest], $arr->[$i]);
        heapify($arr, $n, $largest);
    }

}

sub heap_sort {

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

    for (my $i = int($n / 2) - 1; $i >= 0; $i--) {
        heapify($arr, $n, $i);
    }

    for (my $i = $n - 1; $i > 0; $i--) {
        ($arr->[0], $arr->[$i]) = ($arr->[$i], $arr->[0]);
        heapify($arr, $i, 0);
    }

}

my @numbers = (12, 11, 13, 5, 6, 7);
heap_sort(\@numbers);

print "Sorted array: @numbers\n";

This program first converts the array into a max heap, where the largest value sits at the top. It then swaps the largest value with the last element and reduces the heap size. Beginners can focus on understanding how values move from the heap into their final sorted positions.

Program 2: Heap Sort Using a Clearer Heapify Function

This version improves readability by making the heapify process easier to follow. It helps beginners who want to understand each comparison more clearly.

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

sub heapify {

    my ($arr, $size, $root) = @_;
    my $largest = $root;

    my $left_child = 2 * $root + 1;
    my $right_child = 2 * $root + 2;

    if ($left_child < $size && $arr->[$left_child] > $arr->[$largest]) {
        $largest = $left_child;
    }

    if ($right_child < $size && $arr->[$right_child] > $arr->[$largest]) {
        $largest = $right_child;
    }

    if ($largest != $root) {
        ($arr->[$root], $arr->[$largest]) = ($arr->[$largest], $arr->[$root]);
        heapify($arr, $size, $largest);
    }

}

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

for (my $i = int($n / 2) - 1; $i >= 0; $i--) {
    heapify(\@numbers, $n, $i);
}

for (my $i = $n - 1; $i > 0; $i--) {
    ($numbers[0], $numbers[$i]) = ($numbers[$i], $numbers[0]);
    heapify(\@numbers, $i, 0);
}

print "Sorted array: @numbers\n";

This program separates heap construction and sorting more clearly. Beginners can trace how each node compares with its children. This makes the heap structure easier to understand step by step.

Program 3: Heap Sort Wrapped in a Reusable Subroutine

This program places all the logic inside reusable subroutines. It is useful for beginners who want clean and modular Perl code.

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

sub heap_sort {

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

    for (my $i = int($n / 2) - 1; $i >= 0; $i--) {
        heapify(\@arr, $n, $i);
    }

    for (my $i = $n - 1; $i > 0; $i--) {
        ($arr[0], $arr[$i]) = ($arr[$i], $arr[0]);
        heapify(\@arr, $i, 0);
    }

    return @arr;

}

sub heapify {

    my ($arr, $n, $i) = @_;
    my $largest = $i;
    my $l = 2 * $i + 1;
    my $r = 2 * $i + 2;

    if ($l < $n && $arr->[$l] > $arr->[$largest]) {
        $largest = $l;
    }

    if ($r < $n && $arr->[$r] > $arr->[$largest]) {
        $largest = $r;
    }

    if ($largest != $i) {
        ($arr->[$i], $arr->[$largest]) = ($arr->[$largest], $arr->[$i]);
        heapify($arr, $n, $largest);
    }

}

my @numbers = (9, 8, 7, 6, 5);
my @sorted = heap_sort(@numbers);

print "Sorted array: @sorted\n";

This approach makes the code reusable and easier to maintain. Beginners learn how sorting logic can be separated from the main program. This is an important step toward writing professional-quality Perl code.

Program 4: Heap Sort Explained with Step-by-Step Heap Building

This version focuses on clarity and learning rather than speed. It shows Heap Sort in a very readable way.

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

sub heapify {

    my ($arr, $n, $i) = @_;
    my $largest = $i;

    my $left = 2 * $i + 1;
    my $right = 2 * $i + 2;

    if ($left < $n && $arr->[$left] > $arr->[$largest]) {
        $largest = $left;
    }

    if ($right < $n && $arr->[$right] > $arr->[$largest]) {
        $largest = $right;
    }

    if ($largest != $i) {
        ($arr->[$i], $arr->[$largest]) = ($arr->[$largest], $arr->[$i]);
        heapify($arr, $n, $largest);
    }

}

my @numbers = (16, 14, 10, 8, 7, 9, 3, 2, 4, 1);
my $n = scalar @numbers;

for (my $i = int($n / 2) - 1; $i >= 0; $i--) {
    heapify(\@numbers, $n, $i);
}

for (my $i = $n - 1; $i >= 0; $i--) {
    ($numbers[0], $numbers[$i]) = ($numbers[$i], $numbers[0]);
    heapify(\@numbers, $i, 0);
}

print "Sorted array: @numbers\n";

This program is ideal for learning how a heap is built before sorting begins. Beginners can study how the tree-like structure is maintained. Understanding this makes Heap Sort much less intimidating.

Program 5: Heap Sort with Negative Numbers

Heap Sort works perfectly with negative numbers because comparisons still behave the same way. This program demonstrates that behavior clearly.

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

my @numbers = (3, -1, -7, 8, 2, -5);

sub heapify {

    my ($arr, $n, $i) = @_;
    my $largest = $i;

    my $left = 2 * $i + 1;
    my $right = 2 * $i + 2;

    if ($left < $n && $arr->[$left] > $arr->[$largest]) {
        $largest = $left;
    }

    if ($right < $n && $arr->[$right] > $arr->[$largest]) {
        $largest = $right;
    }

    if ($largest != $i) {
        ($arr->[$i], $arr->[$largest]) = ($arr->[$largest], $arr->[$i]);
        heapify($arr, $n, $largest);
    }

}

my $n = scalar @numbers;

for (my $i = int($n / 2) - 1; $i >= 0; $i--) {
    heapify(\@numbers, $n, $i);
}

for (my $i = $n - 1; $i > 0; $i--) {
    ($numbers[0], $numbers[$i]) = ($numbers[$i], $numbers[0]);
    heapify(\@numbers, $i, 0);
}

print "Sorted array: @numbers\n";

This program shows that Heap Sort does not need special handling for negative values. Beginners can confidently sort mixed numeric data using the same logic.

Program 6: Heap Sort with Floating-Point Numbers

Heap Sort also handles floating-point numbers without any changes. This final program proves that the algorithm works smoothly with decimal values.

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

my @numbers = (3.5, 1.2, -4.8, 0.0, 2.9);

sub heapify {

    my ($arr, $n, $i) = @_;
    my $largest = $i;

    my $left = 2 * $i + 1;
    my $right = 2 * $i + 2;

    if ($left < $n && $arr->[$left] > $arr->[$largest]) {
        $largest = $left;
    }

    if ($right < $n && $arr->[$right] > $arr->[$largest]) {
        $largest = $right;
    }

    if ($largest != $i) {
        ($arr->[$i], $arr->[$largest]) = ($arr->[$largest], $arr->[$i]);
        heapify($arr, $n, $largest);
    }

}

my $n = scalar @numbers;

for (my $i = int($n / 2) - 1; $i >= 0; $i--) {
    heapify(\@numbers, $n, $i);
}

for (my $i = $n - 1; $i > 0; $i--) {
    ($numbers[0], $numbers[$i]) = ($numbers[$i], $numbers[0]);
    heapify(\@numbers, $i, 0);
}

print "Sorted array: @numbers\n";

This program confirms that Perl compares floating-point numbers correctly. Beginners do not need extra logic to support decimals when using Heap Sort.

Frequently Asked Questions (FAQ)

This section answers common beginner questions about Heap Sort in Perl. These answers help remove confusion and strengthen understanding.

Q1: Is Heap Sort faster than Quick Sort?
Heap Sort has consistent performance, but Quick Sort is often faster in practice. Heap Sort is preferred when predictable speed is required.

Q2: Does Heap Sort use recursion?
Heap Sort mainly uses loops, but heapify can be written recursively. It does not rely heavily on recursion like Merge Sort.

Q3: Is Heap Sort stable?
Heap Sort is not stable by default, which means equal values may change order during sorting.

Q4: Does Perl provide Heap Sort by default?
Perl provides a built-in sort function that is optimized and easier to use. Heap Sort is mainly for learning purposes.

Q5: Should beginners learn Heap Sort?
Yes, Heap Sort teaches important concepts like heaps and tree-based thinking. It is very useful for understanding advanced algorithms.

Conclusion

Heap Sort is a strong and reliable sorting algorithm that performs well even with large datasets. By learning how to implement Heap Sort in Perl, beginners gain exposure to heap structures, efficient sorting, and advanced algorithmic thinking. Although it may seem complex at first, breaking it down into heap building and sorting makes it much easier to understand.

Practicing these Perl Heap Sort programs will improve your confidence with arrays, loops, and comparisons. Once you understand Heap Sort, many other advanced topics in computer science will feel more approachable. Keep practicing, stay patient, and enjoy your progress as you grow your Perl programming skills.

Scroll to Top