Perl Program to Implement Insertion Sort

Perl Program to Implement Insertion Sort

Insertion Sort is one of the most beginner-friendly sorting algorithms you can learn. It works in a very natural way, similar to how people sort playing cards in their hands. You take one value at a time and insert it into the correct position among the already sorted values. Because of this simple idea, Insertion Sort is easy to understand and easy to implement.

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 Insertion Sort using Perl is helpful because it strengthens your understanding of arrays, loops, and comparisons. While Insertion Sort is not the fastest algorithm for very large data sets, it performs quite well for small lists and nearly sorted data. This makes it useful in real-life situations like small scripts, quick data cleanup tasks, and as a building block for learning more advanced sorting algorithms.

Program 1: Basic Insertion Sort Using For Loops

This first program shows the classic and most commonly taught version of Insertion Sort in Perl. It uses simple loops and comparisons, making it ideal for beginners who want to see the algorithm clearly.

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

my @numbers = (12, 11, 13, 5, 6);
my $n = scalar @numbers;

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

    my $key = $numbers[$i];
    my $j = $i - 1;

    while ($j >= 0 && $numbers[$j] > $key) {
        $numbers[$j + 1] = $numbers[$j];
        $j--;
    }

    $numbers[$j + 1] = $key;

}

print "Sorted array: @numbers\n";

This program works by taking one element and placing it into the correct position among the elements before it. Each pass grows the sorted portion of the array. Beginners can easily follow how values move step by step until the array becomes sorted.

Program 2: Insertion Sort Using While Loops

This version uses while loops instead of for loops to control the flow. It helps beginners understand that the same logic can be written in different styles.

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

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

while ($i < $n) {

    my $key = $numbers[$i];
    my $j = $i - 1;

    while ($j >= 0 && $numbers[$j] > $key) {
        $numbers[$j + 1] = $numbers[$j];
        $j--;
    }

    $numbers[$j + 1] = $key;
    $i++;

}

print "Sorted array: @numbers\n";

The logic here is the same as the basic version, but the loop structure is different. This program teaches beginners that understanding the algorithm is more important than memorizing one exact syntax.

Program 3: Insertion Sort Using a Subroutine

In this program, the sorting logic is placed inside a subroutine. This approach is useful for writing clean and reusable Perl code.

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

sub insertion_sort {

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

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

        my $key = $arr[$i];
        my $j = $i - 1;

        while ($j >= 0 && $arr[$j] > $key) {
            $arr[$j + 1] = $arr[$j];
            $j--;
        }

        $arr[$j + 1] = $key;

    }

    return @arr;

}

my @numbers = (8, 2, 4, 9, 3);
my @sorted = insertion_sort(@numbers);

print "Sorted array: @sorted\n";

Using a subroutine makes the program easier to reuse in other projects. Beginners learn how to pass arrays to functions and return results, which is a key skill in Perl programming.

Program 4: Recursive Insertion Sort in Perl

This version shows how Insertion Sort can be written using recursion. While recursion is not commonly used for this algorithm, it is helpful for learning purposes.

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

sub insertion_sort_recursive {

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

    insertion_sort_recursive($arr_ref, $n - 1);

    my $last = $arr_ref->[$n - 1];
    my $j = $n - 2;

    while ($j >= 0 && $arr_ref->[$j] > $last) {
        $arr_ref->[$j + 1] = $arr_ref->[$j];
        $j--;
    }

    $arr_ref->[$j + 1] = $last;

}

my @numbers = (7, 4, 6, 2, 1);
insertion_sort_recursive(\@numbers, scalar @numbers);

print "Sorted array: @numbers\n";

This program sorts the array by first sorting a smaller part and then inserting the last element in the correct position. Beginners should see this as a way to understand recursion rather than a preferred sorting method.

Program 5: Insertion Sort Optimized for Nearly Sorted Data

Insertion Sort works especially well when data is already nearly sorted. This program demonstrates that behavior clearly.

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

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

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

    my $key = $numbers[$i];
    my $j = $i - 1;

    while ($j >= 0 && $numbers[$j] > $key) {
        $numbers[$j + 1] = $numbers[$j];
        $j--;
    }

    $numbers[$j + 1] = $key;

}

print "Sorted array: @numbers\n";

Because the array is almost sorted, very few movements are needed. This shows beginners why Insertion Sort can be efficient in certain real-world situations, even though it is slow for large random data.

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

Insertion Sort in Perl works naturally with negative numbers and floating-point values. This program shows that no special changes are required.

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

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

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

    my $key = $numbers[$i];
    my $j = $i - 1;

    while ($j >= 0 && $numbers[$j] > $key) {
        $numbers[$j + 1] = $numbers[$j];
        $j--;
    }

    $numbers[$j + 1] = $key;

}

print "Sorted array: @numbers\n";

This program confirms that Perl handles numeric comparisons correctly, whether the numbers are negative or decimal. Beginners can confidently sort different kinds of numeric data without extra logic.

Frequently Asked Questions (FAQ)

This section answers common questions beginners often have about Insertion Sort in Perl. These answers aim to remove confusion and build confidence.

Q1: Is Insertion Sort used in real applications?
Insertion Sort is used in small systems and as part of more advanced algorithms. It works well when data is small or nearly sorted.

Q2: Why is Insertion Sort good for beginners?
Insertion Sort is easy to understand because it follows a natural sorting process. It helps beginners learn array manipulation and comparisons.

Q3: Is Insertion Sort faster than Bubble Sort?
Insertion Sort is usually faster than Bubble Sort, especially when the data is nearly sorted. Both are mainly used for learning.

Q4: Does Perl have built-in sorting?
Yes, Perl has a built-in sort function that is much faster and recommended for real-world use.

Q5: Should I use recursion for Insertion Sort?
Recursion is not necessary and is shown mainly for learning purposes. Loop-based versions are simpler and more efficient.

Conclusion

Insertion Sort is a simple yet powerful sorting algorithm that every beginner should understand. By exploring different Perl programs, you can see how the same idea can be written using loops, subroutines, and recursion. This helps build a strong foundation in programming logic.

Practicing these Perl Insertion Sort programs will improve your confidence with arrays and control structures. Once you master this algorithm, learning more advanced sorting techniques will feel much easier. Keep practicing, keep experimenting, and enjoy your journey into Perl programming.

Scroll to Top