Sorting algorithms/Cocktail sort: Difference between revisions
Content added Content deleted
m (added Category:Sorting) |
SqrtNegInf (talk | contribs) 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 { |
|||
⚫ | |||
⚫ | |||
print "@B\n"; |
|||
⚫ | |||
my @C=cocktailSort(@B); |
|||
⚫ | |||
print "@C\n"; |
|||
⚫ | |||
################### cocktailSort ##################### |
|||
⚫ | |||
sub cocktailSort { #( A : list of sortable items ) defined as: |
|||
@a[$i, $i+1] = @a[$i+1, $i]; |
|||
$swapped_forward = 1; |
|||
⚫ | |||
⚫ | |||
} |
|||
last if not $swapped_forward; |
|||
⚫ | |||
my $swapped_backward = 0; |
|||
⚫ | |||
# elements are in the wrong |
|||
if ($a[$i] gt $a[$i+1]) { |
|||
⚫ | |||
$swapped_backward = 1; |
|||
($A[$i+1], $A[$i])=($A[$i], $A[$i+1]); # let the two elements |
|||
} |
|||
# change places |
|||
} |
|||
last if not $swapped_backward; |
|||
⚫ | |||
} |
} |
||
⚫ | |||
if ($swapped == 0) { |
|||
} |
|||
# we can exit the outer loop here if no swaps occurred. |
|||
print "no more swaps"; |
|||
⚫ | |||
else { |
|||
$swapped = 0; |
|||
⚫ | |||
⚫ | |||
⚫ | |||
{{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> |
|||
⚫ | |||
⚫ | |||
⚫ | |||
} |
|||
} |
|||
# if no elements have been swapped, |
|||
# then the list is sorted |
|||
} |
|||
return (@A); |
|||
#end sub |
|||
}</lang> |
|||
=={{header|Phix}}== |
=={{header|Phix}}== |