Sorting algorithms/Cocktail sort: Difference between revisions

Content deleted Content added
→‎version handles non-blanks: De-obfuscate Rexx version
Chkas (talk | contribs)
 
(5 intermediate revisions by 5 users not shown)
Line 1,599:
}</syntaxhighlight>
Note that this solution contains no repeated code to handle the forward and reverse passes.
 
=={{header|EasyLang}}==
<syntaxhighlight lang=text>
proc sort . d[] .
a = 1
b = len d[] - 1
while a <= b
h = a
for i = a to b
if d[i] > d[i + 1]
swap d[i] d[i + 1]
h = i
.
.
b = h - 1
h = b
for i = b downto a
if d[i] > d[i + 1]
swap d[i] d[i + 1]
h = i
.
.
a = h + 1
.
.
l[] = [ 5 6 1 2 9 14 2 15 6 7 8 97 ]
sort l[]
print l[]
</syntaxhighlight>
{{out}}
<pre>
[ 1 2 2 5 6 6 7 8 9 14 15 97 ]
</pre>
 
=={{header|Eiffel}}==
Line 1,742 ⟶ 1,775:
 
=={{header|Elena}}==
ELENA 56.0x :
<syntaxhighlight lang="elena">import extensions;
import system'math;
Line 1,758 ⟶ 1,791:
swapped := false;
for(int i := 0,; i <= list.Length - 2,; i += 1)
{
if (list[i]>list[i+1])
Line 1,772 ⟶ 1,805:
swapped := false;
for(int i := list.Length - 2,; i >= 0,; i -= 1)
{
if (list[i]>list[i+1])
Line 3,787 ⟶ 3,820:
===version handles non-blanks===
This faster REXX version can handle array elements that don't contain blanks or spaces by using a simpler ''swap'' mechanism.
The REXX ''PARSE'' instruction separates an input into parts and assigns them to
variables, in a single operation. Thus
<syntaxhighlight lang="rexx">PARSE VALUE 0 items.j items.jp WITH done items.jp items.j</syntaxhighlight>
sets ''done'' to 0, ''items.jp'' to ''items.j'', and ''items.j'' to ''items.jp'', as long as none of the input
variables contain any blanks.
<syntaxhighlight lang="rexx">cocktailSort2: procedure expose items.
nn = items.0 - 1 /*N: the number of items in items.*/
Line 3,829 ⟶ 3,867:
end
</syntaxhighlight>
 
=={{header|RPL}}==
{{works with|RPL|HP-49C}}
« '''DO''' 1 CF
1 OVER SIZE 1 - '''FOR''' h
DUP h DUP 1 + SUB
'''IF''' DUP EVAL > '''THEN'''
h SWAP REVLIST REPL
1 SF
'''ELSE''' DROP '''END'''
'''NEXT'''
'''IF''' 1 FS? '''THEN'''
DUP SIZE 1 - 1 '''FOR''' h
DUP h DUP 1 + SUB
'''IF''' DUP EVAL > '''THEN'''
h SWAP REVLIST REPL
1 SF
'''ELSE''' DROP '''END'''
-1 '''STEP'''
'''END'''
'''UNTIL''' 1 FC? '''END'''
» '<span style="color:blue">COCKTAILSORT</span>' STO
 
{ 7 6 5 9 8 4 3 1 2 0 } <span style="color:blue">COCKTAILSORT</span>
{{out}}
<pre>
1: { 0 1 2 3 4 5 6 7 8 9 }
</pre>
This implementation is 40 times slower than the built-in <code>SORT</code> function on an HP-50g.
 
=={{header|Ruby}}==
Line 4,447 ⟶ 4,514:
=={{header|Wren}}==
{{trans|Go}}
<syntaxhighlight lang="ecmascriptwren">var cocktailSort = Fn.new { |a|
var last = a.count - 1
while (true) {