Sorting algorithms/Cocktail sort: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
No edit summary
m (→‎{{header|Wren}}: Changed to Wren S/H)
(13 intermediate revisions by 9 users not shown)
Line 36:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F cocktailSort(&A)
L
L(indices) ((0 .< A.len-1).step(1), (A.len-2 .. 0).step(-1))
Line 49:
V test1 = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]
cocktailSort(&test1)
print(test1)</langsyntaxhighlight>
 
{{out}}
Line 59:
{{trans|PL/I}}
The program uses HLASM structured macros (DO,ENDDO,IF,ELSE,ENDIF) for readability and two ASSIST/360 macros (XDECO,XPRNT) to keep the code as short as possible.
<langsyntaxhighlight lang="360asm">* Cocktail sort 25/06/2016
COCKTSRT CSECT
USING COCKTSRT,R13 base register
Line 129:
YREGS
RI EQU 6 i
END COCKTSRT</langsyntaxhighlight>
{{out}}
<pre>
Line 136:
=={{header|6502 Assembly}}==
Implemented in Easy6502. Output is provided below but it's best to watch this in action. Just copy and paste the code in, hit Assemble then Run. Make sure you check the Monitor box and set the address to 1200 and the length to 100. This takes about half as long as the bubble sort.
<langsyntaxhighlight lang="6502asm">define z_HL $00
define z_L $00
define z_H $01
Line 226:
JMP COCKTAILSORT
doneSorting:
RTS</langsyntaxhighlight>
 
{{out}}
Line 249:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program cocktailSort64.s */
Line 432:
.include "../includeARM64.inc"
 
</syntaxhighlight>
</lang>
=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC PrintArray(INT ARRAY a INT size)
INT i
 
Put('[)
FOR i=0 TO size-1
DO
IF i>0 THEN Put(' ) FI
PrintI(a(i))
OD
Put(']) PutE()
RETURN
 
PROC CoctailSort(INT ARRAY a INT size)
INT i,tmp
BYTE swapped
 
DO
swapped=0
i=0
WHILE i<size-1
DO
IF a(i)>a(i+1) THEN
tmp=a(i) a(i)=a(i+1) a(i+1)=tmp
swapped=1
FI
i==+1
OD
 
IF swapped=0 THEN EXIT FI
 
swapped=0
i=size-1
WHILE i>=0
DO
IF a(i)>a(i+1) THEN
tmp=a(i) a(i)=a(i+1) a(i+1)=tmp
swapped=1
FI
i==-1
OD
 
UNTIL swapped=0
OD
RETURN
 
PROC Test(INT ARRAY a INT size)
PrintE("Array before sort:")
PrintArray(a,size)
CoctailSort(a,size)
PrintE("Array after sort:")
PrintArray(a,size)
PutE()
RETURN
 
PROC Main()
INT ARRAY
a(10)=[1 4 65535 0 3 7 4 8 20 65530],
b(21)=[10 9 8 7 6 5 4 3 2 1 0
65535 65534 65533 65532 65531
65530 65529 65528 65527 65526],
c(8)=[101 102 103 104 105 106 107 108],
d(12)=[1 65535 1 65535 1 65535 1
65535 1 65535 1 65535]
Test(a,10)
Test(b,21)
Test(c,8)
Test(d,12)
RETURN</syntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Cocktail_Sort.png Screenshot from Atari 8-bit computer]
<pre>
Array before sort:
[1 4 -1 0 3 7 4 8 20 -6]
Array after sort:
[-6 -1 0 1 3 4 4 7 8 20]
 
Array before sort:
[10 9 8 7 6 5 4 3 2 1 0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10]
Array after sort:
[-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9 10]
 
Array before sort:
[101 102 103 104 105 106 107 108]
Array after sort:
[101 102 103 104 105 106 107 108]
 
Array before sort:
[1 -1 1 -1 1 -1 1 -1 1 -1 1 -1]
Array after sort:
[-1 -1 -1 -1 -1 -1 1 1 1 1 1 1]
</pre>
 
=={{header|ActionScript}}==
<langsyntaxhighlight ActionScriptlang="actionscript">function cocktailSort(input:Array):Array {
do {
var swapped:Boolean=false;
Line 458 ⟶ 552:
} while (swapped);
return input;
}</langsyntaxhighlight>
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_Io; use Ada.Text_Io;
 
procedure Cocktail_Sort_Test is
Line 497 ⟶ 591:
Cocktail_Sort(Data);
Put_Line(Data);
end Cocktail_Sort_Test;</langsyntaxhighlight>
 
=={{header|ALGOL 60}}==
{{works with|A60}}
<langsyntaxhighlight lang="algol60">begin
comment Sorting algorithms/Cocktail sort - Algol 60;
integer nA;
Line 557 ⟶ 651:
writetable(1,nA)
end
end </langsyntaxhighlight>
{{out}}
<pre>
Line 565 ⟶ 659:
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">MODE DATA = CHAR;
PROC swap = (REF DATA a,b)VOID:(
DATA tmp:=a; a:=b; b:=tmp
Line 597 ⟶ 691:
[32]CHAR data := "big fjords vex quick waltz nymph";
cocktail sort(data);
print(data)</langsyntaxhighlight>
{{out}}
<pre> abcdefghiijklmnopqrstuvwxyz</pre>
Line 603 ⟶ 697:
indirectly, thus removing the need to actually swap large chunks of memory
as only addresses are swapped.
<langsyntaxhighlight lang="algol68">MODE DATA = REF CHAR;
PROC swap = (REF DATA a,b)VOID:(
DATA tmp:=a; a:=b; b:=tmp
Line 614 ⟶ 708:
cocktail sort(ref data);
FOR i TO UPB ref data DO print(ref data[i]) OD; print(new line);
print((data))</langsyntaxhighlight>
{{out}}<pre> abcdefghiijklmnopqrstuvwxyz
big fjords vex quick waltz nymph</pre>
The above two routines both scan the entire width of the array, in both directions, even though the first and last elements of each sweep had already reached their final destination during the previous pass. The solution is to zig-zag, but have the sweeps shorten and converge on the centre element. This reduces the number of comparisons required by about 50%.
<langsyntaxhighlight lang="algol68">PROC odd even sort = (REF []DATA a)VOID: (
FOR offset FROM 0 DO
BOOL swapped := FALSE;
Line 640 ⟶ 734:
OD;
break do od loop: SKIP
);</langsyntaxhighlight>
 
=={{header|ALGOL W}}==
As noted in the ALGOL 68 sample above, the highest and lowest elements are sorted into their correct positions each time through the main loop.
This implementation optimises by reducing the number of elements to sort on each pass through the main loop.
<langsyntaxhighlight lang="algolw">begin
% As algol W does not allow overloading, we have to have type-specific %
% sorting procedures - this coctail sorts an integer array %
Line 709 ⟶ 803:
writeData;
end test ;
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 717 ⟶ 811:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* program cocktailSort.s */
Line 889 ⟶ 983:
.include "../affichage.inc"
 
</syntaxhighlight>
</lang>
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">trySwap: function [arr,i][
if arr\[i] < arr\[i-1] [
tmp: arr\[i]
Line 919 ⟶ 1,013:
]
 
print cocktailSort [3 1 2 8 5 7 9 4 6]</langsyntaxhighlight>
 
{{out}}
Line 927 ⟶ 1,021:
=={{header|AutoHotkey}}==
contributed by Laszlo on the ahk [http://www.autohotkey.com/forum/post-276379.html#276379 forum]
<langsyntaxhighlight AutoHotkeylang="autohotkey">MsgBox % CocktailSort("")
MsgBox % CocktailSort("xxx")
MsgBox % CocktailSort("3,2,1")
Line 958 ⟶ 1,052:
sorted .= "," . array%A_Index%
Return SubStr(sorted,2) ; drop leading comma
}</langsyntaxhighlight>
 
=={{header|AWK}}==
Sort the standard input and print it to standard output
<langsyntaxhighlight lang="awk">{
line[NR] = $0
}
Line 991 ⟶ 1,085:
print line[i]
}
}</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
Sorting an integer array. '%' indicates integer variable in BBC BASIC
<langsyntaxhighlight BBClang="bbc BASICbasic">DEF PROC_ShakerSort(Size%)
 
Start%=2
Line 1,013 ⟶ 1,107:
UNTIL ( ( End% * Direction% ) < ( Start% * Direction% ) )
 
ENDPROC</langsyntaxhighlight>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
 
// can be any swap function. This swap is optimized for numbers.
Line 1,054 ⟶ 1,148:
printf("%d ", a[i]);
return 0;
}</langsyntaxhighlight>
 
'''Output''':
 
<syntaxhighlight lang="text">-4 -1 0 1 2 3 5 6 8 101</langsyntaxhighlight>
 
===Generic version===
This version can be used with arrays of any type, like the standard library function qsort.
<langsyntaxhighlight lang="c">#include <stdbool.h>
#include <stdio.h>
#include <string.h>
Line 1,125 ⟶ 1,219:
print(a, len);
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 1,134 ⟶ 1,228:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">public static void cocktailSort(int[] A)
{
bool swapped;
Line 1,169 ⟶ 1,263:
//if no elements have been swapped, then the list is sorted
} while (swapped);
}</langsyntaxhighlight>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <windows.h>
Line 1,253 ⟶ 1,347:
return 0;
}
</syntaxhighlight>
</lang>
 
