Sorting a table without using the sort function

December 2016






Getting started


First of all we initialize a variable $ max with the 1st value of table.
Then we will make a loop until the table still contains elements.
Using the splice function,we will empty the table.

Pseudocode


IF table contains elements 
    find the maximum  value
    determine the position of the element found 
    add the item to the top of the table sorted, in ascending order
    add the item to the end of the table sorted - in descending order 
    delete items found with splice - stopping condition for the loop 
    reset the position 
    reset the max$ with first item in the table decreased with splice 
END AS

The coding


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

my @tab = qw/9 3 7 14 8 7 25 12 1 6/;
my ($n,$max,@tri,@tri_desc);
$max = $tab[0];

print "@tab\n";
while(@tab){
        $_ > $max and $max = $_ for @tab;
        for (@tab){ $n++;last if $max == $_}
        unshift @tri,$max;
        push @tri_desc,$max;
        splice(@tab,$n-1,1);
        $n=0;
        $max = $tab[0];
}
print "ascending order:\t@tri\n";
print "descending order:\t@tri_desc\n";
__END__


Results

When using the following combination: 9 3 7 14 8 7 25 12 1 6
Ascending order: 1 3 6 7 7 8 9 12 14 25
Descending order: 25 14 12 9 8 7 7

Related :

This document entitled « Sorting a table without using the sort function » from CCM (ccm.net) is made available under the Creative Commons license. You can copy, modify copies of this page, under the conditions stipulated by the license, as this note appears clearly.