SPUG: Sort an array question

Andrew Reid blueovalfun at yahoo.com
Thu Dec 26 14:53:17 CST 2002


While attempting to gain more meaninful employment, I
happened upon this question from a prospective
provider of opportunity.  "Sort an array
alphabetically without using the Perl sort command." 
This was provided by someone not familiar with Perl
but other languages and all work was shown on a white
board.  I think I did OK, there were a few holes in
the code, and I decided to really give it a shot. 
This works and is very close to what I provided on the

If any of you have some free time and thoughts, I'd
appreciate them!  Tell me what you think.

Here is my program.

#!/usr/bin/perl -w

$arrayCnt = 0;
$passCnt = 0;
$elementCnt = 0;

@array1 = qw(e c g h z r t a i h j l p b d r q x v a);
@array2 = sort(@array1);

foreach (@array1) {$arrayCnt++;}
print "This is the array Count [$arrayCnt]\n";

while (defined @array1) {

$startPnt = $array1[$passCnt];
$lowValue = $startPnt;

if ($arrayCnt <= $passCnt) {
    print "My sort list [@array1]\n";
    print "A Check Sort [@array2]";

print "The array as found in loop $passCnt
print "The Start point value \t** $startPnt **\t \n";

    foreach (@array1) { 
        if ($elementCnt < $passCnt){
            print "Element Value [ $_ ]\t";
            print "Element Count [$elementCnt]\t Pass
Count [$passCnt]\n";
        } elsif (($_ lt $lowValue) || ($_ eq
              print "Comparing $_ to $lowValue
[Element #$elementCnt]\t";
              $lowValue = $_;
     	      print "Low value [$lowValue]\n";
     	      $lowElement = $elementCnt;
    } #end of foreach
    if ($startPnt ne $lowValue) {
        print "This was the low value [$lowValue] and
low element [$lowElement]\n";
        print ("splice()
",splice(@array1,$lowElement,1), "\n");
        $array1[$passCnt] = $lowValue;
    } else {$passCnt++;}
} #end of while 

Do you Yahoo!?
Yahoo! Mail Plus - Powerful. Affordable. Sign up now.

 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     POST TO: spug-list at pm.org       PROBLEMS: owner-spug-list at pm.org
      Subscriptions; Email to majordomo at pm.org:  ACTION  LIST  EMAIL
  Replace ACTION by subscribe or unsubscribe, EMAIL by your Email-address
 For daily traffic, use spug-list for LIST ;  for weekly, spug-list-digest
     Seattle Perl Users Group (SPUG) Home Page: http://seattleperl.org

More information about the spug-list mailing list