Sorting algorithms/Cocktail sort: Difference between revisions

Content added Content deleted
m (added Category:Sorting)
m (→‎{{header|Perl}}: replaced broken algorithm, fiddled with layout)
Line 2,837: Line 2,837:
<lang perl>use strict;
<lang perl>use strict;
use warnings;
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 (1) {
my @C=cocktailSort(@B);
my $swapped_forward = 0;
print "@C\n";
for my $i (0..$#a-1) {
################### cocktailSort #####################
if ($a[$i] gt $a[$i+1]) {
sub cocktailSort { #( A : list of sortable items ) defined as:
my @A = @_;
@a[$i, $i+1] = @a[$i+1, $i];
my $swapped = 1;
$swapped_forward = 1;
}
while ($swapped == 1) {
$swapped = 0;
}
last if not $swapped_forward;
for (my $i=0; $i<($#A-1); $i+=1) {


if ($A[$i] gt $A[$i+1]) { # test whether the two
my $swapped_backward = 0;
for my $i (reverse 0..$#a-1) {
# elements are in the wrong
# order
if ($a[$i] gt $a[$i+1]) {
@a[$i, $i+1] = @a[$i+1, $i];

$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) {


say join ' ', 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}}==
=={{header|Phix}}==