Perl Program to Implement Radix Sort

Perl Program to Implement Radix Sort

Radix Sort is a special sorting algorithm that works very differently from comparison-based sorts like Bubble Sort or Heap Sort. Instead of comparing numbers directly, Radix Sort looks at each digit of the numbers, starting from the least significant digit and moving toward the most significant one. By sorting numbers digit by digit, Radix Sort can achieve very fast performance for certain types of data.

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

This algorithm matters because it can sort numbers in linear time when the number of digits is limited. Radix Sort is often used in systems that deal with large volumes of numeric data, such as sorting IDs, phone numbers, or ZIP codes in places like Kenya, Zambia, or Nigeria. Learning how to implement Radix Sort in Perl helps beginners understand non-comparison sorting and builds strong algorithmic thinking.

Program 1: Basic Radix Sort Using Loops in Perl

This first program shows the most common way to implement Radix Sort using loops. It sorts positive integers by processing one digit at a time. This version is perfect for beginners seeing Radix Sort for the first time.

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

sub radix_sort {

    my @arr = @_;
    my $max = $arr[0];

    for my $num (@arr) {
        $max = $num if $num > $max;
    }

    for (my $exp = 1; int($max / $exp) > 0; $exp *= 10) {
        counting_sort(\@arr, $exp);
    }

    return @arr;

}

sub counting_sort {

    my ($arr, $exp) = @_;
    my @output = (0) x scalar(@$arr);
    my @count = (0) x 10;

    for my $num (@$arr) {
        my $index = int($num / $exp) % 10;
        $count[$index]++;
    }

    for (my $i = 1; $i < 10; $i++) {
        $count[$i] += $count[$i - 1];
    }

    for (my $i = @$arr - 1; $i >= 0; $i--) {
        my $index = int($arr->[$i] / $exp) % 10;
        $output[$count[$index] - 1] = $arr->[$i];
        $count[$index]--;
    }

    @$arr = @output;

}

my @numbers = (170, 45, 75, 90, 802, 24, 2, 66);
my @sorted = radix_sort(@numbers);

print "Sorted array: @sorted\n";

This program finds the largest number to know how many digits to process. It then uses Counting Sort internally for each digit position. Beginners can focus on the idea that numbers are grouped by digits rather than compared directly.

Program 2: Radix Sort with Clearer Variable Names

This version improves readability by using clearer variable names. It helps beginners understand what each part of the algorithm is doing.

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

sub radix_sort {

    my @data = @_;
    my $largest = 0;

    for my $value (@data) {
        $largest = $value if $value > $largest;
    }

    my $place = 1;

    while (int($largest / $place) > 0) {
        digit_sort(\@data, $place);
        $place *= 10;
    }

    return @data;

}

sub digit_sort {

    my ($data, $place) = @_;
    my @result;
    my @count = (0) x 10;

    for my $value (@$data) {
        my $digit = int($value / $place) % 10;
        $count[$digit]++;
    }

    for (my $i = 1; $i < 10; $i++) {
        $count[$i] += $count[$i - 1];
    }

    for (my $i = @$data - 1; $i >= 0; $i--) {
        my $digit = int($data->[$i] / $place) % 10;
        $result[$count[$digit] - 1] = $data->[$i];
        $count[$digit]--;
    }

    @$data = @result;

}

my @numbers = (329, 457, 657, 839, 436, 720, 355);
print "Sorted array: ", join(" ", radix_sort(@numbers)), "\n";

This program works the same way as the first one but is easier to read. Beginners benefit from meaningful variable names because they reduce confusion. This makes learning Radix Sort feel less overwhelming.

Program 3: Radix Sort Using Modular Design

This program focuses on clean structure by separating responsibilities into small functions. It is useful for beginners learning good coding habits.

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

sub get_max {

    my @arr = @_;
    my $max = $arr[0];

    for (@arr) {
        $max = $_ if $_ > $max;
    }

    return $max;

}

sub radix_sort {

    my @arr = @_;
    my $max = get_max(@arr);

    for (my $exp = 1; int($max / $exp) > 0; $exp *= 10) {
        counting_sort(\@arr, $exp);
    }

    return @arr;

}

