Sorting algorithms/Cocktail sort: Difference between revisions
m
→{{header|Wren}}: Changed to Wren S/H
m (Minor edit) |
m (→{{header|Wren}}: Changed to Wren S/H) |
||
(32 intermediate revisions by 21 users not shown) | |||
Line 1:
{{task|Sorting Algorithms}}
{{Sorting Algorithm}}
[[Category:Sorting]]
{{Wikipedia|Cocktail sort}}
Line 31 ⟶ 32:
:* [https://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort_with_shifting_bounds cocktail sort with shifting bounds]
<br><br>
=={{header|11l}}==
{{trans|Python}}
<syntaxhighlight lang="11l">F cocktailSort(&A)
L
L(indices) ((0 .< A.len-1).step(1), (A.len-2 .. 0).step(-1))
V swapped = 0B
L(i) indices
I A[i] > A[i + 1]
swap(&A[i], &A[i + 1])
swapped = 1B
I !swapped
R
V test1 = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]
cocktailSort(&test1)
print(test1)</syntaxhighlight>
{{out}}
<pre>
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</pre>
=={{header|360 Assembly}}==
{{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.
<
COCKTSRT CSECT
USING COCKTSRT,R13 base register
Line 105 ⟶ 129:
YREGS
RI EQU 6 i
END COCKTSRT</
{{out}}
<pre>
-31 0 1 2 2 4 45 58 65 69 74 82 82 83 88 89 99 104 112 782
</pre>
=={{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.
<syntaxhighlight lang="6502asm">define z_HL $00
define z_L $00
define z_H $01
define temp $02
define temp2 $03
define yINC $04
define yDEC $05
set_table:
dex
txa
sta $1200,y
iny
bne set_table ;stores $ff at $1200, $fe at $1201, etc.
lda #$12
sta z_H
lda #$00
sta z_L ;get the base address of the data table
lda #0
tax
tay ;clear regs
sty yINC ;yINC = 0
dey ;LDY #255
sty yDEC ;yDEC = 255
iny ;LDY #0
JSR COCKTAILSORT
BRK
COCKTAILSORT:
;yINC starts at the beginning and goes forward, yDEC starts at the end and goes back.
LDY yINC
LDA (z_HL),y ;get item Y
STA temp
INY
LDA (z_HL),y ;get item Y+1
DEY
STA temp2
CMP temp
bcs doNothing_Up ;if Y<=Y+1, do nothing. Otherwise swap them.
;we had to re-arrange an item.
lda temp
iny
sta (z_HL),y ;store the higher value at base+y+1
inx ;sort count. If zero at the end, we're done.
dey
lda temp2
sta (z_HL),y ;store the lower value at base+y
doNothing_Up:
LDY yDEC
LDA (z_HL),y
STA temp
DEY
LDA (z_HL),y
INY
STA temp2
CMP temp
bcc doNothing_Down ;if Y<=Y+1, do nothing. Otherwise swap them.
;we had to re-arrange an item.
lda temp
dey
sta (z_HL),y ;store the higher value at base+y+1
inx ;sort count. If zero at the end, we're done.
iny
lda temp2
sta (z_HL),y ;store the lower value at base+y
doNothing_Down:
INC yINC
DEC yDEC
LDA yINC
BPL COCKTAILSORT
CPX #0
BEQ doneSorting
LDX #0 ;reset the counter
LDY #0
STY yINC
DEY ;LDY #$FF
STY yDEC
INY ;LDY #0
JMP COCKTAILSORT
doneSorting:
RTS</syntaxhighlight>
{{out}}
<pre>
1200: 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f
1210: 10 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f
1220: 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f
1230: 30 31 32 33 34 35 36 37 38 39 3a 3b 3c 3d 3e 3f
1240: 40 41 42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f
1250: 50 51 52 53 54 55 56 57 58 59 5a 5b 5c 5d 5e 5f
1260: 60 61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f
1270: 70 71 72 73 74 75 76 77 78 79 7a 7b 7c 7d 7e 7f
1280: 80 81 82 83 84 85 86 87 88 89 8a 8b 8c 8d 8e 8f
1290: 90 91 92 93 94 95 96 97 98 99 9a 9b 9c 9d 9e 9f
12a0: a0 a1 a2 a3 a4 a5 a6 a7 a8 a9 aa ab ac ad ae af
12b0: b0 b1 b2 b3 b4 b5 b6 b7 b8 b9 ba bb bc bd be bf
12c0: c0 c1 c2 c3 c4 c5 c6 c7 c8 c9 ca cb cc cd ce cf
12d0: d0 d1 d2 d3 d4 d5 d6 d7 d8 d9 da db dc dd de df
12e0: e0 e1 e2 e3 e4 e5 e6 e7 e8 e9 ea eb ec ed ee ef
12f0: f0 f1 f2 f3 f4 f5 f6 f7 f8 f9 fa fb fc fd fe ff
</pre>
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program cocktailSort64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeConstantesARM64.inc"
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessSortOk: .asciz "Table sorted.\n"
szMessSortNok: .asciz "Table not sorted !!!!!.\n"
sMessResult: .asciz "Value : @ \n"
szCarriageReturn: .asciz "\n"
.align 4
#TableNumber: .quad 1,3,6,2,5,9,10,8,4,7
TableNumber: .quad 10,9,8,7,6,-5,4,3,2,1
.equ NBELEMENTS, (. - TableNumber) / 8
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrTableNumber // address number table
mov x1,0
mov x2,NBELEMENTS // number of élements
bl cocktailSort
ldr x0,qAdrTableNumber // address number table
bl displayTable
ldr x0,qAdrTableNumber // address number table
mov x1,NBELEMENTS // number of élements
bl isSorted // control sort
cmp x0,1 // sorted ?
beq 1f
ldr x0,qAdrszMessSortNok // no !! error sort
bl affichageMess
b 100f
1: // yes
ldr x0,qAdrszMessSortOk
bl affichageMess
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrsZoneConv: .quad sZoneConv
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsMessResult: .quad sMessResult
qAdrTableNumber: .quad TableNumber
qAdrszMessSortOk: .quad szMessSortOk
qAdrszMessSortNok: .quad szMessSortNok
/******************************************************************/
/* control sorted table */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains the number of elements > 0 */
/* x0 return 0 if not sorted 1 if sorted */
isSorted:
stp x2,lr,[sp,-16]! // save registers
stp x3,x4,[sp,-16]! // save registers
mov x2,0
ldr x4,[x0,x2,lsl 3]
1:
add x2,x2,1
cmp x2,x1
bge 99f
ldr x3,[x0,x2, lsl 3]
cmp x3,x4
blt 98f
mov x4,x3
b 1b
98:
mov x0,0 // not sorted
b 100f
99:
mov x0,1 // sorted
100:
ldp x3,x4,[sp],16 // restaur 2 registers
ldp x2,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* cocktail sort */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains the first element */
/* x2 contains the number of element */
cocktailSort:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
stp x6,x7,[sp,-16]! // save registers
stp x8,x9,[sp,-16]! // save registers
sub x2,x2,1 // compute i = n - 1
1: // start loop 1
mov x3,x1 // start index
mov x9,0
sub x7,x2,1
2: // start loop 2
add x4,x3,1
ldr x5,[x0,x3,lsl 3] // load value A[j]
ldr x6,[x0,x4,lsl 3] // load value A[j+1]
cmp x6,x5 // compare value
bge 3f
str x6,[x0,x3,lsl 3] // if smaller inversion
str x5,[x0,x4,lsl 3]
mov x9,1 // top table not sorted
3:
add x3,x3,1 // increment index j
cmp x3,x7 // end ?
ble 2b // no -> loop 2
cmp x9,0 // table sorted ?
beq 100f // yes -> end
mov x9,0
mov x3,x7
4:
add x4,x3,1
ldr x5,[x0,x3,lsl 3] // load value A[j]
ldr x6,[x0,x4,lsl 3] // load value A[j+1]
cmp x6,x5 // compare value
bge 5f
str x6,[x0,x3,lsl 3] // if smaller inversion
str x5,[x0,x4,lsl 3]
mov x9,1 // top table not sorted
5:
sub x3,x3,1 // decrement index j
cmp x3,x1 // end ?
bge 4b // no -> loop 2
cmp x9,0 // table sorted ?
bne 1b // no -> loop 1
100:
ldp x8,x9,[sp],16 // restaur 2 registers
ldp x6,x7,[sp],16 // restaur 2 registers
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* Display table elements */
/******************************************************************/
/* x0 contains the address of table */
displayTable:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
mov x2,x0 // table address
mov x3,0
1: // loop display table
ldr x0,[x2,x3,lsl 3]
ldr x1,qAdrsZoneConv
bl conversion10S // décimal conversion
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
add x3,x3,1
cmp x3,NBELEMENTS - 1
ble 1b
ldr x0,qAdrszCarriageReturn
bl affichageMess
100:
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
=={{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}}==
<
do {
var swapped:Boolean=false;
Line 136 ⟶ 552:
} while (swapped);
return input;
}</
=={{header|Ada}}==
<
procedure Cocktail_Sort_Test is
Line 175 ⟶ 591:
Cocktail_Sort(Data);
Put_Line(Data);
end Cocktail_Sort_Test;</
=={{header|ALGOL 60}}==
{{works with|A60}}
<
comment Sorting algorithms/Cocktail sort - Algol 60;
nA:=20;
begin
integer
begin
lbx:=lb; ubx:=ub-1; swapped
for i:=1 while swapped
swapped:=true
end swap;
swapped:=false;
for i:=lbx step 1 until ubx do if A[i]>A[i+1] then swap(i);
if swapped
then begin
for i:=ubx step -1 until lbx do if A[i]>A[i+1] then swap(i);
ubx:=ubx-1; lbx:=lbx+1
end
end
end cocktailsort;
procedure inittable(lb,ub);
integer i;
for i:=lb step 1 until ub do A[i]:=entier(rand*100)
end inittable;
procedure writetable(lb,ub);
integer i;
for i:=lb step 1 until ub do outinteger(1,A[i]);
nA:=20;
inittable(1,nA
end
end </
{{out}}
<pre>
Line 236 ⟶ 657:
3 6 14 16 19 23 28 33 33 47 61 62 64 67 73 77 78 81 83 92
</pre>
=={{header|ALGOL 68}}==
<
PROC swap = (REF DATA a,b)VOID:(
DATA tmp:=a; a:=b; b:=tmp
Line 271 ⟶ 691:
[32]CHAR data := "big fjords vex quick waltz nymph";
cocktail sort(data);
print(data)</
{{out}}
<pre> abcdefghiijklmnopqrstuvwxyz</pre>
Line 277 ⟶ 697:
indirectly, thus removing the need to actually swap large chunks of memory
as only addresses are swapped.
<
PROC swap = (REF DATA a,b)VOID:(
DATA tmp:=a; a:=b; b:=tmp
Line 288 ⟶ 708:
cocktail sort(ref data);
FOR i TO UPB ref data DO print(ref data[i]) OD; print(new line);
print((data))</
{{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%.
<
FOR offset FROM 0 DO
BOOL swapped := FALSE;
Line 314 ⟶ 734:
OD;
break do od loop: SKIP
);</
=={{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.
<
% As algol W does not allow overloading, we have to have type-specific %
% sorting procedures - this coctail sorts an integer array %
Line 383 ⟶ 803:
writeData;
end test ;
end.</
{{out}}
<pre>
Line 389 ⟶ 809:
-6 0 2 8 9 9 14 16 23 90
</pre>
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program cocktailSort.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes */
/************************************/
.include "../constantes.inc"
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessSortOk: .asciz "Table sorted.\n"
szMessSortNok: .asciz "Table not sorted !!!!!.\n"
sMessResult: .asciz "Value : @ \n"
szCarriageReturn: .asciz "\n"
.align 4
#TableNumber: .int 1,3,6,2,5,9,10,8,4,7
TableNumber: .int 10,9,8,7,6,5,4,3,2,1
.equ NBELEMENTS, (. - TableNumber) / 4
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
1:
ldr r0,iAdrTableNumber @ address number table
mov r1,#0
mov r2,#NBELEMENTS @ number of élements
bl cocktailSort
ldr r0,iAdrTableNumber @ address number table
bl displayTable
ldr r0,iAdrTableNumber @ address number table
mov r1,#NBELEMENTS @ number of élements
bl isSorted @ control sort
cmp r0,#1 @ sorted ?
beq 2f
ldr r0,iAdrszMessSortNok @ no !! error sort
bl affichageMess
b 100f
2: @ yes
ldr r0,iAdrszMessSortOk
bl affichageMess
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsMessResult: .int sMessResult
iAdrTableNumber: .int TableNumber
iAdrszMessSortOk: .int szMessSortOk
iAdrszMessSortNok: .int szMessSortNok
/******************************************************************/
/* control sorted table */
/******************************************************************/
/* r0 contains the address of table */
/* r1 contains the number of elements > 0 */
/* r0 return 0 if not sorted 1 if sorted */
isSorted:
push {r2-r4,lr} @ save registers
mov r2,#0
ldr r4,[r0,r2,lsl #2]
1:
add r2,#1
cmp r2,r1
movge r0,#1
bge 100f
ldr r3,[r0,r2, lsl #2]
cmp r3,r4
movlt r0,#0
blt 100f
mov r4,r3
b 1b
100:
pop {r2-r4,lr}
bx lr @ return
/******************************************************************/
/* cocktail Sort */
/******************************************************************/
/* r0 contains the address of table */
/* r1 contains the first element */
/* r2 contains the number of element */
cocktailSort:
push {r1-r9,lr} @ save registers
sub r2,r2,#1 @ compute i = n - 1
add r8,r1,#1
1: @ start loop 1
mov r3,r1 @ start index
mov r9,#0
sub r7,r2,#1 @ max
2: @ start loop 2
add r4,r3,#1
ldr r5,[r0,r3,lsl #2] @ load value A[j]
ldr r6,[r0,r4,lsl #2] @ load value A[j+1]
cmp r6,r5 @ compare value
strlt r6,[r0,r3,lsl #2] @ if smaller inversion
strlt r5,[r0,r4,lsl #2]
movlt r9,#1 @ top table not sorted
add r3,#1 @ increment index j
cmp r3,r7 @ end ?
ble 2b @ no -> loop 2
cmp r9,#0 @ table sorted ?
beq 100f @ yes -> end
@ bl displayTable
mov r9,#0
mov r3,r7
3:
add r4,r3,#1
ldr r5,[r0,r3,lsl #2] @ load value A[j]
ldr r6,[r0,r4,lsl #2] @ load value A[j+1]
cmp r6,r5 @ compare value
strlt r6,[r0,r3,lsl #2] @ if smaller inversion
strlt r5,[r0,r4,lsl #2]
movlt r9,#1 @ top table not sorted
sub r3,#1 @ decrement index j
cmp r3,r1 @ end ?
bge 3b @ no -> loop 2
@ bl displayTable
cmp r9,#0 @ table sorted ?
bne 1b @ no -> loop 1
100:
pop {r1-r9,lr}
bx lr @ return
/******************************************************************/
/* Display table elements */
/******************************************************************/
/* r0 contains the address of table */
displayTable:
push {r0-r3,lr} @ save registers
mov r2,r0 @ table address
mov r3,#0
1: @ loop display table
ldr r0,[r2,r3,lsl #2]
ldr r1,iAdrsZoneConv @
bl conversion10S @ décimal conversion signed
ldr r0,iAdrsMessResult
ldr r1,iAdrsZoneConv @ insert conversion
bl strInsertAtCharInc
bl affichageMess @ display message
add r3,#1
cmp r3,#NBELEMENTS - 1
ble 1b
ldr r0,iAdrszCarriageReturn
bl affichageMess
100:
pop {r0-r3,lr}
bx lr
iAdrsZoneConv: .int sZoneConv
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
</syntaxhighlight>
=={{header|Arturo}}==
<syntaxhighlight lang="rebol">trySwap: function [arr,i][
if arr\[i] < arr\[i-1] [
tmp: arr\[i]
arr\[i]: arr\[i-1]
arr\[i-1]: tmp
return null
]
return true
]
cocktailSort: function [items][
t: false
l: size items
while [not? t][
t: true
loop 1..dec l 'i [
if null? trySwap items i ->
t: false
]
if t -> break
loop (l-1)..1 'i [
if null? trySwap items i ->
t: false
]
]
return items
]
print cocktailSort [3 1 2 8 5 7 9 4 6]</syntaxhighlight>
{{out}}
<pre>1 2 3 4 5 6 7 8 9</pre>
=={{header|AutoHotkey}}==
contributed by Laszlo on the ahk [http://www.autohotkey.com/forum/post-276379.html#276379 forum]
<
MsgBox % CocktailSort("xxx")
MsgBox % CocktailSort("3,2,1")
Line 423 ⟶ 1,052:
sorted .= "," . array%A_Index%
Return SubStr(sorted,2) ; drop leading comma
}</
=={{header|AWK}}==
Sort the standard input and print it to standard output
<
line[NR] = $0
}
Line 456 ⟶ 1,085:
print line[i]
}
}</
=={{header|BBC BASIC}}==
Sorting an integer array. '%' indicates integer variable in BBC BASIC
<
Start%=2
Line 478 ⟶ 1,107:
UNTIL ( ( End% * Direction% ) < ( Start% * Direction% ) )
ENDPROC</
=={{header|C}}==
<
// can be any swap function. This swap is optimized for numbers.
Line 519 ⟶ 1,148:
printf("%d ", a[i]);
return 0;
}</
'''Output''':
<syntaxhighlight lang="text">-4 -1 0 1 2 3 5 6 8 101</
===Generic version===
This version can be used with arrays of any type, like the standard library function qsort.
<
#include <stdio.h>
#include <string.h>
Line 590 ⟶ 1,219:
print(a, len);
return 0;
}</
{{out}}
Line 599 ⟶ 1,228:
=={{header|C sharp|C#}}==
<
{
bool swapped;
Line 634 ⟶ 1,263:
//if no elements have been swapped, then the list is sorted
} while (swapped);
}</
=={{header|C++}}==
<
#include <iostream>
#include <windows.h>
Line 718 ⟶ 1,347:
return 0;
}
</syntaxhighlight>
=== Alternate version ===
Uses C++11. Compile with
g++ -std=c++11 cocktail.cpp
<
#include <iostream>
#include <iterator>
Line 757 ⟶ 1,386:
copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
}</
{{out}}
<pre>
Line 765 ⟶ 1,394:
=={{header|COBOL}}==
This is procedure division only.
<
C-000.
DISPLAY "SORT STARTING".
Line 802 ⟶ 1,431:
F-999.
EXIT.</
=={{header|Common Lisp}}==
This version works on lists and vectors alike. The vector implementation is coded directly. The list version uses an intermediate vector.
<
(labels ((scan (start step &aux swapped)
(loop for i = start then (+ i step) while (< 0 i len) do
Line 824 ⟶ 1,453:
(list (map-into sequence 'identity
(cocktail-sort-vector (coerce sequence 'vector)
predicate)))))</
=={{header|D}}==
<
module rosettaCode.sortingAlgorithms.cocktailSort;
Line 864 ⟶ 1,493:
["Alice", "Jane", "Joe", "John", "Kate", "Zerg"]);
}
</syntaxhighlight>
{{out}}
<syntaxhighlight lang="d">
import rosettaCode.sortingAlgorithms.cocktailSort;
Line 874 ⟶ 1,503:
//generate 10 sorted random numbers in [0 .. 10)
rndGen.take(10).map!(a=>a%10).array.cocktailSort.writeln();
}</
<pre>[2, 2, 3, 4, 5, 5, 7, 7, 7, 8]</pre>
Line 881 ⟶ 1,510:
Static array is an arbitrary-based array of fixed length
<
{$APPTYPE CONSOLE}
Line 944 ⟶ 1,573:
Writeln;
Readln;
end.</
{{out}}
<pre>
Line 952 ⟶ 1,581:
=={{header|E}}==
<
def cocktailSort(array) {
def swapIndexes := 0..(array.size() - 2)
Line 968 ⟶ 1,597:
}
}
}</
Note that this solution contains no repeated code to handle the forward and reverse passes.
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
class
Line 1,065 ⟶ 1,694:
end
</syntaxhighlight>
Test:
<syntaxhighlight lang="eiffel">
class
Line 1,103 ⟶ 1,732:
end
</syntaxhighlight>
{{out}}
<pre>
Line 1,113 ⟶ 1,742:
=={{header|Elena}}==
ELENA
<
import system'math;
import system'routines;
Line 1,129 ⟶ 1,758:
swapped := false;
for(int i := 0
{
if (list[i]>list[i+1])
Line 1,143 ⟶ 1,772:
swapped := false;
for(int i := list.Length - 2
{
if (list[i]>list[i+1])
Line 1,163 ⟶ 1,792:
console.printLine("before:", list.asEnumerable());
console.printLine("after :", list.cocktailSort().asEnumerable())
}</
{{out}}
<pre>
Line 1,171 ⟶ 1,800:
=={{header|Elixir}}==
<
def cocktail_sort(list) when is_list(list), do: cocktail_sort(list, [], [])
Line 1,191 ⟶ 1,820:
end
IO.inspect Sort.cocktail_sort([5,3,9,4,1,6,8,2,7])</
{{out}}
Line 1,199 ⟶ 1,828:
=={{header|Euphoria}}==
<
integer swapped, d
object temp
Line 1,223 ⟶ 1,852:
constant s = rand(repeat(1000,10))
? s
? cocktail_sort(s)</
{{out}}
<pre>{963,398,374,455,53,210,611,285,984,308}
Line 1,232 ⟶ 1,861:
===Pseudocode translation===
This is a faithful translation of the pseudocode given in the task description. It uses lexical variables.
<
:: cocktail-sort! ( seq -- seq' )
Line 1,249 ⟶ 1,878:
] when
] do while
seq ; ! return the sequence</
===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.
<
SYMBOL: swapped?
Line 1,273 ⟶ 1,902:
: cocktail-sort! ( seq -- seq' )
[ swapped? get ] [ (cocktail-sort!) ] do while ;</
=={{header|Forth}}==
<
\ e.g. ' < is precedes
: sort ( a n --)
Line 1,294 ⟶ 1,923:
-1 cells +loop
repeat then drop 2r> 2drop
;</
This is an optimized version:
<
1- cells bounds 1
begin
Line 1,307 ⟶ 1,936:
>r negate >r swap r@ cells + r> r>
until drop drop drop
;</
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<
IMPLICIT NONE
Line 1,354 ⟶ 1,983:
END SUBROUTINE Cocktail_sort
END PROGRAM COCKTAIL</
=={{header|FreeBASIC}}==
<
' compile with: fbc -s console
' for boundry checks on array's compile with: fbc -s console -exx
Line 1,414 ⟶ 2,043:
Print : Print "hit any key to end program"
Sleep
End</
{{out}}
<pre>unsorted -2 -4 7 -5 -7 4 2 -1 5 -6 6 1 0 -3 3
Line 1,421 ⟶ 2,050:
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=ee5467e58f0ef649373eed5a2503b988 Click this link to run this code]'''
<
Dim siCount, siRev, siProcess As Short
Dim bSorting As Boolean
Line 1,467 ⟶ 2,096:
Print
End</
Output:
<pre>
Line 1,484 ⟶ 2,113:
=={{header|Go}}==
<
import "fmt"
Line 1,519 ⟶ 2,148:
}
}
}</
More generic version that sorts anything that implements <code>sort.Interface</code>:
<
import (
Line 1,559 ⟶ 2,188:
}
}
}</
=={{header|Groovy}}==
Solution:
<
def checkSwap = { a, i, j = i+1 -> [(a[i] > a[j])].find{ it }.each { makeSwap(a, i, j) } }
Line 1,576 ⟶ 2,205:
}
list
}</
Test:
<
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 ])</
{{out}}
<pre>..............................................................................................................................................[4, 12, 14, 23, 24, 24, 31, 35, 38, 46, 51, 57, 57, 58, 76, 78, 89, 92, 95, 97, 99]
Line 1,592 ⟶ 2,221:
=={{header|Haskell}}==
<
cocktailSort l
| not swapped1 = l
Line 1,605 ⟶ 2,234:
| otherwise = swappingPass op (swapped, x1 : l) (x2 : xs)
swappingPass _ (swapped, l) [x] = (swapped, x : l)
swappingPass _ pair [] = pair</
=={{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}}==
<
@:generic
public static function sort<T>(arr:Array<T>) {
Line 1,656 ⟶ 2,337:
Sys.println('Sorted Strings: ' + stringArray);
}
}</
{{out}}
Line 1,669 ⟶ 2,350:
=={{header|Icon}} and {{header|Unicon}}==
<
demosort(cocktailsort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty")
end
Line 1,685 ⟶ 2,366:
X[i+1] :=: X[swapped := i]
return X
end</
Note: This example relies on [[Sorting_algorithms/Bubble_sort#Icon| the supporting procedures 'sortop', and 'demosort' in Bubble Sort]].
Line 1,698 ⟶ 2,379:
=={{header|Io}}==
<
cocktailSortInPlace := method(
start := 0
Line 1,728 ⟶ 2,409:
l := list(2, 3, 4, 5, 1)
l cocktailSortInPlace println # ==> list(1, 2, 3, 4, 5)</
=={{header|IS-BASIC}}==
<
110 RANDOMIZE
120 NUMERIC ARRAY(5 TO 24)
Line 1,757 ⟶ 2,438:
340 LET EN=ST:LET ST=CH-D:LET D=-1*D
350 LOOP UNTIL EN*D<ST*D
360 END DEF</
=={{header|J}}==
{{eff note|J|/:~}}
<
smallToLeft=: (([ (<. , >.) {.@]) , }.@])/
cocktailSort=: |. @: (|. @: smallToLeft @: |. @: bigToLeft ^:_)</
Test run:
<
4 6 8 6 5 8 6 6 6 9
cocktailSort ?. 10 $ 10
4 5 6 6 6 6 6 8 8 9</
As is usual with J, <code>/:~</code> is the preferred method of sorting in practice.
Line 1,774 ⟶ 2,455:
This algorithm sorts in place.
Call it with a copy of the array to preserve the unsorted order.
<
boolean swapped;
do {
Line 1,802 ⟶ 2,483:
//if no elements have been swapped, then the list is sorted
} while (swapped);
}</
=={{header|JavaScript}}==
<
// Node 5.4.1 tested implementation (ES6)
"use strict";
Line 1,839 ⟶ 2,520:
console.log(arr);
}</
Line 1,849 ⟶ 2,530:
=={{header|jq}}==
{{ works with|jq|1.4}}
<
def until(cond; next):
def _until:
if cond then . else (next|_until) end;
_until;</
<
def swap(i;j): .[i] as $t | .[i] = .[j] | .[j] = $t;
Line 1,876 ⟶ 2,557:
else .
end )
| .[1];</
'''Tests:'''
<
([],
Line 1,890 ⟶ 2,571:
[1.5, -1.5],
["cocktail", ["sort"], null, {}]
) | verify</
{{out}}
<
$</
=={{header|Julia}}==
{{works with|Julia|0.6}}
<
b = copy(a)
isordered = false
Line 1,924 ⟶ 2,605:
v = rand(-10:10, 10)
println("# unordered: $v\n -> ordered: ", cocktailsort(v))</
{{out}}
Line 1,931 ⟶ 2,612:
=={{header|Kotlin}}==
<
fun cocktailSort(a: IntArray) {
Line 1,967 ⟶ 2,648:
println(a.joinToString(", "))
}
}</
{{out}}
Line 1,977 ⟶ 2,658:
=={{header|Lua}}==
<
local swapped
repeat
Line 1,999 ⟶ 2,680:
until swapped==false
end</
{{out|Example}}
<
cocktailSort(list)
for i=1,#list do
print(list[i]j)
end</
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module cocktailSort {
k=(3,2,1)
print k
cocktailSort(k)
print k
k=("c","b","a")
print k
cocktailSortString(k)
print k
Dim a(5)
a(0)=1,2,5,6,3
print a()
cocktailSort(a())
print a()
End
Sub cocktailSort(a)
\\ this is like Link a to a() but using new for a() - shadow any a()
push &a : read new &a()
local swapped, lenA2=len(a)-2
do
for i=0 to lenA2
if a(i) > a(i+1) then swap a(i), a(i+1): swapped = true
next
if swapped then
swapped~
for i=lenA2 to 0
if a(i) > a(i+1) then swap a(i), a(i+1): swapped = true
next
end if
until not swapped
End Sub
Sub cocktailSortString(a)
push &a : read new &a$()
local swapped, lenA2=len(a)-2
do
for i=0 to lenA2
if a$(i) > a$(i+1) then
swap a$(i), a$(i+1)
swapped = true
end if
next
if swapped then
swapped~
for i=lenA2 to 0
if a$(i) > a$(i+1) then
swap a$(i), a$(i+1)
swapped = true
end if
next
end if
until not swapped
End Sub
}
cocktailSort
</syntaxhighlight>
{{out}}
<pre>
3 2 1
1 2 3
c b a
a b c
1 2 5 6 3
1 2 3 5 6
</pre>
=={{header|Maple}}==
<
len := numelems(arr):
swap := proc(arr, a, b)
Line 2,033 ⟶ 2,781:
if (not swapped) then break: end if:
end do:
arr;</
{{Output|Out}}
<pre>[0,0,2,3,3,8,17,36,40,72]</pre>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
While[ swapped == True,
swapped=False;
Line 2,048 ⟶ 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;]
]]]</
{{out|Example}}
<pre>cocktailSort[{2,1,5,3,6}]
Line 2,054 ⟶ 2,802:
=={{header|MATLAB}} / {{header|Octave}}==
<
%We have to do this because the do...while loop doesn't exist in MATLAB
Line 2,083 ⟶ 2,831:
end %for
end %while
end %cocktail sort</
{{out|Sample usage}}
<
ans =
1 2 3 4 5 6 7 8 9</
=={{header|MAXScript}}==
<
(
local swapped = true
Line 2,117 ⟶ 2,865:
)
return arr
)</
=={{header|NetRexx}}==
<
options replace format comments java crossref savelog symbols binary
Line 2,176 ⟶ 2,924:
method isFalse public constant binary returns boolean
return \isTrue</
{{out}}
<pre>
Line 2,199 ⟶ 2,947:
=={{header|Nim}}==
<syntaxhighlight lang
if a[i] < a[i-1]:
swap a[i], a[i-1]
Line 2,209 ⟶ 2,957:
while not t:
t = true
for i in 1 ..
if t: break
for i in countdown(l-1, 1): trySwap
Line 2,215 ⟶ 2,963:
var a = @[4, 65, 2, -31, 0, 99, 2, 83, 782]
cocktailSort a
echo a</
{{out}}
<pre>@[-31, 0, 2, 2, 4, 65, 83, 99, 782]</pre>
=={{header|Objeck}}==
<
class Cocktail {
function : Main(args : String[]) ~ Nil {
Line 2,261 ⟶ 3,009:
}
}
}</
=={{header|OCaml}}==
<
let tmp = a.(i) in
a.(i) <- a.(j);
Line 2,300 ⟶ 3,048:
Array.iter (Printf.printf " %d") a;
print_newline();
;;</
{{out}}
<pre>
Line 2,307 ⟶ 3,055:
=={{header|Octave}}==
<
swapped = true;
while(swapped)
Line 2,333 ⟶ 3,081:
endwhile
sl = l;
endfunction</
{{out|Example}}
<
1, 8, 6, 2, 3 ]);
disp(s);</
=={{header|ooRexx}}==
{{Trans|NetRexx}}
<
placesList = .array~of( -
Line 2,391 ⟶ 3,139:
end swaps
return A</
{{out}}
<pre>
Line 2,414 ⟶ 3,162:
=={{header|Oz}}==
<
proc {CocktailSort Arr}
proc {Swap I J}
Line 2,439 ⟶ 3,187:
in
{CocktailSort Arr}
{Inspect Arr}</
=={{header|PARI/GP}}==
<
while(1,
my(done=1);
Line 2,465 ⟶ 3,213:
if(done, return(v))
)
};</
=={{header|Pascal}}==
Line 2,471 ⟶ 3,219:
=={{header|Perl}}==
<
use warnings;
use feature 'say';
sub cocktail_sort {
my @a = @_;
while (1) {
my $swapped_forward = 0;
for my $i (0..$#a-1) {
if ($a[$i] gt $a[$i+1]) {
}
last if not $swapped_forward;
my $swapped_backward = 0;
for my $i (reverse 0..$#a-1) {
if ($
@a[$i, $i+1] = @a[$i+1, $i];
$swapped_backward = 1;
}
}
last if not $swapped_backward;
}
@a
}
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> );</syntaxhighlight>
{{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}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">cocktail_sort</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">deep_copy</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">swapped</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">f</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">t</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">d</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">swapped</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">swapped</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">f</span> <span style="color: #008080;">to</span> <span style="color: #000000;">t</span> <span style="color: #008080;">by</span> <span style="color: #000000;">d</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">object</span> <span style="color: #000000;">si</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span>
<span style="color: #000000;">sn</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">si</span><span style="color: #0000FF;">></span><span style="color: #000000;">sn</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">sn</span>
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">si</span>
<span style="color: #000000;">swapped</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000080;font-style:italic;">-- swap to and from, and flip direction.
-- additionally, we can reduce one element to be
-- examined, depending on which way we just went.</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">f</span><span style="color: #0000FF;">,</span><span style="color: #000000;">t</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">t</span><span style="color: #0000FF;">-</span><span style="color: #000000;">d</span><span style="color: #0000FF;">,</span><span style="color: #000000;">f</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">d</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sq_rand</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1000</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</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;">"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>
<!--</syntaxhighlight>-->
{{out}}
<pre>
original: {
sorted: {
</pre>
=={{header|PHP}}==
<
if (is_string($arr)) $arr = str_split(preg_replace('/\s+/','',$arr));
Line 2,582 ⟶ 3,325:
echo implode(',',$arr) . '<br>';
echo implode(',',$arr2) . '<br>';
echo implode('',$strg) . '<br>';</
{{out}}
<pre>
Line 2,591 ⟶ 3,334:
=={{header|PicoLisp}}==
<
(use (Swapped L)
(loop
Line 2,609 ⟶ 3,352:
(on Swapped) )
(T (== Lst L)) )
(NIL Swapped Lst) ) ) )</
{{out}}
<pre>: (cocktailSort (make (do 9 (link (rand 1 999)))))
Line 2,617 ⟶ 3,360:
=={{header|PL/I}}==
<
declare A(*) fixed;
declare t fixed;
Line 2,633 ⟶ 3,376:
end;
end;
end cocktail;</
=={{header|PowerShell}}==
Based on the entry for PowerShell in [[Bubble Sort]]
<
$l = $a.Length
$m = 0
Line 2,668 ⟶ 3,411:
}
$l = 10; CocktailSort ( 1..$l | ForEach-Object { $Rand = New-Object Random }{ $Rand.Next( -( $l - 1 ), $l - 1 ) } )</
=={{header|Prolog}}==
<
ctail(fwrd, [A,B|T], In, Rev, unsorted) :- A > B, !,
ctail(fwrd, [B,A|T], In, Rev, _).
Line 2,689 ⟶ 3,432:
cocktail(In, R),
writef('-> %w\n', [R]).
</syntaxhighlight>
{{out|Example}}
<pre>?- test.
Line 2,703 ⟶ 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.
<
Procedure cocktailSort(Array a(1))
Protected index, hasChanged, low, high
Line 2,733 ⟶ 3,476:
low + 1
Until hasChanged = #False ;if no elements have been changed, then the array is sorted
EndProcedure</
=={{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.
<
up = range(len(A)-1)
while True:
Line 2,747 ⟶ 3,490:
swapped = True
if not swapped:
return</
{{out|Usage}}
<
cocktailSort(test1)
print test1
Line 2,757 ⟶ 3,500:
cocktailSort(test2)
print ''.join(test2)
#>>> abcdefghiijklmnopqrstuvwxyz</
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.
<
for i in range(len(a)//2):
swap = False
Line 2,775 ⟶ 3,518:
swap = True
if not swap:
break</
=={{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.
<syntaxhighlight lang="rsplus">cocktailSort <- function(A)
{
repeat
swapped <- FALSE
for(i in
{
if(A[i] > A[i + 1])
{
swapped <- TRUE
}
}
if(!swapped)
{
if(A[i] > A[i + 1])
{
swapped <- TRUE
}
}
A
}
#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")</syntaxhighlight>
{{out}}
<pre>> cocktailSort(ints)
[1] -19 -1 0 1 2 4 5 5 10 23
> cocktailSort(numerics)
[1] -9.5 -5.7 -4.1 -3.2 0.0 1.0 3.5 5.2 7.3 10.8
> cocktailSort(strings)
[1] "all" "are" "be" "created" "equal" "hold" "men"
[8] "self-evident" "that" "these" "to" "truths" "We"</pre>
=={{header|Racket}}==
<
#lang racket
(require (only-in srfi/43 vector-swap!))
Line 2,832 ⟶ 3,618:
[(zero? (bubble (- len 2) 0 -1)) xs]
[(loop)])))
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku"
my $range = 0 ..^ @a.end;
loop {
Line 2,861 ⟶ 3,647:
my @weights = (^50).map: { 100 + ( 1000.rand.Int / 10 ) };
say @weights.sort.Str eq @weights.&cocktail_sort.Str ?? 'ok' !! 'not ok';</
=={{header|REXX}}==
===version handles blanks===
This REXX version can handle array elements that may contain blanks or spaces.
<
/* bidirectional bubble sort, */
/* cocktail shaker sort, ripple sort,*/
Line 2,872 ⟶ 3,658:
/* shuffle sort, shuttle sort, or */
/* a bubble sort variation. */
call
call
call cocktailSort
call
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
cocktailSort: procedure expose
nn = items.0 - 1
do until done
done = 1
do j = 1 for
jp = j + 1
if items.j > items.jp
temp =
items.j =
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.
items.= /*assign a default value for the stem. */
items.1 ='---the 22 card tarot deck (larger deck has 56 additional cards in 4 suits)---'
items.2 ='==========symbol====================pip======================================'
items.9
items.24='the fool [often unnumbered] ◄─── XXII'
items.0 =24 /* number of entries in the array. */
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
showitems: procedure expose items.
parse arg phase
width = length(items.0)
do j=1 to
say 'element' right(j, width) phase || ":" items.j
end /*j*/ /* ↑ */
/* └─────max width of any line number. */
return</syntaxhighlight>
{{out|output|text= when using the internal default inputs:}}
(Shown at three-quarter size.)
<pre style="font-size:75%">
element 1 before sort: ---the 22 card tarot deck (larger deck has 56 additional cards in 4 suits)---
Line 2,946 ⟶ 3,751:
element 16 before sort: temperance ◄─── XIV
element 17 before sort: the devil ◄─── XV
element 18 before sort:
element 19 before sort: the stars ◄─── XVII
element 20 before sort: the moon ◄─── XVIII
element 21 before sort: the sun ◄─── XIX
element 22 before sort: judgment ◄─── XX
element 23 before sort: the world ◄─── XXI
element 24 before sort: the fool [often unnumbered] ◄─── XXII
█████████████████████████████████████████████████████████████████████████████████████████████████████
element 1 after sort: ---the 22 card tarot deck (larger deck has 56 additional cards in 4 suits)---
Line 2,952 ⟶ 3,763:
element 3 after sort: death [often unlabeled] ◄─── XIII
element 4 after sort: fortune [the wheel of] ◄─── X
element 5 after sort:
element 6 after sort:
element 7 after sort:
element 8 after sort:
element 9 after sort:
element 10 after sort: the
element 11 after sort: the
element 12 after sort: the
element 13 after sort: the
element 14 after sort: the
element 15 after sort: the
element 16 after sort: the
element 17 after sort: the
element 18 after sort: the
element 19 after sort: the juggler ◄─── I
element 20 after sort: the lovers ◄─── VI
element 21 after sort: the moon ◄─── XVIII
element 22 after sort: the stars ◄─── XVII
element 23 after sort: the sun ◄─── XIX
element 24 after sort: the world ◄─── XXI
</pre>
===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.*/
do until done
done = 1
do j = 1 for
jp = j + 1
if items.j
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}}==
<
aList = [ 5, 6, 1, 2, 9, 14, 2, 15, 6, 7, 8, 97]
flag = 0
Line 3,005 ⟶ 3,833:
next
end
</syntaxhighlight>
=={{header|Ruby}}==
<
def cocktailsort!
begin
Line 3,030 ⟶ 3,858:
self
end
end</
Another way
<
def cocktailsort!
start, finish, way = 0, size-1, 1
Line 3,049 ⟶ 3,877:
self
end
end</
Test:
<
p ary.cocktailsort!
ary = ["John", "Kate", "Zerg", "Alice", "Joe", "Jane"]
p ary.cocktailsort!</
{{out}}
Line 3,064 ⟶ 3,892:
=={{header|Run BASIC}}==
<
a(i) = rnd(0) * 100
next i
Line 3,090 ⟶ 3,918:
print i;" ";a(i)
next i
end</
=={{header|Rust}}==
<
let len = a.len();
loop {
Line 3,127 ⟶ 3,955:
cocktail_sort(&mut v);
println!("after: {:?}", v);
}</
{{out}}
Line 3,136 ⟶ 3,964:
=={{header|Scala}}==
<
def sort(arr: Array[Int]) = {
var swapped = false
Line 3,161 ⟶ 3,989:
println(sort(Array(170, 45, 75, -90, -802, 24, 2, 66)).mkString(", "))
}</
=={{header|Scilab}}==
<syntaxhighlight lang="text">function varargout=cocktailSort(list_in)
swapped = %T;
while swapped
Line 3,188 ⟶ 4,016:
endfunction
disp(cocktailSort([6 3 7 8 5 1 2 4 9]));</
{{out}}
<pre> 1. 2. 3. 4. 5. 6. 7. 8. 9.</pre>
=={{header|Seed7}}==
<
local
var boolean: swapped is FALSE;
Line 3,221 ⟶ 4,049:
end if;
until not swapped;
end func;</
Original source: [http://seed7.sourceforge.net/algorith/sorting.htm#cocktailSort]
=={{header|Sidef}}==
<
var swapped = false
func cmpsw(i) {
Line 3,241 ⟶ 4,069:
} while (swapped)
return a
}</
Test:
<
say cocktailsort(numbers)
var strs = ["John", "Kate", "Zerg", "Alice", "Joe", "Jane"]
say cocktailsort(strs)</
{{out}}
<pre>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Line 3,253 ⟶ 4,081:
=={{header|Slate}}==
<
[ |swapped|
swapped: False.
Line 3,262 ⟶ 4,090:
swapped: False].
] loop
].</
{{out|Example}}
<
{-5. 0. 6. 7. 8. 9. 10}</
=={{header|Smalltalk}}==
{{works with|GNU Smalltalk}}
<
swap: indexA and: indexB [
|t|
Line 3,298 ⟶ 4,126:
^ self
]
].</
{{out|Example}}
<
=={{header|Swift}}==
<
public func cocktailSorted() -> [Element] {
var swapped = false
Line 3,338 ⟶ 4,166:
print("Before: \(arr)")
print("Cocktail sort: \(arr.cocktailSorted())")</
{{out}}
Line 3,347 ⟶ 4,175:
=={{header|Tcl}}==
{{tcllib|struct::list}}<!-- convenient element swapping only -->
<
package require struct::list
Line 3,375 ⟶ 4,203:
}
return $A
}</
{{out|Example}}
<
=={{header|uBasic/4tH}}==
<syntaxhighlight lang="text">PRINT "Cocktail sort:"
n = FUNC (_InitArray)
PROC _ShowArray (n)
Line 3,431 ⟶ 4,259:
PRINT
RETURN</
=={{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.
<
ctsort = ^=+ +^|(==?/~&l+ @r+ ~&x++ @x,^/~&)+ ("p". =><> ~&r?\~&C "p"?lrhPX/~&C ~&rhPlrtPCC)^~/not ~&</
test program:
<
test = ctsort(lleq) 'mdfdguldxisgbxjtqkadfkslakwkyioukdledbig'</
{{out}}
<pre>
Line 3,449 ⟶ 4,277:
=={{header|Vala}}==
{{trans|C}}
<
if (array[i1] == array[i2])
return;
Line 3,481 ⟶ 4,309:
stdout.printf("%d ", i);
}
}</
{{out}}
Line 3,489 ⟶ 4,317:
=={{header|VBA}}==
{{trans|Phix}}<
Dim swapped As Boolean
Dim f As Integer, t As Integer, d As Integer, tmp As Integer
Line 3,524 ⟶ 4,352:
Debug.Print Join(s, ", ")
Debug.Print Join(cocktail_sort(s), ", ")
End Sub</
<pre>45, 414, 862, 790, 373, 961, 871, 56, 949, 364
45, 56, 364, 373, 414, 790, 862, 871, 949, 961</pre>
Line 3,532 ⟶ 4,360:
;Implementation
<
dim swapped
dim i
Line 3,561 ⟶ 4,389:
a = b
b = tmp
end sub</
;Invocation
<
a = array( "portcullis", "redoubt", "palissade", "turret", "collins", "the parapet", "the quarterdeck")
wscript.echo join( a, ", ")
Line 3,569 ⟶ 4,397:
dim b
b = cocktailSort( a )
wscript.echo join( b, ", ")</
{{out}}
<pre>
Line 3,576 ⟶ 4,404:
</pre>
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">fn cocktail(
input := 'Input'
output := 'Output'
Line 3,615 ⟶ 4,443:
arr = [-8, 15, 1, 4, -3, 20]
cocktail(mut arr)
}</
{{out}}
<pre>Input : [6, 9, 1, 4]
Line 3,624 ⟶ 4,452:
=={{header|Wren}}==
{{trans|Go}}
<
var last = a.count - 1
while (true) {
Line 3,655 ⟶ 4,483:
System.print("Before: %(a)")
cocktailSort.call(a)
System.print("After : %(a)")</
{{out}}
Line 3,664 ⟶ 4,492:
=={{header|XPL0}}==
<
proc CocktailSort(A, L); \Sort array A of length L
Line 3,691 ⟶ 4,519:
CocktailSort(A, 10);
for I:= 0 to 10-1 do [IntOut(0, A(I)); ChOut(0, ^ )];
]</
{{out}}
Line 3,700 ⟶ 4,528:
=={{header|zkl}}==
This has the Wikipedia optimizations.
<
swapped,begin,end:=False,-1,a.len() - 2;
do{
Line 3,714 ⟶ 4,542:
}while(swapped);
a
}</
<
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();</
{{out}}
<pre>
Line 3,729 ⟶ 4,557:
=={{header|ZX Spectrum Basic}}==
its a "cocktail" bubble sort, but the writer called it 'zigzag' since the name was unknown
<
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 3,749 ⟶ 4,577:
5064 IF d AND i<la THEN GO TO 5020
5072 PRINT AT 12,0;a$
9000 STOP</
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 3,755 ⟶ 4,583:
its a " Sticky (edge) Cocktail Sort"
By C. Born (freeware)
<
5002 LET a$="": FOR f=1 TO 96: LET a$=a$+CHR$ (48+INT (RND*48)): NEXT f
5004 PRINT 'a$
Line 3,787 ⟶ 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</
{{omit from|GUISS}}
|