=== Alternate version ===
Uses C++11. Compile with
g++ -std=c++11 cocktail.cpp
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <iostream>
#include <iterator>
Line 1,292 ⟶ 1,386:
copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,300 ⟶ 1,394:
=={{header|COBOL}}==
This is procedure division only.
<langsyntaxhighlight lang="cobol"> C-SORT SECTION.
C-000.
DISPLAY "SORT STARTING".
Line 1,337 ⟶ 1,431:
 
F-999.
EXIT.</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
This version works on lists and vectors alike. The vector implementation is coded directly. The list version uses an intermediate vector.
<langsyntaxhighlight lang="lisp">(defun cocktail-sort-vector (vector predicate &aux (len (length vector)))
(labels ((scan (start step &aux swapped)
(loop for i = start then (+ i step) while (< 0 i len) do
Line 1,359 ⟶ 1,453:
(list (map-into sequence 'identity
(cocktail-sort-vector (coerce sequence 'vector)
predicate)))))</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">// Written in the D programming language.
module rosettaCode.sortingAlgorithms.cocktailSort;
 
Line 1,399 ⟶ 1,493:
["Alice", "Jane", "Joe", "John", "Kate", "Zerg"]);
}
</syntaxhighlight>
</lang>
 
{{out}}
<syntaxhighlight lang="d">
<lang d>
import rosettaCode.sortingAlgorithms.cocktailSort;
 
Line 1,409 ⟶ 1,503:
//generate 10 sorted random numbers in [0 .. 10)
rndGen.take(10).map!(a=>a%10).array.cocktailSort.writeln();
}</langsyntaxhighlight>
<pre>[2, 2, 3, 4, 5, 5, 7, 7, 7, 8]</pre>
 
Line 1,416 ⟶ 1,510:
 
Static array is an arbitrary-based array of fixed length
<langsyntaxhighlight Delphilang="delphi">program TestShakerSort;
 
{$APPTYPE CONSOLE}
Line 1,479 ⟶ 1,573:
Writeln;
Readln;
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 1,487 ⟶ 1,581:
 
=={{header|E}}==
<langsyntaxhighlight lang="e">/** Cocktail sort (in-place) */
def cocktailSort(array) {
def swapIndexes := 0..(array.size() - 2)
Line 1,503 ⟶ 1,597:
}
}
}</langsyntaxhighlight>
Note that this solution contains no repeated code to handle the forward and reverse passes.
 
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
 
class
Line 1,600 ⟶ 1,694:
end
 
</syntaxhighlight>
</lang>
Test:
<syntaxhighlight lang="eiffel">
<lang Eiffel>
 
class
Line 1,638 ⟶ 1,732:
end
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,648 ⟶ 1,742:
 
