Jump to content

Sorting algorithms/Cocktail sort: Difference between revisions

m
→‎{{header|Perl}}: replaced broken algorithm, fiddled with layout
m (added Category:Sorting)
m (→‎{{header|Perl}}: replaced broken algorithm, fiddled with layout)
Line 2,837:
<lang perl>use strict;
use warnings;
use feature 'say';
 
sub cocktail_sort {
my @B=qw(t h e q u i c k b r o w n f o x j u m p s o v e r t h e l a z y d o g);
my @a }= @_;
print "@B\n";
while ($swapped ==while (1) {
my @C=cocktailSort(@B);
my $swappedswapped_forward = 10;
print "@C\n";
for (my $i=0; $i<(0..$#Aa-1); $i+=1) {
################### cocktailSort #####################
if ($Aa[$i] gt $Aa[$i+1]) {
sub cocktailSort { #( A : list of sortable items ) defined as:
my @Aa[$i, $i+1] = @_a[$i+1, $i];
my $swappedswapped_forward = 1;
}
while ($swapped == 1) {
$swapped = 0; }
last if not $swapped_forward;
for (my $i=0; $i<($#A-1); $i+=1) {
 
if ($A[$i] gtmy $A[$i+1]) { # test whether theswapped_backward two= 0;
for (my $i= ($#A-1);reverse $i>0 ; ..$i#a-=1) {
# elements are in the wrong
if ($a[$i] gt $a[$i+1]) # order{
($A @a[$i+1], $A[$i+1]) =($A @a[$i]+1, $A[$i+1]);
 
$swapped_backward = 1;
($A[$i+1], $A[$i])=($A[$i], $A[$i+1]); # let the two elements
}
# change places
$swapped = 1;}
last if not $swapped_backward;
}
}
}@a
if ($swapped == 0) {
}
# we can exit the outer loop here if no swaps occurred.
print "no more swaps";
}
else {
$swapped = 0;
for (my $i=($#A-1); $i>0 ; $i-=1) {
 
mysay @B=qwjoin ' ', cocktail_sort( <t h e q u i c k b r o w n f o x j u m p s o v e r t h e l a z y d o g> );</lang>
if($A[$i] gt $A[$i+1]) {
{{out}}
 
<pre>a b c d e e e f g h h i j k l m n o o o o p q r r s t t u u v w x y z</pre>
($A[$i+1], $A[$i])=($A[$i], $A[$i+1]);
$swapped = 1;
}
}
}
# if no elements have been swapped,
# then the list is sorted
}
return (@A);
#end sub
}</lang>
 
=={{header|Phix}}==
2,392

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.