sub counting_sort {

    my ($arr, $exp) = @_;
    my @count = (0) x 10;
    my @output = (0) x @$arr;

    for my $num (@$arr) {
        $count[int($num / $exp) % 10]++;
    }

    for (1 .. 9) {
        $count[$_] += $count[$_ - 1];
    }

    for (my $i = @$arr - 1; $i >= 0; $i--) {
        my $digit = int($arr->[$i] / $exp) % 10;
        $output[$count[$digit] - 1] = $arr->[$i];
        $count[$digit]--;
    }

    @$arr = @output;

}

my @numbers = (88, 410, 1772, 20, 5);
print "Sorted array: ", join(" ", radix_sort(@numbers)), "\n";

This approach teaches beginners how to break a problem into smaller parts. Each function has one clear purpose, which makes debugging and understanding easier. This style is common in real-world Perl programs.

Program 4: Radix Sort with Step-by-Step Digit Processing

This version is written for learning clarity rather than speed. It makes the digit-by-digit process very obvious.

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

my @numbers = (91, 46, 85, 15, 92, 35);

my $max = 0;

for (@numbers) {
    $max = $_ if $_ > $max;
}

my $exp = 1;

while (int($max / $exp) > 0) {

    my @buckets = map { [] } (0..9);

    for my $num (@numbers) {
        my $digit = int($num / $exp) % 10;
        push @{$buckets[$digit]}, $num;
    }

    @numbers = ();

    for my $bucket (@buckets) {
        push @numbers, @$bucket;
    }

    $exp *= 10;

}

print "Sorted array: @numbers\n";

This program uses buckets instead of counting arrays. Beginners can easily visualize numbers being placed into buckets based on digits. This makes Radix Sort feel more intuitive.

Program 5: Radix Sort Using Bucket Arrays

This version expands on the bucket idea and is very beginner-friendly. It avoids complex math as much as possible.

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

sub radix_sort {

    my @arr = @_;
    my $max = 0;

    for (@arr) {
        $max = $_ if $_ > $max;
    }

    my $exp = 1;

    while (int($max / $exp) > 0) {

        my @buckets = map { [] } (0..9);

        for my $value (@arr) {
            my $digit = int($value / $exp) % 10;
            push @{$buckets[$digit]}, $value;
        }

        @arr = map { @$_ } @buckets;
        $exp *= 10;

    }

    return @arr;
}

my @numbers = (300, 3, 34, 23, 122, 87);
print "Sorted array: ", join(" ", radix_sort(@numbers)), "\n";

This program is very readable and easy to follow. Beginners often prefer this style because it clearly shows how values move between buckets. It is excellent for learning purposes.

Program 6: Radix Sort with Larger Numbers

This program demonstrates Radix Sort with larger values. It proves that the algorithm scales well.

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

my @numbers = (1000, 500, 1234, 9999, 250, 75);

sub radix_sort {

    my @arr = @_;
    my $max = (sort { $a <=> $b } @arr)[-1];

    for (my $exp = 1; int($max / $exp) > 0; $exp *= 10) {

        my @count = (0) x 10;
        my @output;

        for (@arr) {
            $count[int($_ / $exp) % 10]++;
        }

        for (1 .. 9) {
            $count[$_] += $count[$_ - 1];
        }

        for (my $i = $#arr; $i >= 0; $i--) {
            my $digit = int($arr[$i] / $exp) % 10;
            $output[$count[$digit] - 1] = $arr[$i];
            $count[$digit]--;
        }

        @arr = @output;

    }

    return @arr;

}

print "Sorted array: ", join(" ", radix_sort(@numbers)), "\n";

This program reassures beginners that Radix Sort is reliable even for bigger numbers. The logic stays the same regardless of size. Only the number of digit passes changes.

Program 7: Radix Sort with Zero Values

This version shows that Radix Sort handles zero correctly. This is important for real-world data.

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

my @numbers = (0, 10, 100, 1, 0, 50);

sub radix_sort {

    my @arr = @_;
    my $max = 0;

    for (@arr) {
        $max = $_ if $_ > $max;
    }

    for (my $exp = 1; int($max / $exp) > 0; $exp *= 10) {

        my @buckets = map { [] } (0..9);

        for (@arr) {
            push @{$buckets[int($_ / $exp) % 10]}, $_;
        }

        @arr = map { @$_ } @buckets;

    }

    return @arr;

}

