Sorting a table without using the sort function

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.


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 

The coding

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";
        $_ > $max and $max = $_ for @tab;
        for (@tab){ $n++;last if $max == $_}
        unshift @tri,$max;
        push @tri_desc,$max;
        $max = $tab[0];
print "ascending order:\t@tri\n";
print "descending order:\t@tri_desc\n";


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
Published by jak58. Latest update on October 22, 2009 at 10:49 AM by jak58.
This document, titled "Sorting a table without using the sort function," is available under the Creative Commons license. Any copy, reuse, or modification of the content should be sufficiently credited to CCM (
Converting a 32-bit integer into IP