Sorting algorithms/Cocktail sort: Difference between revisions

jq
(jq)
Line 1,149:
} while (swapped);
}</lang>
 
=={{header|jq}}==
{{ works with|jq|1.4}}
<lang jq># In case your jq does not have "until" defined:
def until(cond; next):
def _until:
if cond then . else (next|_until) end;
_until;</lang>
<lang jq>def cocktailSort:
def swap(i;j): .[i] as $t | .[i] = .[j] | .[j] = $t;
 
def cocktail(stream):
reduce stream as $i
(.[0]=false;
.[1] as $A
| if $A[ $i ] > $A[ $i+1 ] then
[true, ($A|swap( $i; $i+1 ))]
else .
end);
 
(length - 2) as $lm2
# state: [swapped, A]
| [true, .]
| until( .[0]|not;
cocktail(range(0; $lm2 + 1))
| if .[0] then
# for each i in length( A ) - 2 down to 0
cocktail( $lm2 - range(0; $lm2 + 1))
else .
end )
| .[1];</lang>
'''Tests:'''
<lang jq>def verify: if cocktailSort == sort then empty else . end;
 
([],
[1],
[1,1],
[3, 14],
[33, 14],
[3, 14, 1, 5, 9, 2, 6, 3],
[23,76,99,58,97,57,35,89,51,38,95,92,24,46,31,24,14,12,57,78,4],
[88,18,31,44,4,0,8,81,14,78,20,76,84,33,73,75,82,5,62,70,12,7,1],
[1.5, -1.5],
["cocktail", ["sort"], null, {}]
) | verify</lang>
{{out}}
<lang sh>$ jq -n -c -f cocktail_sort.jq
$</lang>
 
=={{header|Lua}}==
2,478

edits