Perl Program to Implement Shell Sort

Perl Program to Implement Shell Sort

Shell Sort is an improved version of Insertion Sort that helps data move faster toward its correct position. Instead of comparing and shifting elements one step at a time, Shell Sort allows elements to jump over long distances early on. This simple idea makes sorting much quicker, especially for medium-sized datasets that are not already sorted.

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

Shell Sort matters because it is easy to understand, simple to implement, and performs better than basic sorting algorithms like Bubble Sort and Insertion Sort in many real-world cases. It is often used in educational settings, small utilities, and systems where simplicity is valued over complex optimizations. Learning how to write a Perl program to implement Shell Sort gives beginners a strong foundation in algorithm optimization and array manipulation.

Program 1: Basic Shell Sort Using Loops

This first program shows the classic Shell Sort implementation using loops. It uses predefined data and follows the most common gap-reduction approach.

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

my @numbers = (23, 12, 1, 8, 34, 54, 2, 3);

sub shell_sort {

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

    for (my $gap = int($n / 2); $gap > 0; $gap = int($gap / 2)) {

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

            my $temp = $arr[$i];
            my $j = $i;

            while ($j >= $gap && $arr[$j - $gap] > $temp) {

                $arr[$j] = $arr[$j - $gap];
                $j -= $gap;

            }

            $arr[$j] = $temp;

        }

    }

    return @arr;

}

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

This program works by reducing the gap size after each pass and performing insertion-like sorting within those gaps. It is useful because it clearly shows how Shell Sort improves efficiency by reducing the number of shifts needed. Beginners can understand it by focusing on how the gap controls how far elements can move.

Program 2: Shell Sort with Clearer Variable Names

This version improves readability by using descriptive variable names. It is helpful for beginners who want clarity over compactness.

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

my @data = (45, 22, 11, 89, 3, 77, 9);

sub shell_sort {

    my @array = @_;
    my $length = scalar @array;

    for (my $gap = int($length / 2); $gap > 0; $gap = int($gap / 2)) {

        for (my $current = $gap; $current < $length; $current++) {

            my $value = $array[$current];
            my $position = $current;

            while ($position >= $gap && $array[$position - $gap] > $value) {
                $array[$position] = $array[$position - $gap];
                $position -= $gap;
            }

            $array[$position] = $value;

        }

    }

    return @array;

}

print "Sorted array: ", join(" ", shell_sort(@data)), "\n";

This program behaves the same as the first one but is easier to read. Clear variable names help beginners follow the logic without getting lost. This style is excellent for learning and teaching purposes.

Program 3: Shell Sort with Custom Gap Sequence

This program demonstrates Shell Sort using a custom gap sequence instead of halving the gap every time.

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

my @numbers = (64, 34, 25, 12, 22, 11, 90);
my @gaps = (4, 2, 1);

sub shell_sort {

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

    for my $gap (@$gaps_ref) {

        for (my $i = $gap; $i < @$arr_ref; $i++) {

            my $temp = $arr_ref->[$i];
            my $j = $i;

            while ($j >= $gap && $arr_ref->[$j - $gap] > $temp) {
                $arr_ref->[$j] = $arr_ref->[$j - $gap];
                $j -= $gap;
            }

            $arr_ref->[$j] = $temp;

        }

    }

}

shell_sort(\@numbers, \@gaps);
print "Sorted array: @numbers\n";

Using a custom gap sequence allows better control over performance. This program shows beginners that Shell Sort is flexible and can be tuned. It also introduces passing arrays by reference, which is an important Perl concept.

Program 4: Shell Sort Written Step by Step

This version keeps all logic in one place to make learning easier. It avoids extra functions and focuses on clarity.

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

my @numbers = (19, 2, 31, 45, 6, 11, 121, 27);
my $n = scalar @numbers;

for (my $gap = int($n / 2); $gap > 0; $gap = int($gap / 2)) {

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

        my $temp = $numbers[$i];
        my $j = $i;

        while ($j >= $gap && $numbers[$j - $gap] > $temp) {
            $numbers[$j] = $numbers[$j - $gap];
            $j -= $gap;
        }

        $numbers[$j] = $temp;

    }

}

print "Sorted array: @numbers\n";

This program is ideal for beginners who want to trace the algorithm line by line. Everything happens in a single script, making it easier to debug and experiment. It is also perfect for classroom learning.

Program 5: Shell Sort with Descending Order Option

This version shows how Shell Sort can be easily modified to sort in descending order.

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

my @numbers = (10, 7, 8, 9, 1, 5);

