Un program de sortare a unui array

104

Secvenţă cod (tst28.pl)

 

Rezultat īn consola text

# read the array from standard input one item at a time

print ("Enter the array to sort, one item at a time.\n");

print ("Enter an empty line to quit.\n");

$count = 1;

$inputline = <STDIN>;

chop ($inputline);

while ($inputline ne "") {

     @array[$count-1] = $inputline;

     $count++;

     $inputline = <STDIN>;

     chop ($inputline);

}

# now sort the array

$count = 1;

while ($count < @array) {

     $x = 1;

     while ($x < @array) {

           if ($array[$x - 1] gt $array[$x]) {

                @array[$x-1,$x] = @array[$x,$x-1];

           }

     $x++;

     }

     $count++;

}

# finally, print the sorted array

print ("@array\n");

  Enter the array to sort, one item at a time.

Enter an empty line to quit.

am

fost

din

nou

la

garaj

dar

m-am

intors

devreme

 

am dar devreme din fost garaj intors la m-am nou

 

    Un exemplu de introducere a unui array direct de la <STDIN> este următorul

 

Secvenţă cod (tst29.pl)

 

Rezultat īn consola text

print ("Enter the array, one item at a time.\n");

print ("Enter an ^Z to quit.\n");

  Enter the array, one item at a time.

Enter an ^Z to quit.

@array = <STDIN>;   a

b

c

^Z

print (@array,"\n");

 

  a

b

c

print (@array[0..@array]);   a

b

c

Observaţie: Codul ^Z (scrierea compactă a comenzii CTRL+Z), nu este tipăribil pe ecran (secvenţa ^Z a fost introdusă pentru identificarea uşoară, de către cititor, a momentului introducerii comenzii CTRL+Z. Īn alte implementări şi sau pe alte maşini īn locul ^Z se poate folosi altceva, spre exemplu, ^D. De regulă se introduce comanda corespunzătoare codului End Of File (EOF).

© Cornel Mironel Niculae, 2003-2004

13-Nov-2009