#!/usr/bin/perl -w
##################
#
# Sort a list of numbers.
# 
# As an exercise, and without using Perl's
# built in "sort" function, here's a program
# to sort a list of numbers.
#
# The algorithm I've chosen is
#   * Look through the list to find the smallest number.
#   * Pull out the smallest and save it somewhere else.
#   * Repeat on the list that remains.
# This isn't the fastest (that's another whole subject),
# but it works, eh?
#
#  - Jim M.
#
# Want to see what's going on?
# Add some print statements...
#
#
##################
use strict;

my $number_in_list = 10;
my $max_digit      = 50;

# First, define a list of numbers to sort.
my @list;
push @list, int(1+$max_digit*rand()) for 1..$number_in_list;
print "The original list is: @list .\n";

# Now allocate storage for the sorted list.
my @sorted = ();

# ** The outer loop **
# as long as there's a list left to sort, 
while (@list){

  # ** The inner loop **
  # (1) Find the index of the smallest element in the list.
  my $i_smallest = 0;
  for (my $i=1; $i<scalar(@list); $i++){
    if ($list[$i] < $list[$i_smallest]){
      $i_smallest = $i;
    }
  }

  # (2) Put that smallest entry into the new list.
  push @sorted, $list[$i_smallest];

  # (3) Make a copy of the list without that smallest one.
  my @list_copy;
  for (my $i=0; $i<scalar(@list); $i++){
    if (not $i == $i_smallest ){
      push @list_copy, $list[$i];
    }
  }
  
  # (4) Replace the list with this smaller copy.
  @list = @list_copy;
}

print "The sorted list is @sorted .\n";