sub shell_sort_desc {

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

    for (my $gap = int($n / 2); $gap > 0; $gap = int($gap / 2)) {

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

            my $temp = $arr[$i];
            my $j = $i;

            while ($j >= $gap && $arr[$j - $gap] < $temp) {
                $arr[$j] = $arr[$j - $gap];
                $j -= $gap;
            }

            $arr[$j] = $temp;

        }

    }

    return @arr;

}

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

This program shows how changing one comparison can alter the sorting order. Beginners learn that algorithms are flexible and adaptable. This is useful when different sorting requirements arise.

Program 6: Shell Sort with Input Validation

This version includes simple checks to ensure the array is not empty.

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

my @numbers = (41, 33, 17, 80, 61);

sub shell_sort {

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

    my $n = scalar @arr;

    for (my $gap = int($n / 2); $gap > 0; $gap = int($gap / 2)) {

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

            my $temp = $arr[$i];
            my $j = $i;

            while ($j >= $gap && $arr[$j - $gap] > $temp) {
                $arr[$j] = $arr[$j - $gap];
                $j -= $gap;
            }

            $arr[$j] = $temp;

        }

    }
    return @arr;

}

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

This program teaches beginners to think about edge cases. Even though Shell Sort handles most inputs well, it is good practice to validate data. This habit is valuable in real-world programming.

Program 7: Shell Sort with Array References

This version sorts the array in place using references.

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

my @numbers = (99, 44, 6, 2, 1, 5, 63, 87);

sub shell_sort {

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

    for (my $gap = int($n / 2); $gap > 0; $gap = int($gap / 2)) {

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

            my $temp = $arr->[$i];
            my $j = $i;

            while ($j >= $gap && $arr->[$j - $gap] > $temp) {
                $arr->[$j] = $arr->[$j - $gap];
                $j -= $gap;
            }

            $arr->[$j] = $temp;

        }

    }

}

shell_sort(\@numbers);
print "Sorted array: @numbers\n";

Sorting in place is memory-efficient and common in real applications. This program introduces references in a practical way. Beginners gain confidence handling more advanced Perl features.

Program 8: Shell Sort with Mixed Values

This program sorts a mix of small and large integers.

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

my @numbers = (5, 100, 3, 50, 2, 200, 1);

sub shell_sort {

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

    for (my $gap = int($n / 2); $gap > 0; $gap = int($gap / 2)) {

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

            my $temp = $arr[$i];
            my $j = $i;

            while ($j >= $gap && $arr[$j - $gap] > $temp) {
                $arr[$j] = $arr[$j - $gap];
                $j -= $gap;
            }

            $arr[$j] = $temp;

        }

    }

    return @arr;

}

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

This program reassures beginners that Shell Sort handles varied data well. The algorithm remains stable and predictable. It is a good test case for practice.

Program 9: Shell Sort Supporting Floating Point and Negative Numbers

Shell Sort naturally supports negative and floating point numbers. This final program demonstrates that clearly.

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

my @numbers = (-2.5, 3.1, 0.0, -7.4, 1.8, 4.2);

sub shell_sort {

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

    for (my $gap = int($n / 2); $gap > 0; $gap = int($gap / 2)) {

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

            my $temp = $arr[$i];
            my $j = $i;

            while ($j >= $gap && $arr[$j - $gap] > $temp) {
                $arr[$j] = $arr[$j - $gap];
                $j -= $gap;
            }

            $arr[$j] = $temp;

        }

    }

    return @arr;

}

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

This program proves that Shell Sort works without modification for negative and decimal values. Beginners learn that not all algorithms need special handling for such cases. This makes Shell Sort very practical.

Frequently Asked Questions (FAQ)

This section answers common beginner questions about Shell Sort in Perl.

Q1: Why is Shell Sort faster than Insertion Sort?
Shell Sort allows elements to move long distances early, reducing total shifts.

Q2: Is Shell Sort stable?
Shell Sort is generally not stable because elements may jump over each other.

Q3: When should I use Shell Sort?
Shell Sort is good for medium-sized datasets where simplicity matters.

Q4: Does Shell Sort work with decimals and negatives?
Yes, Shell Sort naturally supports both.

Q5: Should I use Perl’s built-in sort instead?
For production code, built-in sort is easier, but Shell Sort is excellent for learning.

Conclusion

Shell Sort is a powerful improvement over basic sorting algorithms and is surprisingly easy to understand. By implementing Shell Sort in Perl, beginners learn how small changes in strategy can lead to big performance gains.

Practicing these Perl Shell Sort programs will strengthen your understanding of loops, arrays, and algorithm design. Keep experimenting with different gap values and datasets. With regular practice, sorting algorithms will start to feel natural and intuitive.

Scroll to Top