print "Sorted array: ", join(" ", radix_sort(@numbers)), "\n";

This program confirms that zero values do not break the algorithm. Beginners can safely use Radix Sort with datasets that include zeros.

Program 8: Radix Sort Explained with Inline Logic

This program keeps everything in one place. It is helpful for beginners who prefer fewer functions.

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

my @numbers = (14, 3, 88, 42, 1);

my $max = 0;

for (@numbers) {
    $max = $_ if $_ > $max;
}

for (my $exp = 1; int($max / $exp) > 0; $exp *= 10) {

    my @count = (0) x 10;
    my @output;

    for (@numbers) {
        $count[int($_ / $exp) % 10]++;
    }

    for (1 .. 9) {
        $count[$_] += $count[$_ - 1];
    }

    for (my $i = $#numbers; $i >= 0; $i--) {

        my $digit = int($numbers[$i] / $exp) % 10;
        $output[$count[$digit] - 1] = $numbers[$i];
        $count[$digit]--;

    }

    @numbers = @output;

}

print "Sorted array: @numbers\n";

This program is compact and easy to experiment with. Beginners can modify it quickly to test different datasets. It is ideal for practice.

Program 9: Radix Sort Supporting Negative Numbers and Floating Points

By default, Radix Sort does not handle negative or floating-point numbers. This final program tweaks the logic to support them.

#!/usr/bin/perl
use strict;
use warnings;
use POSIX qw(floor);

my @numbers = (3.5, -2.1, 4.0, -7.3, 1.2);

# Multiply by 10 for one decimal precision
my @positives = map { int($_ * 10) } grep { $_ >= 0 } @numbers;
# For negatives, multiply and take abs
my @negatives = map { abs(int($_ * 10)) } grep { $_ < 0 } @numbers;

sub radix_sort {

    my @arr = @_;
    return () unless @arr;

    # Find max value
    my $max = 0;

    for my $n (@arr) {
        $max = $n if $n > $max;
    }

    # Radix sort by each digit
    for (my $exp = 1; int($max / $exp) > 0; $exp *= 10) {

        my @buckets = map { [] } (0..9);

        for (@arr) {
            push @{$buckets[int($_ / $exp) % 10]}, $_;
        }

        @arr = map { @$_ } @buckets;

    }

    return @arr;

}

@positives = radix_sort(@positives);
@negatives = reverse radix_sort(@negatives);

# Restore negatives and positives separately
my @sorted_negatives = map { -$_ / 10 } @negatives;  # restore negative numbers
my @sorted_positives = map { $_ / 10 } @positives;   # restore positive numbers

@numbers = (@sorted_negatives, @sorted_positives);

print "Sorted array: @numbers\n";

This program converts floating-point numbers into integers and separates negatives from positives. After sorting, it restores the original values. Beginners learn an important lesson here, which is that algorithms can be adapted creatively.

Frequently Asked Questions (FAQ)

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

Q1: Is Radix Sort faster than Quick Sort?
Radix Sort can be faster when sorting numbers with limited digits. Quick Sort is usually better for general-purpose sorting.

Q2: Does Radix Sort compare numbers directly?
No, Radix Sort groups numbers by digits instead of comparing them directly.

Q3: Can Radix Sort sort strings?
Radix Sort can sort strings, but it requires extra logic. This article focuses on numeric sorting.

Q4: Is Radix Sort stable?
Yes, Radix Sort is stable when implemented correctly using stable sub-sorts like Counting Sort.

Q5: Should beginners use Perl’s built-in sort instead?
For real projects, Perl’s built-in sort is easier. Radix Sort is mainly for learning and understanding algorithms.

Conclusion

Radix Sort is a fascinating algorithm that teaches a very different way of thinking about sorting. Instead of comparing values, it focuses on digits and structure. By implementing Radix Sort in Perl, beginners gain deeper insight into how efficient algorithms work behind the scenes.

Practicing these Perl Radix Sort programs will strengthen your confidence with arrays, loops, and numeric processing. Keep experimenting with different inputs and variations. The more you practice, the more natural algorithmic thinking will become.

Scroll to Top