in reply to Inertion sort in perl

First, Perl is not C or FORTAN or ASM.
This kind of thing:
for ($i=1; $i lt $n; $i++){....}
is an extremely "rare duck" in Perl!
These i-n (INteger) variables just aren't needed in most cases.

Perl uses a variant of QuickSort and for almost all of your sorting, you should too! This is normally faster than SelectSort. Use the power of the language!

Re-coding your program,

@a = (8,5,2,4,88,1,5,4,3,2); @a = sort @a; #same as @a = sort{$a <=> $b}@a; #because only digits not alpha/digits print "@a","\n"; #prints: 1 2 2 3 4 4 5 5 8 88

Replies are listed 'Best First'.
Re^2: Inertion sort in perl
by Corion (Patriarch) on Apr 25, 2009 at 15:54 UTC

    Close, but not entirely true:

    >perl -le "print for sort @ARGV" 1 10 2 20 1 10 2 20

    But with an explicit comparison, it works:

    >perl -le "print for sort{ $a <=> $b } @ARGV" 1 10 2 20 1 2 10 20
      Yes, we are on the same page here!
      Thanks for emphasizing the difference between ASCII vs numeric sort order!

      Corion is completely correct about this...there is a difference.

      I attach some code that I use for a GUI sort gizmo that doesn't know if it is sorting numbers or alpha-number strings. It uses normal string compare unless both items are strictly numeric and in that case, it uses the "spaceship" operator "<=>" for the compare.

      sub alpha_num_cmp { my($a, $b) = @_; if (( $a =~ m/\D/) || ($b =~ m/\D/) ) { #look for a non-digit return ($a cmp $b); #if so, then use string compare } return ($a <=> $b); #otherwise straight numeric comparison }
      Ok, a cut-n-paste goof...The above code was one level down in the GUI..Ooops!

      That code compares "columns" of similar things. Here is more code...

      #!usr/bin/perl -w use strict; my @a=(8,5,2,4,88,1,10,20,5,4,3,2); my @b = sort @a; print "alpha sort\n"; print "@b\n"; @b = sort {$a<=>$b}@a; print "numeric sort\n"; print "@b\n"; @b = sort alpha_num_cmp @a; print "an any sort\n"; print "@b\n"; sub alpha_num_cmp { if ( ( $a =~ m/\D/) || ($b =~ m/\D/) ) { #look for a non-digit return ($a cmp $b); #if so, then use string compare } return ($a <=> $b); #otherwise straight numeric comparison } __END__ prints: alpha sort 1 10 2 2 20 3 4 4 5 5 8 88 numeric sort 1 2 2 3 4 4 5 5 8 10 20 88 an any sort 1 2 2 3 4 4 5 5 8 10 20 88