=={{header|Elena}}==
ELENA 56.0x :
<langsyntaxhighlight lang="elena">import extensions;
import system'math;
import system'routines;
Line 1,664 ⟶ 1,758:
swapped := false;
for(int i := 0,; i <= list.Length - 2,; i += 1)
{
if (list[i]>list[i+1])
Line 1,678 ⟶ 1,772:
swapped := false;
for(int i := list.Length - 2,; i >= 0,; i -= 1)
{
if (list[i]>list[i+1])
Line 1,698 ⟶ 1,792:
console.printLine("before:", list.asEnumerable());
console.printLine("after :", list.cocktailSort().asEnumerable())
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,706 ⟶ 1,800:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Sort do
def cocktail_sort(list) when is_list(list), do: cocktail_sort(list, [], [])
Line 1,726 ⟶ 1,820:
end
 
IO.inspect Sort.cocktail_sort([5,3,9,4,1,6,8,2,7])</langsyntaxhighlight>
 
{{out}}
Line 1,734 ⟶ 1,828:
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">function cocktail_sort(sequence s)
integer swapped, d
object temp
Line 1,758 ⟶ 1,852:
constant s = rand(repeat(1000,10))
? s
? cocktail_sort(s)</langsyntaxhighlight>
{{out}}
<pre>{963,398,374,455,53,210,611,285,984,308}
Line 1,767 ⟶ 1,861:
===Pseudocode translation===
This is a faithful translation of the pseudocode given in the task description. It uses lexical variables.
<langsyntaxhighlight lang="factor">USING: kernel locals math math.ranges sequences ;
 
:: cocktail-sort! ( seq -- seq' )
Line 1,784 ⟶ 1,878:
] when
] do while
seq ; ! return the sequence</langsyntaxhighlight>
 
===More idiomatic===
This is perhaps a more idiomatic solution, eschewing the use of lexical variables. If we had tried to translate the pseudocode directly, we'd be dealing with a data stack that is 6+ values deep. Our main strategy against this is to factor the problem into short words that deal with only a few items at a time. When writing mutating words, we can simplify matters by writing words that return nothing, and letting the caller decide if and how to leave references on the data stack.
<langsyntaxhighlight lang="factor">USING: fry kernel math math.ranges namespaces sequences ;
 
SYMBOL: swapped?
Line 1,808 ⟶ 1,902:
 
: cocktail-sort! ( seq -- seq' )
[ swapped? get ] [ (cocktail-sort!) ] do while ;</langsyntaxhighlight>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">defer precedes ( addr addr -- flag )
\ e.g. ' < is precedes
: sort ( a n --)
Line 1,829 ⟶ 1,923:
-1 cells +loop
repeat then drop 2r> 2drop
;</langsyntaxhighlight>
This is an optimized version:
<langsyntaxhighlight lang="forth">: sort
1- cells bounds 1
begin
Line 1,842 ⟶ 1,936:
>r negate >r swap r@ cells + r> r>
until drop drop drop
;</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">PROGRAM COCKTAIL
IMPLICIT NONE
 
Line 1,889 ⟶ 1,983:
END SUBROUTINE Cocktail_sort
 
END PROGRAM COCKTAIL</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight FreeBASIClang="freebasic">' version 21-10-2016
' compile with: fbc -s console
' for boundry checks on array's compile with: fbc -s console -exx
Line 1,949 ⟶ 2,043:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>unsorted -2 -4 7 -5 -7 4 2 -1 5 -6 6 1 0 -3 3
Line 1,956 ⟶ 2,050:
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=ee5467e58f0ef649373eed5a2503b988 Click this link to run this code]'''
<langsyntaxhighlight lang="gambas">Public Sub Main()
Dim siCount, siRev, siProcess As Short
Dim bSorting As Boolean
Line 2,002 ⟶ 2,096:
Print
End</langsyntaxhighlight>
Output:
<pre>
Line 2,019 ⟶ 2,113:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 2,054 ⟶ 2,148:
}
}
}</langsyntaxhighlight>
More generic version that sorts anything that implements <code>sort.Interface</code>:
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,094 ⟶ 2,188:
}
}
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
Solution:
<langsyntaxhighlight lang="groovy">def makeSwap = { a, i, j = i+1 -> print "."; a[[j,i]] = a[[i,j]] }
def checkSwap = { a, i, j = i+1 -> [(a[i] > a[j])].find{ it }.each { makeSwap(a, i, j) } }
Line 2,111 ⟶ 2,205:
}
list
}</langsyntaxhighlight>
Test:
<langsyntaxhighlight lang="groovy">println cocktailSort([23,76,99,58,97,57,35,89,51,38,95,92,24,46,31,24,14,12,57,78,4])
println cocktailSort([88,18,31,44,4,0,8,81,14,78,20,76,84,33,73,75,82,5,62,70,12,7,1])
 
println cocktailSort([ 3, 14, 1, 5, 9, 2, 6, 3 ])
println cocktailSort([ 3, 14 ])
println cocktailSort([ 33, 14 ])</langsyntaxhighlight>
{{out}}
<pre>..............................................................................................................................................[4, 12, 14, 23, 24, 24, 31, 35, 38, 46, 51, 57, 57, 58, 76, 78, 89, 92, 95, 97, 99]
Line 2,127 ⟶ 2,221:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">cocktailSort :: Ord a => [a] -> [a]
cocktailSort l
| not swapped1 = l
Line 2,140 ⟶ 2,234:
| otherwise = swappingPass op (swapped, x1 : l) (x2 : xs)
swappingPass _ (swapped, l) [x] = (swapped, x : l)
swappingPass _ pair [] = pair</langsyntaxhighlight>
 
=={{header|Ksh}}==
<syntaxhighlight lang="ksh">#!/bin/ksh
 
# cocktail shaker sort
 
# # Variables:
#
integer TRUE=1
integer FALSE=0
typeset -a arr=( 5 -1 101 -4 0 1 8 6 2 3 )
 
# # Functions:
#
function _swap {
typeset _i ; integer _i=$1
typeset _j ; integer _j=$2
typeset _array ; nameref _array="$3"
typeset _swapped ; nameref _swapped=$4
 
typeset _tmp ; _tmp=${_array[_i]}
_array[_i]=${_array[_j]}
_array[_j]=${_tmp}
_swapped=$TRUE
}
 
######
# main #
######
 
print "( ${arr[*]} )"
 
integer i j
integer swapped=$TRUE
while (( swapped )); do
swapped=$FALSE
for (( i=0 ; i<${#arr[*]}-2 ; i++ , j=i+1 )); do
(( arr[i] > arr[j] )) && _swap ${i} ${j} arr swapped
done
(( ! swapped )) && break
 
swapped=$FALSE
for (( i=${#arr[*]}-2 ; i>0 ; i-- , j=i+1 )); do
(( arr[i] > arr[j] )) && _swap ${i} ${j} arr swapped
done
done
 
print "( ${arr[*]} )"</syntaxhighlight>
{{out}}
<pre>( 5 -1 101 -4 0 1 8 6 2 3 )
( -4 -1 0 1 2 3 5 6 8 101 )</pre>
 
 
=={{header|Haxe}}==
<langsyntaxhighlight lang="haxe">class CocktailSort {
@:generic
public static function sort<T>(arr:Array<T>) {
Line 2,191 ⟶ 2,337:
Sys.println('Sorted Strings: ' + stringArray);
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,204 ⟶ 2,350:
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">procedure main() #: demonstrate various ways to sort a list and string
demosort(cocktailsort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty")
end
Line 2,220 ⟶ 2,366:
X[i+1] :=: X[swapped := i]
return X
end</langsyntaxhighlight>
 
Note: This example relies on [[Sorting_algorithms/Bubble_sort#Icon| the supporting procedures 'sortop', and 'demosort' in Bubble Sort]].
Line 2,233 ⟶ 2,379:
 
=={{header|Io}}==
<langsyntaxhighlight lang="io">List do (
cocktailSortInPlace := method(
start := 0
Line 2,263 ⟶ 2,409:
 
l := list(2, 3, 4, 5, 1)
l cocktailSortInPlace println # ==> list(1, 2, 3, 4, 5)</langsyntaxhighlight>
 
=={{header|IS-BASIC}}==
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "CocktSrt.bas"
110 RANDOMIZE
120 NUMERIC ARRAY(5 TO 24)
Line 2,292 ⟶ 2,438:
340 LET EN=ST:LET ST=CH-D:LET D=-1*D
350 LOOP UNTIL EN*D<ST*D
360 END DEF</langsyntaxhighlight>
 
=={{header|J}}==
{{eff note|J|/:~}}
<langsyntaxhighlight lang="j">bigToLeft=: (([ (>. , <.) {.@]) , }.@])/
smallToLeft=: (([ (<. , >.) {.@]) , }.@])/
cocktailSort=: |. @: (|. @: smallToLeft @: |. @: bigToLeft ^:_)</langsyntaxhighlight>
Test run:
<langsyntaxhighlight lang="j"> ?. 10 $ 10
4 6 8 6 5 8 6 6 6 9
cocktailSort ?. 10 $ 10
4 5 6 6 6 6 6 8 8 9</langsyntaxhighlight>
As is usual with J, <code>/:~</code> is the preferred method of sorting in practice.
 
Line 2,309 ⟶ 2,455:
This algorithm sorts in place.
Call it with a copy of the array to preserve the unsorted order.
<langsyntaxhighlight lang="java">public static void cocktailSort( int[] A ){
boolean swapped;
do {
Line 2,337 ⟶ 2,483:
//if no elements have been swapped, then the list is sorted
} while (swapped);
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">
// Node 5.4.1 tested implementation (ES6)
"use strict";
Line 2,374 ⟶ 2,520:
console.log(arr);
 
}</langsyntaxhighlight>
 
 
Line 2,384 ⟶ 2,530:
=={{header|jq}}==
{{ works with|jq|1.4}}
<langsyntaxhighlight 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;</langsyntaxhighlight>
<langsyntaxhighlight lang="jq">def cocktailSort:
def swap(i;j): .[i] as $t | .[i] = .[j] | .[j] = $t;
 
Line 2,411 ⟶ 2,557:
else .
end )
| .[1];</langsyntaxhighlight>
'''Tests:'''
<langsyntaxhighlight lang="jq">def verify: if cocktailSort == sort then empty else . end;
 
([],
Line 2,425 ⟶ 2,571:
[1.5, -1.5],
["cocktail", ["sort"], null, {}]
) | verify</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="sh">$ jq -n -c -f cocktail_sort.jq
$</langsyntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">function cocktailsort(a::Vector)
b = copy(a)
isordered = false
Line 2,459 ⟶ 2,605:
 
v = rand(-10:10, 10)
println("# unordered: $v\n -> ordered: ", cocktailsort(v))</langsyntaxhighlight>
 
{{out}}
Line 2,466 ⟶ 2,612:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.0
 
fun cocktailSort(a: IntArray) {
Line 2,502 ⟶ 2,648:
println(a.joinToString(", "))
}
}</langsyntaxhighlight>
 
{{out}}
Line 2,512 ⟶ 2,658:
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">function cocktailSort( A )
local swapped
repeat
Line 2,534 ⟶ 2,680:
 
until swapped==false
end</langsyntaxhighlight>
{{out|Example}}
<langsyntaxhighlight lang="lua">list = { 5, 6, 1, 2, 9, 14, 2, 15, 6, 7, 8, 97 }
cocktailSort(list)
for i=1,#list do
print(list[i]j)
end</langsyntaxhighlight>
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module cocktailSort {
k=(3,2,1)
Line 2,598 ⟶ 2,744:
}
cocktailSort
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,610 ⟶ 2,756:
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">arr := Array([17,3,72,0,36,2,3,8,40,0]):
len := numelems(arr):
swap := proc(arr, a, b)
Line 2,635 ⟶ 2,781:
if (not swapped) then break: end if:
end do:
arr;</langsyntaxhighlight>
{{Output|Out}}
<pre>[0,0,2,3,3,8,17,36,40,72]</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">cocktailSort[A_List] := Module[ { swapped = True },
While[ swapped == True,
swapped=False;
Line 2,650 ⟶ 2,796:
For [ i= Length[A]-1, i > 0, i--,
If[ A[[i]] > A[[i+1]], A[[i;;i+1]] = A[[i+1;;i;;-1]]; swapped = True;]
]]]</langsyntaxhighlight>
{{out|Example}}
<pre>cocktailSort[{2,1,5,3,6}]
Line 2,656 ⟶ 2,802:
 
=={{header|MATLAB}} / {{header|Octave}}==
<langsyntaxhighlight MATLABlang="matlab">function list = cocktailSort(list)
%We have to do this because the do...while loop doesn't exist in MATLAB
Line 2,685 ⟶ 2,831:
end %for
end %while
end %cocktail sort</langsyntaxhighlight>
{{out|Sample usage}}
<langsyntaxhighlight MATLABlang="matlab">cocktailSort([6 3 7 8 5 1 2 4 9])
 
ans =
 
1 2 3 4 5 6 7 8 9</langsyntaxhighlight>
 
=={{header|MAXScript}}==
<langsyntaxhighlight lang="maxscript">fn cocktailSort arr =
(
local swapped = true
Line 2,719 ⟶ 2,865:
)
return arr
)</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols binary
 
Line 2,778 ⟶ 2,924:
 
method isFalse public constant binary returns boolean
return \isTrue</langsyntaxhighlight>
{{out}}
<pre>
Line 2,801 ⟶ 2,947:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">template trySwap(): untyped =
if a[i] < a[i-1]:
swap a[i], a[i-1]
Line 2,817 ⟶ 2,963:
var a = @[4, 65, 2, -31, 0, 99, 2, 83, 782]
cocktailSort a
echo a</langsyntaxhighlight>
{{out}}
<pre>@[-31, 0, 2, 2, 4, 65, 83, 99, 782]</pre>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">bundle Default {
class Cocktail {
function : Main(args : String[]) ~ Nil {
Line 2,863 ⟶ 3,009:
}
}
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let swap a i j =
let tmp = a.(i) in
a.(i) <- a.(j);
Line 2,902 ⟶ 3,048:
Array.iter (Printf.printf " %d") a;
print_newline();
;;</langsyntaxhighlight>
{{out}}
<pre>
Line 2,909 ⟶ 3,055:
 
=={{header|Octave}}==
<langsyntaxhighlight lang="octave">function sl = cocktailsort(l)
swapped = true;
while(swapped)
Line 2,935 ⟶ 3,081:
endwhile
sl = l;
endfunction</langsyntaxhighlight>
{{out|Example}}
<langsyntaxhighlight lang="octave">s = cocktailsort([5, -1, 101, -4, 0, \
1, 8, 6, 2, 3 ]);
disp(s);</langsyntaxhighlight>
 
=={{header|ooRexx}}==
{{Trans|NetRexx}}
<langsyntaxhighlight ooRexxlang="oorexx">/* Rexx */
 
placesList = .array~of( -
Line 2,993 ⟶ 3,139:
end swaps
 
return A</langsyntaxhighlight>
{{out}}
<pre>
Line 3,016 ⟶ 3,162:
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
proc {CocktailSort Arr}
proc {Swap I J}
Line 3,041 ⟶ 3,187:
in
{CocktailSort Arr}
{Inspect Arr}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">cocktailSort(v)={
while(1,
my(done=1);
Line 3,067 ⟶ 3,213:
if(done, return(v))
)
};</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 3,073 ⟶ 3,219:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use strict;
use warnings;
use feature 'say';
Line 3,101 ⟶ 3,247:
}
 
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> );</langsyntaxhighlight>
{{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>
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
Line 3,134 ⟶ 3,280:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"original: %V\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">s</span><span style="color: #0000FF;">})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" sorted: %V\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">cocktail_sort</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)})</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 3,142 ⟶ 3,288:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">function cocktailSort($arr){
if (is_string($arr)) $arr = str_split(preg_replace('/\s+/','',$arr));
 
Line 3,179 ⟶ 3,325:
echo implode(',',$arr) . '<br>';
echo implode(',',$arr2) . '<br>';
echo implode('',$strg) . '<br>';</langsyntaxhighlight>
{{out}}
<pre>
Line 3,188 ⟶ 3,334:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de cocktailSort (Lst)
(use (Swapped L)
(loop
Line 3,206 ⟶ 3,352:
(on Swapped) )
(T (== Lst L)) )
(NIL Swapped Lst) ) ) )</langsyntaxhighlight>
{{out}}
<pre>: (cocktailSort (make (do 9 (link (rand 1 999)))))
Line 3,214 ⟶ 3,360:
 
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii">cocktail: procedure (A);
declare A(*) fixed;
declare t fixed;
Line 3,230 ⟶ 3,376:
end;
end;
end cocktail;</langsyntaxhighlight>
 
=={{header|PowerShell}}==
Based on the entry for PowerShell in [[Bubble Sort]]
<langsyntaxhighlight PowerShelllang="powershell">function CocktailSort ($a) {
$l = $a.Length
$m = 0
Line 3,265 ⟶ 3,411:
}
 
$l = 10; CocktailSort ( 1..$l | ForEach-Object { $Rand = New-Object Random }{ $Rand.Next( -( $l - 1 ), $l - 1 ) } )</langsyntaxhighlight>
 
=={{header|Prolog}}==
<langsyntaxhighlight Prologlang="prolog">ctail(_, [], Rev, Rev, sorted) :- write(Rev), nl.
ctail(fwrd, [A,B|T], In, Rev, unsorted) :- A > B, !,
ctail(fwrd, [B,A|T], In, Rev, _).
Line 3,286 ⟶ 3,432:
cocktail(In, R),
writef('-> %w\n', [R]).
</syntaxhighlight>
</lang>
{{out|Example}}
<pre>?- test.
Line 3,300 ⟶ 3,446:
=={{header|PureBasic}}==
The following approach improves on the method in the pseudo-code by not examining indexes on either end of the array that have already been sorted by reducing the index range on each subsequent pass.
<langsyntaxhighlight PureBasiclang="purebasic">;sorts an array of integers
Procedure cocktailSort(Array a(1))
Protected index, hasChanged, low, high
Line 3,330 ⟶ 3,476:
low + 1
Until hasChanged = #False ;if no elements have been changed, then the array is sorted
EndProcedure</langsyntaxhighlight>
 
=={{header|Python}}==
This implementation takes advantage of the identical processing of the two ''for'' loops and that a ''range'' is a first-class object in Python.
<langsyntaxhighlight lang="python">def cocktailSort(A):
up = range(len(A)-1)
while True:
Line 3,344 ⟶ 3,490:
swapped = True
if not swapped:
return</langsyntaxhighlight>
{{out|Usage}}
<langsyntaxhighlight lang="python">test1 = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]
cocktailSort(test1)
print test1
Line 3,354 ⟶ 3,500:
cocktailSort(test2)
print ''.join(test2)
#>>> abcdefghiijklmnopqrstuvwxyz</langsyntaxhighlight>
 
This implementation is clearer in structure to it's bubblesort origins while also being ever so slightly faster, in python 3.5.2 at least.
<langsyntaxhighlight lang="python">def cocktail(a):
for i in range(len(a)//2):
swap = False
Line 3,372 ⟶ 3,518:
swap = True
if not swap:
break</langsyntaxhighlight>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="Quackery">
[ 2dup 1+ peek dip peek > ] is compare ( [ n --> b )
 
[ dup 1+ unrot
2dup peek
dip
[ 2dup 1+ peek
unrot poke
swap ]
unrot poke ] is exchange ( [ n --> [ )
 
[ [ 0 swap
dup size 1 - times
[ dup i^ compare if
[ i^ exchange
dip 1+ ] ]
over while
dup size 1 - times
[ dup i compare if
[ i exchange
dip 1+ ] ]
over while
nip again ]
nip ] is cocktail ( [ --> [ )
 
randomise
[] 20 times [ 89 random 10 + join ]
dup echo cr
cocktail echo</syntaxhighlight>
 
{{out}}
 
<pre>[ 46 42 73 92 95 19 27 52 33 12 60 70 34 45 93 15 64 41 12 55 ]
[ 12 12 15 19 27 33 34 41 42 45 46 52 55 60 64 70 73 92 93 95 ]</pre>
 
=={{header|R}}==
The previously solution missed out on a cool R trick for swapping items. As R is 1-indexed, we have made some minor adjustments to the given pseudo-code. Otherwise, we have aimed to be faithful to it.
<langsyntaxhighlight rlang="rsplus">cocktailSort <- function(A)
{
repeat
{
swapped <- FALSE
for(i in 1:seq_len(length(A) - 1))
{
if(A[i] > A[i + 1])
{
A[c(i, i + 1)] <- A[c(i + 1, i)]#The cool trick mentioned above.
swapped <- TRUE
}
}
if(!swapped) break
swapped <- FALSE
for(i in (length(A)-1):1)
{
if(A[i] > A[i + 1])
{
A[c(i, i + 1)] <- A[c(i + 1, i)]
swapped <- TRUE
}
}
Line 3,404 ⟶ 3,587:
}
#Examples taken from the Haxe solution.
ints <- c(1, 10, 2, 5, -1, 5, -19, 4, 23, 0)
numerics <- c(1, -3.2, 5.2, 10.8, -5.7, 7.3, 3.5, 0, -4.1, -9.5)
strings <- c("We", "hold", "these", "truths", "to", "be", "self-evident", "that", "all", "men", "are", "created", "equal")</langsyntaxhighlight>
 
{{out}}
Line 3,418 ⟶ 3,601:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(require (only-in srfi/43 vector-swap!))
Line 3,435 ⟶ 3,618:
[(zero? (bubble (- len 2) 0 -1)) xs]
[(loop)])))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>sub cocktail_sort ( @a ) {
my $range = 0 ..^ @a.end;
loop {
Line 3,464 ⟶ 3,647:
 
my @weights = (^50).map: { 100 + ( 1000.rand.Int / 10 ) };
say @weights.sort.Str eq @weights.&cocktail_sort.Str ?? 'ok' !! 'not ok';</langsyntaxhighlight>
 
=={{header|REXX}}==
===version handles blanks===
This REXX version can handle array elements that may contain blanks or spaces.
<langsyntaxhighlight lang="rexx">/*REXX program sorts an array using the cocktail─sort method, A.K.A.: happy hour sort,*/
/* bidirectional bubble sort, */
/* cocktail shaker sort, ripple sort,*/
Line 3,475 ⟶ 3,658:
/* shuffle sort, shuttle sort, or */
/* a bubble sort variation. */
call gen@ genItems /*generate some array elements. */
call show@showItems 'before sort' /*show unsorted array elements. */
say copies('█', 101) /*show a separator line (a fence). */
call cocktailSort # /*invoke the cocktail sort subroutine. */
call show@showItems ' after sort' /*show sorted array elements. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
cocktailSort: procedure expose @.; parse arg N; nn= N-1 /*N: is number of items. */
nn = items.0 - 1 do until done; done= 1 /*items.0: is number of items. */
do until done
do j=1 for nn; jp= j+1
done = 1
if @.j>@.jp then do; done=0; _=@.j; @.j=@.jp; @.jp=_; end
do j = 1 for end /*j*/nn
jp = j + 1 if done then/* leaveRexx doesn't allow "items.(j+1)", so use this instead. /*No swaps done? Finished*/
if items.j > items.jp then do k=nn for nn by -1; kp= k+1
if @.k>@.kp then do; done=0; _=@.k; @.k=@.kp; @.kp=_; end0
temp = end /*k*/items.j
items.j = end /*until*/items.jp
return items.jp = temp
end
end /*j*/
if done then leave /*No swaps done? Finished*/
do k = nn for nn by -1
kp = k + 1 /* Rexx doesn't allow "items.(k+1)", so use this instead. */
if items.k > items.kp then do
done = 0
temp = items.k
items.k = items.kp
items.kp = temp
end
end /*k*/
end /*until*/
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
genitems: procedure expose items.
gen@: @.= /*assign a default value for the stem. */
items.= /*assign a default value for the stem. */
@.1 ='---the 22 card tarot deck (larger deck has 56 additional cards in 4 suits)---'
items.1 ='---the 22 card tarot deck (larger deck has 56 additional cards in 4 suits)---'
@.2 ='==========symbol====================pip======================================'
items.2 ='==========symbol====================pip======================================'
@.3 ='the juggler ◄─── I'
@items.43 ='the highjuggler priestess [Popess] ◄─── II I'
@items.54 ='the empresshigh priestess [Popess] ◄─── ◄─── IIIII'
@items.65 ='the emperorempress ◄─── IVIII'
@items.76 ='the hierophantemperor [Pope] ◄─── V ◄─── IV'
@items.87 ='the lovershierophant [Pope] ◄─── ◄─── VIV'
@items.98 ='the chariotlovers ◄─── VII VI'
items.9 @.10='justicethe chariot ◄─── ◄─── VIIIVII'
@items.1110='thejustice hermit ◄─── ◄─── IXVIII'
@items.1211='fortunethe hermit [the wheel of] ◄─── X ◄─── IX'
@items.1312='strengthfortune [the wheel of] ◄─── ◄─── XIX'
@items.1413='thestrength hanging man ◄─── XII XI'
@items.1514='deaththe hanging man [often unlabeled] ◄─── XIII XII'
@items.1615='temperance death [often unlabeled] ◄─── XIVXIII'
@items.1716='the devil temperance ◄─── XVXIV'
@items.1817='lightningthe devil [the tower] ◄─── XVI XV'
@items.1918='thelightning stars [the tower] ◄─── ◄─── XVIIXVI'
@items.2019='the moon stars ◄─── XVIII XVII'
@items.2120='the sun moon ◄─── XIXXVIII'
@items.2221='judgmentthe sun ◄─── ◄─── XXXIX'
@items.2322='thejudgment world ◄─── XXI XX'
@items.2423='the foolworld [often unnumbered] ◄─── XXII XXI'
items.24='the fool [often unnumbered] ◄─── XXII'
items.0 =24 /* number of entries in the array. */
 
return
do #=1 until @.#==''; end; #= #-1 /*find how many entries in the array. */
return /* [↑] adjust for DO loop advancement.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
showitems: procedure expose items.
show@: w= length(#); do j=1 for # /*#: is the number of items in @. */
parse arg phase
say 'element' right(j, w) arg(1)":" @.j
width = length(items.0)
end /*j*/ /* ↑ */
do j=1 to return items.0 /* items.0 is the number └─────maxof widthitems ofin anyitems. line.*/</lang>
say 'element' right(j, width) phase || ":" items.j
end /*j*/ /* ↑ */
/* └─────max width of any line number. */
return</syntaxhighlight>
{{out|output|text=&nbsp; when using the internal default inputs:}}
 
Line 3,584 ⟶ 3,787:
===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
<lang rexx>/*──────────────────────────────────────────────────────────────────────────────────────*/
variables, in a single operation. Thus
cocktailSort2: procedure expose @.; parse arg N; nn=n-1 /*N: the number of items in @.*/
<syntaxhighlight lang="rexx">PARSE VALUE 0 items.j items.jp WITH done items.jp items.j</syntaxhighlight>
do until done; done= 1 /*array items can't have blanks*/
sets ''done'' to 0, ''items.jp'' to ''items.j'', and ''items.j'' to ''items.jp'', as long as none of the input
do j=1 for nn; jp= j+1
variables contain any blanks.
if @.j>@.jp then parse value 0 @.j @.jp with done @.jp @.j
<syntaxhighlight lang="rexx">cocktailSort2: procedure expose items.
end /*j*/
nn = items.0 - 1 /*N: the number of items in items.*/
if done then leave /*Did swaps? Then we're done.*/
do until done
do k=nn for nn by -1; kp= k+1
done = 1 if @.k>@.kp then parse value 0 @.k @.kp with done @.kp @.k
do j = 1 for end /*k*/nn
jp = j + 1 end /* Rexx doesn't allow "items.(j+1)", so use this instead. /*until*/
if items.j return</lang> <br><br>items.jp then ,
parse value 0 items.j items.jp with done items.jp items.j /* swap items.j and items.jp, and set done to 0 */
end /*j*/
if done then leave /*Did swaps? Then we're done.*/
do k = nn for nn by -1
kp = k + 1 /* Rexx doesn't allow "items.(k+1)", so use this instead. */
if items.k > items.kp then ,
parse value 0 items.k items.kp with done items.kp items.k /* swap items.k and items.kp, and set done to 0 */
end /*k*/
end /*until*/
 
return</syntaxhighlight> <br><br>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
aList = [ 5, 6, 1, 2, 9, 14, 2, 15, 6, 7, 8, 97]
flag = 0
Line 3,619 ⟶ 3,833:
next
end
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">class Array
def cocktailsort!
begin
Line 3,644 ⟶ 3,858:
self
end
end</langsyntaxhighlight>
 
Another way
<langsyntaxhighlight lang="ruby">class Array
def cocktailsort!
start, finish, way = 0, size-1, 1
Line 3,663 ⟶ 3,877:
self
end
end</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="ruby">ary = [7,6,5,9,8,4,3,1,2,0]
p ary.cocktailsort!
ary = ["John", "Kate", "Zerg", "Alice", "Joe", "Jane"]
p ary.cocktailsort!</langsyntaxhighlight>
 
{{out}}
Line 3,678 ⟶ 3,892:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">for i = 1 to 100 ' fill array
a(i) = rnd(0) * 100
next i
Line 3,704 ⟶ 3,918:
print i;" ";a(i)
next i
end</langsyntaxhighlight>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn cocktail_sort<T: PartialOrd>(a: &mut [T]) {
let len = a.len();
loop {
Line 3,741 ⟶ 3,955:
cocktail_sort(&mut v);
println!("after: {:?}", v);
}</langsyntaxhighlight>
 
{{out}}
Line 3,750 ⟶ 3,964:
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">object CocktailSort extends App {
def sort(arr: Array[Int]) = {
var swapped = false
Line 3,775 ⟶ 3,989:
println(sort(Array(170, 45, 75, -90, -802, 24, 2, 66)).mkString(", "))
 
}</langsyntaxhighlight>
 
=={{header|Scilab}}==
<syntaxhighlight lang="text">function varargout=cocktailSort(list_in)
swapped = %T;
while swapped
Line 3,802 ⟶ 4,016:
endfunction
 
disp(cocktailSort([6 3 7 8 5 1 2 4 9]));</langsyntaxhighlight>
{{out}}
<pre> 1. 2. 3. 4. 5. 6. 7. 8. 9.</pre>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">const proc: cocktailSort (inout array elemType: arr) is func
local
var boolean: swapped is FALSE;
Line 3,835 ⟶ 4,049:
end if;
until not swapped;
end func;</langsyntaxhighlight>
 
Original source: [http://seed7.sourceforge.net/algorith/sorting.htm#cocktailSort]
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func cocktailsort(a) {
var swapped = false
func cmpsw(i) {
Line 3,855 ⟶ 4,069:
} while (swapped)
return a
}</langsyntaxhighlight>
Test:
<langsyntaxhighlight lang="ruby">var numbers = [7,6,5,9,8,4,3,1,2,0]
say cocktailsort(numbers)
 
var strs = ["John", "Kate", "Zerg", "Alice", "Joe", "Jane"]
say cocktailsort(strs)</langsyntaxhighlight>
{{out}}
<pre>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Line 3,867 ⟶ 4,081:
 
=={{header|Slate}}==
<langsyntaxhighlight lang="slate">s@(Sequence traits) cocktailSort
[ |swapped|
swapped: False.
Line 3,876 ⟶ 4,090:
swapped: False].
] loop
].</langsyntaxhighlight>
{{out|Example}}
<langsyntaxhighlight lang="slate">slate[1]> #( 10 9 8 7 6 0 -5) cocktailSort.
{-5. 0. 6. 7. 8. 9. 10}</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
<langsyntaxhighlight lang="smalltalk">OrderedCollection extend [
swap: indexA and: indexB [
|t|
Line 3,912 ⟶ 4,126:
^ self
]
].</langsyntaxhighlight>
{{out|Example}}
<langsyntaxhighlight lang="smalltalk">(#( 10 9 8 7 6 0 -5) asOrderedCollection cocktailSort) printNl.</langsyntaxhighlight>
 
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">extension Collection where Element: Comparable {
public func cocktailSorted() -> [Element] {
var swapped = false
Line 3,952 ⟶ 4,166:
 
print("Before: \(arr)")
print("Cocktail sort: \(arr.cocktailSorted())")</langsyntaxhighlight>
 
{{out}}
Line 3,961 ⟶ 4,175:
=={{header|Tcl}}==
{{tcllib|struct::list}}<!-- convenient element swapping only -->
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
package require struct::list
 
Line 3,989 ⟶ 4,203:
}
return $A
}</langsyntaxhighlight>
{{out|Example}}
<langsyntaxhighlight lang="tcl">puts [cocktailsort {8 6 4 2 1 3 5 7 9}] ;# => 1 2 3 4 5 6 7 8 9</langsyntaxhighlight>
 
=={{header|uBasic/4tH}}==
<syntaxhighlight lang="text">PRINT "Cocktail sort:"
n = FUNC (_InitArray)
PROC _ShowArray (n)
Line 4,045 ⟶ 4,259:
PRINT
RETURN</langsyntaxhighlight>
 
=={{header|Ursala}}==
The same function is used for the traversal in each direction, in one case parameterized by the given predicate and in the other by its negation. Lists are used rather than arrays. The fold combinator (<code>=></code>) avoids explicit recursion.
<langsyntaxhighlight Ursalalang="ursala">#import std
 
ctsort = ^=+ +^|(==?/~&l+ @r+ ~&x++ @x,^/~&)+ ("p". =><> ~&r?\~&C "p"?lrhPX/~&C ~&rhPlrtPCC)^~/not ~&</langsyntaxhighlight>
test program:
<langsyntaxhighlight Ursalalang="ursala">#cast %s
 
test = ctsort(lleq) 'mdfdguldxisgbxjtqkadfkslakwkyioukdledbig'</langsyntaxhighlight>
{{out}}
<pre>
Line 4,063 ⟶ 4,277:
=={{header|Vala}}==
{{trans|C}}
<langsyntaxhighlight lang="vala">void swap(int[] array, int i1, int i2) {
if (array[i1] == array[i2])
return;
Line 4,095 ⟶ 4,309:
stdout.printf("%d ", i);
}
}</langsyntaxhighlight>
 
{{out}}
Line 4,103 ⟶ 4,317:
 
=={{header|VBA}}==
{{trans|Phix}}<langsyntaxhighlight lang="vb">Function cocktail_sort(ByVal s As Variant) As Variant
Dim swapped As Boolean
Dim f As Integer, t As Integer, d As Integer, tmp As Integer
Line 4,138 ⟶ 4,352:
Debug.Print Join(s, ", ")
Debug.Print Join(cocktail_sort(s), ", ")
End Sub</langsyntaxhighlight>{{out}}
<pre>45, 414, 862, 790, 373, 961, 871, 56, 949, 364
45, 56, 364, 373, 414, 790, 862, 871, 949, 961</pre>
Line 4,146 ⟶ 4,360:
 
;Implementation
<langsyntaxhighlight lang="vb">function cocktailSort( byval a )
dim swapped
dim i
Line 4,175 ⟶ 4,389:
a = b
b = tmp
end sub</langsyntaxhighlight>
;Invocation
<langsyntaxhighlight lang="vb">dim a
a = array( "portcullis", "redoubt", "palissade", "turret", "collins", "the parapet", "the quarterdeck")
wscript.echo join( a, ", ")
Line 4,183 ⟶ 4,397:
dim b
b = cocktailSort( a )
wscript.echo join( b, ", ")</langsyntaxhighlight>
{{out}}
<pre>
Line 4,190 ⟶ 4,404:
</pre>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">fn cocktail(arr mut arr []int) {
input := 'Input'
output := 'Output'
Line 4,229 ⟶ 4,443:
arr = [-8, 15, 1, 4, -3, 20]
cocktail(mut arr)
}</langsyntaxhighlight>
{{out}}
<pre>Input : [6, 9, 1, 4]
Line 4,238 ⟶ 4,452:
=={{header|Wren}}==
{{trans|Go}}
<langsyntaxhighlight ecmascriptlang="wren">var cocktailSort = Fn.new { |a|
var last = a.count - 1
while (true) {
Line 4,269 ⟶ 4,483:
System.print("Before: %(a)")
cocktailSort.call(a)
System.print("After : %(a)")</langsyntaxhighlight>
 
{{out}}
Line 4,278 ⟶ 4,492:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">code ChOut=8, IntOut=11;
 
proc CocktailSort(A, L); \Sort array A of length L
Line 4,305 ⟶ 4,519:
CocktailSort(A, 10);
for I:= 0 to 10-1 do [IntOut(0, A(I)); ChOut(0, ^ )];
]</langsyntaxhighlight>
 
{{out}}
Line 4,314 ⟶ 4,528:
=={{header|zkl}}==
This has the Wikipedia optimizations.
<langsyntaxhighlight lang="zkl">fcn cocktailSort(a){
swapped,begin,end:=False,-1,a.len() - 2;
do{
Line 4,328 ⟶ 4,542:
}while(swapped);
a
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">cocktailSort(List(2,1)).println();
x:=List(5, -1, 101, -4, 0, 1, 8, 6, 2, 3 );
cocktailSort(x).println();
x="the lazy fox jumped over the brown dog".split(" ").copy();
cocktailSort(x).println();</langsyntaxhighlight>
{{out}}
<pre>
Line 4,343 ⟶ 4,557:
=={{header|ZX Spectrum Basic}}==
its a "cocktail" bubble sort, but the writer called it 'zigzag' since the name was unknown
<langsyntaxhighlight lang="zxbasic">5000 CLS
5002 LET a$="": FOR f=1 TO 64: LET a$=a$+CHR$ (32+INT (RND*96)): NEXT f
5004 PRINT a$; AT 10,0;"ZigZag BubbleSORT"
Line 4,363 ⟶ 4,577:
5064 IF d AND i<la THEN GO TO 5020
5072 PRINT AT 12,0;a$
9000 STOP</langsyntaxhighlight>
Next is an optimisation by using the margin value's as swop comparative aswell
so its swops inside and at the edges from the file
Line 4,369 ⟶ 4,583:
its a " Sticky (edge) Cocktail Sort"
By C. Born (freeware)
<langsyntaxhighlight lang="zxbasic">5000 CLS : PRINT ;"Jumping Zig Zag BubbleSORT"'"aka Sticky Cocktail Sort"
5002 LET a$="": FOR f=1 TO 96: LET a$=a$+CHR$ (48+INT (RND*48)): NEXT f
5004 PRINT 'a$
Line 4,401 ⟶ 4,615:
5510 IF i-1>=1 THEN IF a$(i)=a$(i-1) THEN LET i=i+1: GO TO 5500
5520 RETURN
9999 CLEAR : SAVE "JZZB" LINE 0</langsyntaxhighlight>
 
{{omit from|GUISS}}
9,476

edits