Sorting Algorithms/Circle Sort: Difference between revisions

m
(Added Julia language)
m (→‎{{header|Wren}}: Minor tidy)
(43 intermediate revisions by 24 users not shown)
Line 1:
{{draft task|Sorting Algorithms}}{{Sorting Algorithm}}
 
Sort an array of integers (of any convenient size) into ascending order using Circlesort.
Line 48:
* For more information on Circle sorting, see [http://sourceforge.net/p/forth-4th/wiki/Circle%20sort/ Sourceforge].
<br><br>
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F circle_sort_backend(&A, Int l, r)
V n = r - l
I n < 2
R 0
V swaps = 0
V m = n I/ 2
L(i) 0 .< m
I A[r - (i + 1)] < A[l + i]
swap(&A[r - (i + 1)], &A[l + i])
swaps++
I (n [&] 1) != 0 & (A[l + m] < A[l + m - 1])
swap(&A[l + m - 1], &A[l + m])
swaps++
R swaps + circle_sort_backend(&A, l, l + m) + circle_sort_backend(&A, l + m, r)
 
F circle_sort(&l)
V swaps = 0
V s = 1
L s != 0
s = circle_sort_backend(&l, 0, l.len)
swaps += s
R swaps
 
L(i) 309
V l = Array(0 .< i)
V m = copy(l)
random:shuffle(&l)
V n = copy(l)
circle_sort(&l)
I l != m
print(l.len)
print(n)
print(l)</syntaxhighlight>
 
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program circleSort64.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"
szMessSortBefore: .asciz "Display table before sort.\n"
sMessResult: .asciz "Value : @ \n"
szCarriageReturn: .asciz "\n"
.align 4
#TableNumber: .quad 1,3,6,2,5,9,10,8,4,7
#TableNumber: .quad 1,2,3,4,5,6,7,8,9,10
#TableNumber: .quad 9,5,12,8,2,12,6
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,qAdrszMessSortBefore
bl affichageMess
ldr x0,qAdrTableNumber // address number table
bl displayTable
1:
ldr x0,qAdrTableNumber // address number table
mov x1,#0
mov x2,#NBELEMENTS -1 // number of élements
mov x3,#0
bl circleSort
cmp x0,#0
bne 1b
ldr x0,qAdrTableNumber // address number table
mov x1,#NBELEMENTS // number of élements
bl displayTable
ldr x0,qAdrTableNumber // address number table
mov x1,#NBELEMENTS // number of élements
bl isSorted // control sort
cmp x0,#1 // sorted ?
beq 2f
ldr x0,qAdrszMessSortNok // no !! error sort
bl affichageMess
b 100f
2: // 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
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsMessResult: .quad sMessResult
qAdrTableNumber: .quad TableNumber
qAdrszMessSortOk: .quad szMessSortOk
qAdrszMessSortNok: .quad szMessSortNok
qAdrszMessSortBefore: .quad szMessSortBefore
/******************************************************************/
/* 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 // smaller -> error
mov x4,x3 // A[i-1] = A[i]
b 1b // else loop
98:
mov x0,#0 // error
b 100f
99:
mov x0,#1 // ok -> return
100:
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* circle sort */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains the first index */
/* x2 contains the last index */
/* x3 contains number of swaps */
circleSort:
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
stp x10,x11,[sp,-16]! // save registers
cmp x1,x2
beq 99f
mov x7,x0 // save address
mov x8,x1 // low
mov x9,x2 // high
sub x4,x2,x1
lsr x4,x4,#1
mov x10,x4 // mid
1: // start loop
cmp x1,x2
bge 3f
ldr x5,[x0,x1,lsl #3]
ldr x6,[x0,x2,lsl #3]
cmp x5,x6
ble 2f
str x6,[x0,x1,lsl #3] // swap values
str x5,[x0,x2,lsl #3]
add x3,x3,#1
2:
add x1,x1,#1 // increment lo
sub x2,x2,#1 // decrement hi
b 1b // and loop
3:
cmp x1,x2 // compare lo hi
bne 4f // not egal
ldr x5,[x0,x1,lsl #3]
add x2,x2,#1
ldr x6,[x0,x2,lsl #3]
cmp x5,x6
ble 4f
str x6,[x0,x1,lsl #3] // swap
str x5,[x0,x2,lsl #3]
add x3,x3,#1
4:
mov x1,x8 // low
mov x2,x10 // mid
add x2,x2,x1
bl circleSort
mov x3,x0 // swaps
mov x0,x7 // table address
mov x1,x8 // low
mov x2,x10 // mid
add x1,x2,x1
add x1,x1,#1
mov x2,x9 // high
bl circleSort
mov x3,x0 // swaps
99:
mov x0,x3 // return number swaps
100:
ldp x10,x11,[sp],16 // restaur 2 registers
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 conversion10 // décimal conversion
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConv // insert conversion
bl strInsertAtCharInc
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
qAdrsZoneConv: .quad sZoneConv
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
<pre>
Display table before sort.
Value : 10
Value : 9
Value : 8
Value : 7
Value : 6
Value : 5
Value : 4
Value : 3
Value : 2
Value : 1
 
Value : 1
Value : 2
Value : 3
Value : 4
Value : 5
Value : 6
Value : 7
Value : 8
Value : 9
Value : 10
 
Table sorted.
</pre>
 
=={{header|Action!}}==
Action! language does not support recursion. Therefore an iterative approach with a stack has been proposed.
<syntaxhighlight lang="action!">DEFINE MAX_COUNT="100"
INT ARRAY stack(MAX_COUNT)
INT stackSize
 
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 InitStack()
stackSize=0
RETURN
 
BYTE FUNC IsEmpty()
IF stackSize=0 THEN
RETURN (1)
FI
RETURN (0)
 
PROC Push(INT low,high)
stack(stackSize)=low stackSize==+1
stack(stackSize)=high stackSize==+1
RETURN
 
PROC Pop(INT POINTER low,high)
stackSize==-1 high^=stack(stackSize)
stackSize==-1 low^=stack(stackSize)
RETURN
 
INT FUNC Partition(INT ARRAY a INT low,high)
INT part,v,i,tmp
 
v=a(high)
part=low-1
 
FOR i=low TO high-1
DO
IF a(i)<=v THEN
part==+1
tmp=a(part) a(part)=a(i) a(i)=tmp
FI
OD
 
part==+1
tmp=a(part) a(part)=a(high) a(high)=tmp
RETURN (part)
 
PROC CircleSort(INT ARRAY a INT size)
INT swaps,low,high,lo,hi,tmp,mid
 
InitStack()
DO
swaps=0
Push(0,size-1)
WHILE IsEmpty()=0
DO
Pop(@low,@high)
IF low<high THEN
lo=low hi=high
WHILE lo<hi
DO
IF a(hi)<a(lo) THEN
tmp=a(lo) a(lo)=a(hi) a(hi)=tmp
swaps==+1
FI
lo==+1 hi==-1
OD
IF lo=hi AND a(lo+1)<a(lo) THEN
tmp=a(lo) a(lo)=a(lo+1) a(lo+1)=tmp
swaps==+1
FI
mid=(lo+hi)/2
Push(low,mid)
Push(mid+1,high)
FI
OD
UNTIL swaps=0
OD
RETURN
 
PROC Test(INT ARRAY a INT size)
PrintE("Array before sort:")
PrintArray(a,size)
CircleSort(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/Circle_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|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program circleSort.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"
szMessSortBefore: .asciz "Display table before sort.\n"
sMessResult: .asciz "Value : @ \n"
szCarriageReturn: .asciz "\n"
.align 4
#TableNumber: .int 1,3,6,2,5,9,10,8,4,7
#TableNumber: .int 1,2,3,4,5,6,7,8,9,10
TableNumber: .int 9,5,12,8,2,12,6
#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
ldr r0,iAdrszMessSortBefore
bl affichageMess
ldr r0,iAdrTableNumber @ address number table
bl displayTable
1:
ldr r0,iAdrTableNumber @ address number table
mov r1,#0
mov r2,#NBELEMENTS -1 @ number of élements
mov r3,#0
bl circleSort
cmp r0,#0
bne 1b
ldr r0,iAdrTableNumber @ address number table
mov r1,#NBELEMENTS @ number of élements
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
iAdrszMessSortBefore: .int szMessSortBefore
/******************************************************************/
/* 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
/******************************************************************/
/* circle sort */
/******************************************************************/
/* r0 contains the address of table */
/* r1 contains the first index */
/* r2 contains the last index */
/* r3 contains number of swaps */
circleSort:
push {r1-r10,lr} @ save registers
cmp r1,r2
beq 99f
mov r7,r0 @ save address
mov r8,r1 @ low
mov r9,r2 @ high
sub r4,r2,r1
lsr r4,#1
mov r10,r4 @ mid
1: @ start loop
cmp r1,r2
bge 3f
ldr r5,[r0,r1,lsl #2]
ldr r6,[r0,r2,lsl #2]
cmp r5,r6
ble 2f
str r6,[r0,r1,lsl #2] @ swap values
str r5,[r0,r2,lsl #2]
add r3,r3,#1
2:
add r1,r1,#1 @ increment lo
sub r2,r2,#1 @ decrement hi
b 1b @ and loop
3:
cmp r1,r2 @ compare lo hi
bne 4f @ not egal
ldr r5,[r0,r1,lsl #2]
add r2,r2,#1
ldr r6,[r0,r2,lsl #2]
cmp r5,r6
ble 4f
str r6,[r0,r1,lsl #2] @ swap
str r5,[r0,r2,lsl #2]
add r3,r3,#1
4:
mov r1,r8 @ low
mov r2,r10 @ mid
add r2,r2,r1
bl circleSort
mov r3,r0 @ swaps
mov r0,r7 @ table address
mov r1,r8 @ low
mov r2,r10 @ mid
add r1,r2,r1
add r1,r1,#1
mov r2,r9 @ high
bl circleSort
mov r3,r0 @ swaps
99:
mov r0,r3 @ return number swaps
100:
pop {r1-r10,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 conversion10 @ décimal conversion
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>
<pre>
Display table before sort.
Value : 9
Value : 5
Value : 12
Value : 8
Value : 2
Value : 12
Value : 6
 
Value : 2
Value : 5
Value : 6
Value : 8
Value : 9
Value : 12
Value : 12
 
Table sorted.
</pre>
 
=={{header|Arturo}}==
<syntaxhighlight lang="arturo">innerCircleSort: function [ar, lo, hi, swaps][
localSwaps: swaps
localHi: hi
localLo: lo
if localLo = localHi -> return swaps
 
high: localHi
low: localLo
mid: (localHi - localLo) / 2
 
while [localLo < localHi] [
if ar\[localLo] > ar\[localHi] [
tmp: ar\[localLo]
ar\[localLo]: ar\[localHi]
ar\[localHi]: tmp
localSwaps: localSwaps + 1
]
localLo: localLo + 1
localHi: localHi - 1
]
if localLo = localHi [
if ar\[localLo] > ar\[localHi + 1] [
tmp: ar\[localLo]
ar\[localLo]: ar\[localHi + 1]
ar\[localHi + 1]: tmp
localSwaps: localSwaps + 1
]
]
 
localSwaps: innerCircleSort ar low low + mid localSwaps
localSwaps: innerCircleSort ar low + mid + 1 high localSwaps
return localSwaps
]
 
circleSort: function [arr][
result: new arr
while [not? zero? innerCircleSort result 0 dec size result 0][]
return result
]
 
print circleSort [3 1 2 8 5 7 9 4 6]</syntaxhighlight>
 
{{out}}
 
<pre>1 2 3 4 5 6 7 8 9</pre>
 
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">nums := [6, 7, 8, 9, 2, 5, 3, 4, 1]
while circlesort(nums, 1, nums.Count(), 0) ; 1-based
continue
for i, v in nums
output .= v ", "
MsgBox % "[" Trim(output, ", ") "]"
return
circlesort(Arr, lo, hi, swaps){
if (lo = hi)
return swaps
high:= hi
low := lo
mid := Floor((hi - lo) / 2)
while (lo < hi) {
if (Arr[lo] > Arr[hi]){
tempVal := Arr[lo], Arr[lo] := Arr[hi], Arr[hi] := tempVal
swaps++
}
lo++
hi--
}
if (lo = hi)
if (Arr[lo] > Arr[hi+1]){
tempVal := Arr[lo], Arr[lo] := Arr[hi+1], Arr[hi+1] := tempVal
swaps++
}
swaps := circlesort(Arr, low, low+mid, swaps)
swaps := circlesort(Arr, low+mid+1, high, swaps)
return swaps
}</syntaxhighlight>
{{out}}
<pre>[1, 2, 3, 4, 5, 6, 7, 8, 9]</pre>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
 
int circle_sort_inner(int *start, int *end)
Line 83 ⟶ 794:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 90 ⟶ 801:
-4 -1 0 1 2 3 5 6 8 101
</pre>
 
=={{header|C#}}==
<syntaxhighlight lang="c#">using System;
using System.Linq;
 
namespace CircleSort
{
internal class Program
{
public static int[] CircleSort(int[] array)
{
if (array.Length > 0)
while (CircleSortR(array, 0, array.Length - 1, 0) != 0)
continue;
return array;
}
 
private static int CircleSortR(int[] arr, int lo, int hi, int numSwaps)
{
if (lo == hi)
return numSwaps;
 
var high = hi;
var low = lo;
var mid = (hi - lo) / 2;
 
while (lo < hi)
{
if (arr[lo] > arr[hi])
{
(arr[lo], arr[hi]) = (arr[hi], arr[lo]);
numSwaps++;
}
lo++;
hi--;
}
 
if (lo == hi && arr[lo] > arr[hi + 1])
{
(arr[lo], arr[hi + 1]) = (arr[hi + 1], arr[lo]);
numSwaps++;
}
 
numSwaps = CircleSortR(arr, low, low + mid, numSwaps);
numSwaps = CircleSortR(arr, low + mid + 1, high, numSwaps);
 
return numSwaps;
}
 
private static void Main(string[] args)
{
var sortedArray = CircleSort(new int[] { 6, 7, 8, 9, 2, 5, 3, 4, 1 });
sortedArray.ToList().ForEach(i => Console.Write(i.ToString() + " "));
Console.WriteLine();
var sortedArray2 = CircleSort(new int[] { 2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1 });
sortedArray2.ToList().ForEach(i => Console.Write(i.ToString() + " "));
Console.WriteLine();
var sortedArray3 = CircleSort(new int[] { 2, 3, 3, 5, 5, 1, 1, 7, 7, 6, 6, 4, 4, 0, 0 });
sortedArray3.ToList().ForEach(i => Console.Write(i.ToString() + " "));
Console.ReadKey();
}
}
}</syntaxhighlight>
{{out}}
<pre>
1 2 3 4 5 6 7 8 9
-1 0 1 2 3 4 5 6 7 8 11 12 13 14
0 0 1 1 2 3 3 4 4 5 5 6 6 7 7
</pre>
 
=={{header|C++}}==
<syntaxhighlight lang="cpp">#include <iostream>
 
int circlesort(int* arr, int lo, int hi, int swaps) {
if(lo == hi) {
return swaps;
}
int high = hi;
int low = lo;
int mid = (high - low) / 2;
while(lo < hi) {
if(arr[lo] > arr[hi]) {
int temp = arr[lo];
arr[lo] = arr[hi];
arr[hi] = temp;
swaps++;
}
lo++;
hi--;
}
 
if(lo == hi) {
if(arr[lo] > arr[hi+1]) {
int temp = arr[lo];
arr[lo] = arr[hi+1];
arr[hi+1] = temp;
swaps++;
}
}
swaps = circlesort(arr, low, low+mid, swaps);
swaps = circlesort(arr, low+mid+1, high, swaps);
return swaps;
}
 
void circlesortDriver(int* arr, int n) {
do {
for(int i = 0; i < n; i++) {
std::cout << arr[i] << ' ';
}
std::cout << std::endl;
} while(circlesort(arr, 0, n-1, 0));
}
 
int main() {
int arr[] = { 6, 7, 8, 9, 2, 5, 3, 4, 1 };
circlesortDriver(arr, sizeof(arr)/sizeof(int));
return 0;
}</syntaxhighlight>
Output:
<pre>6 7 8 9 2 5 3 4 1
1 3 4 2 5 6 7 8 9
1 2 3 4 5 6 7 8 9</pre>
 
=={{header|CoffeeScript}}==
<syntaxhighlight lang="text">circlesort = (arr, lo, hi, swaps) ->
if lo == hi
return (swaps)
Line 124 ⟶ 957:
 
while circlesort(VA,0,VA.length-1,0)
console.log VA</langsyntaxhighlight>
Output:
<pre>console: -1,1,0,3,4,5,8,12,2,9,6,10,7,13,11,14
Line 131 ⟶ 964:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.array, std.traits;
 
void circlesort(T)(T[] items) if (isMutable!T) {
Line 180 ⟶ 1,013:
assert(data.isSorted);
}
}</langsyntaxhighlight>
{{out}}
<pre>[-4, -1, 0, 1, 2, 3, 5, 6, 8, 101]</pre>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{Trans|Go}}
<syntaxhighlight lang="delphi">
program Sorting_Algorithms;
 
{$APPTYPE CONSOLE}
 
uses
System.SysUtils;
 
function CircleSort(a: TArray<Integer>; lo, hi, swaps: Integer): Integer;
begin
if lo = hi then
exit(swaps);
 
var high := hi;
var low := lo;
var mid := (hi - lo) div 2;
 
while lo < hi do
begin
if a[lo] > a[hi] then
begin
var tmp := a[lo];
a[lo] := a[hi];
a[hi] := tmp;
inc(swaps);
end;
inc(lo);
dec(hi);
end;
 
if lo = hi then
begin
if a[lo] > a[hi + 1] then
begin
var tmp := a[lo];
a[lo] := a[hi + 1];
a[hi + 1] := tmp;
inc(swaps);
end;
end;
swaps := CircleSort(a, low, low + mid, swaps);
swaps := CircleSort(a, low + mid + 1, high, swaps);
result := swaps;
end;
 
function ToString(a: TArray<Integer>): string;
begin
Result := '[';
for var e in a do
Result := Result + e.ToString + ',';
Result := Result + ']';
end;
 
const
aa: TArray<TArray<Integer>> = [[6, 7, 8, 9, 2, 5, 3, 4, 1], [2, 14, 4, 6, 8, 1,
3, 5, 7, 11, 0, 13, 12, -1]];
 
begin
for var a in aa do
begin
write('Original: ');
write(ToString(a));
while CircleSort(a, 0, high(a), 0) <> 0 do
;
writeln;
write('Sorted : ');
write(ToString(a));
writeln(#10#10);
end;
readln;
end.</syntaxhighlight>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Sort do
def circle_sort(data) do
List.to_tuple(data)
Line 227 ⟶ 1,134:
data = [6, 7, 8, 9, 2, 5, 3, 4, 1]
IO.puts "before sort: #{inspect data}"
IO.puts " after sort: #{inspect Sort.circle_sort(data)}"</langsyntaxhighlight>
 
{{out}}
Line 237 ⟶ 1,144:
=={{header|Forth}}==
This one features the newest version of the algorithm on [http://sourceforge.net/p/forth-4th/wiki/Circle%20sort/ Sourceforge].
<syntaxhighlight lang="text">[UNDEFINED] cell- [IF] : cell- 1 cells - ; [THEN]
 
defer precedes ( addr addr -- flag )
Line 269 ⟶ 1,176:
: .sample sample /sample cells bounds do i ? 1 cells +loop ;
sample /sample sort .sample</langsyntaxhighlight>
 
=={{header|Fortran}}==
<langsyntaxhighlight lang="fortran">
! circle sort compilation and run on linux
!
module circlesort
! -*- mode: compilation; default-directory: "/tmp/" -*-
! I have commented the code that was here and also 'tightened up' various pieces such as how swap detection was done as well
! Compilation started at Thu Mar 9 00:39:39
! as fixing an error where the code would exceed array bounds for odd number sized arrays.
! Also, giving some some attribution to the author. - Pete
! This code is a Fortran adaptation of a Forth algorithm laid out by "thebeez" at this URL;
! https://sourceforge.net/p/forth-4th/wiki/Circle%20sort/
!
! a=./circle_sort && make $a && $a
! gfortran -std=f2008 -Wall -g -fPIC -fopenmp -ffree-form -fall-intrinsics -fimplicit-none circle_sort.f08 -o circle_sort
! 1 2 3 4 5 6 7 8 9
!
! Compilation finished at Thu Mar 9 00:39:39
 
module circlesort
 
implicit none
logical, private :: csr
public :: circle_sort
 
contains
 
recursive subroutinelogical function csr(a, left, right, n,) swapsresult(swapped)
implicit none
integer, intent(in) :: n, left, right,n
integer, intent(inout) :: a(n), swaps
integer :: lo, hi, mid
integer :: temp
logical :: lefthalf,righthalf
!
swapped = .FALSE.
if (right <= left) return
lo = left !Store the upper and lower bounds of list for
hi = right !Recursion later
!
mid = (lo + hi) / 2
do while (lo < hi)
! Swap the pair of elements if hi < lo
if (a(hi) < a(lo)) then
swapsswapped = swaps + 1.TRUE.
temp = a(lo)
a(lo) = a(hi)
a(hi) = temp
end ifendif
lo = lo + 1
hi = hi - 1
end do
! Special case if ((loarray ==is hi)an .and.odd size (a(lo+1)not .lt. a(loeven))) then
if swaps(lo == swaps + 1hi)then
tempif(a(hi+1) =.lt. a(lo+1))then
a(lo+1) swapped = a(lo).TRUE.
a(lo) = temp = a(hi+1)
hi = lo - a(hi+1) = a(lo)
a(lo) = temp
endif
endif
callmid csr(a,= (left, mid,+ n, swapsright) / 2 ! Bisection point
calllefthalf = csr(a, mid + 1left, rightmid, n, swaps)
righthalf = csr(a, mid + 1, right,n)
end subroutine csr
swapped = swapped .or. lefthalf .or. righthalf
 
end function csr
!
subroutine circle_sort(a, n)
use iso_c_binding, only: c_ptr, c_loc
implicit none
integer, intent(in) :: n
integer, target,intent(inout) :: a(n)
 
integer :: swaps
swapsdo =while ( csr(a, 1, n,n))
! This is the canonical algorithm. However, if you want to
do while (0 < swaps)
! speed it up, count the iterations and when you have approached
swaps = 0
! 0.5*ln(n) iterations, perform a binary insertion sort then exit the loop.
call csr(a, 1, size(a), size(a), swaps)
end do
end subroutine circle_sort
 
end module circlesort
 
program sort
use circlesort
Line 345 ⟶ 1,256:
end program sort
 
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' version 21-10-2016
' compile with: fbc -s console
' for boundry checks on array's compile with: fbc -s console -exx
Line 412 ⟶ 1,323:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>unsorted -4 -1 1 0 5 -7 -2 4 -6 -3 2 6 3 7 -5
sorted -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7</pre>
 
=={{header|Go}}==
<syntaxhighlight lang="go">package main
 
import "fmt"
 
func circleSort(a []int, lo, hi, swaps int) int {
if lo == hi {
return swaps
}
high, low := hi, lo
mid := (hi - lo) / 2
for lo < hi {
if a[lo] > a[hi] {
a[lo], a[hi] = a[hi], a[lo]
swaps++
}
lo++
hi--
}
if lo == hi {
if a[lo] > a[hi+1] {
a[lo], a[hi+1] = a[hi+1], a[lo]
swaps++
}
}
swaps = circleSort(a, low, low+mid, swaps)
swaps = circleSort(a, low+mid+1, high, swaps)
return swaps
}
 
func main() {
aa := [][]int{
{6, 7, 8, 9, 2, 5, 3, 4, 1},
{2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1},
}
for _, a := range aa {
fmt.Printf("Original: %v\n", a)
for circleSort(a, 0, len(a)-1, 0) != 0 {
// empty block
}
fmt.Printf("Sorted : %v\n\n", a)
}
}</syntaxhighlight>
 
{{out}}
<pre>
Original: [6 7 8 9 2 5 3 4 1]
Sorted : [1 2 3 4 5 6 7 8 9]
 
Original: [2 14 4 6 8 1 3 5 7 11 0 13 12 -1]
Sorted : [-1 0 1 2 3 4 5 6 7 8 11 12 13 14]
</pre>
 
=={{header|Haskell}}==
 
This code uses the tortoise-and-the-hare technique to split the input list in two and compare the relevant positions.
 
<syntaxhighlight lang="haskell">import Data.Bool (bool)
 
circleSort :: Ord a => [a] -> [a]
circleSort xs = if swapped then circleSort ks else ks
where
(swapped,ks) = go False xs (False,[])
go d [] sks = sks
go d [x] (s,ks) = (s,x:ks)
go d xs (s,ks) =
let (st,_,ls,rs) = halve d s xs xs
in go False ls (go True rs (st,ks))
halve d s (y:ys) (_:_:zs) = swap d y (halve d s ys zs)
halve d s ys [] = (s,ys,[],[])
halve d s (y:ys) [_] = (s,ys,[y | e],[y | not e])
where e = y <= head ys
swap d x (s,y:ys,ls,rs)
| bool (<=) (<) d x y = ( d || s,ys,x:ls,y:rs)
| otherwise = (not d || s,ys,y:ls,x:rs)</syntaxhighlight>
 
{{out}}
<pre>
>>> circleSort [6,7,8,9,2,5,3,4,1]
[1,2,3,4,5,6,7,8,9]
 
>>> circleSort [2,14,4,6,8,1,3,5,7,11,0,13,12,-1]
[-1,0,1,2,3,4,5,6,7,8,11,12,13,14]
</pre>
 
=={{header|J}}==
Of more parsing and atomic data, or less parsing with large data groups the latter produces faster J programs. Consequently each iteration laminates the original with its reverse. It joins the recursive call to the pairwise minima of the left block to the recursive call of the pairwise maxima of the right block, repeating the operations while the output changes. This is sufficient for power of 2 length data. The pre verb adjusts the data length. And post recovers the original data. This implementation discards the "in place" property described at the sourceforge link.
 
<syntaxhighlight lang="j">
<lang J>
circle_sort =: post power_of_2_length@pre NB. the main sorting verb
power_of_2_length =: even_length_iteration^:_ NB. repeat while the answer changes
Line 426 ⟶ 1,425:
pre =: , (-~ >.&.(2&^.))@# # >./ NB. extend data to next power of 2 length
post =: ({.~ #)~ NB. remove the extra data
</syntaxhighlight>
</lang>
Examples:
<syntaxhighlight lang="j">
<lang J>
show =: [ smoutput
 
Line 446 ⟶ 1,445:
│0 0 1 1 2 3 3 4 4 5 5 6 6 7 7│0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 10 11 11 12│
└─────────────────────────────┴──────────────────────────────────────────────────────┘
</syntaxhighlight>
</lang>
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">import java.util.Arrays;
 
public class CircleSort {
Line 497 ⟶ 1,496:
arr[idx2] = tmp;
}
}</langsyntaxhighlight>
 
<pre>[2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1]
Line 507 ⟶ 1,506:
{{works with|jq|1.4}}
 
With kudos to [[#Perl 6Raku]].
 
"circlesort" as defined in this section can be used to sort any JSON array. In case your jq does not have "until" as a builtin, here is its definition:
<langsyntaxhighlight lang="jq">def until(cond; next):
def _until: if cond then . else (next|_until) end;
_until;</langsyntaxhighlight>
<langsyntaxhighlight lang="jq">def circlesort:
 
def swap(i;j): .[i] as $t | .[i] = .[j] | .[j] = $t;
Line 546 ⟶ 1,545:
| if $swaps == 0 then .
else circlesort
end ;</langsyntaxhighlight>
'''Example:'''
<langsyntaxhighlight lang="jq">"The quick brown fox jumps over the lazy dog" | split(" ") | circlesort</langsyntaxhighlight>
 
{{out}}
<langsyntaxhighlight lang="sh">$ jq -n -c -f -M circleSort.jq
["The","brown","dog","fox","jumps","lazy","over","quick","the"]</langsyntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">function _ciclesort!(arr::Vector, lo::Int, hi::Int, swaps::Int)
lo == hi && return swaps
high = hi
Line 587 ⟶ 1,586:
 
v = rand(10)
println("# $v\n -> ", ciclesort!(v))</langsyntaxhighlight>
 
{{out}}
Line 594 ⟶ 1,593:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.0
 
fun<T: Comparable<T>> circleSort(array: Array<T>, lo: Int, hi: Int, nSwaps: Int): Int {
Line 637 ⟶ 1,636:
while (circleSort(array2, 0, array2.size - 1, 0) != 0) ;
println("Sorted : ${array2.asList()}")
}</langsyntaxhighlight>
 
{{out}}
Line 650 ⟶ 1,649:
=={{header|Lua}}==
The first argument to the 'inner' function needs to be a reference to the table as Lua cannot use a pointer to the first element's memory address. Conversely the 'outer' function only needs one argument as the size of the table is innately knowable.
<langsyntaxhighlight Lualang="lua">-- Perform one iteration of a circle sort
function innerCircle (t, lo, hi, swaps)
if lo == hi then return swaps end
Line 681 ⟶ 1,680:
local array = {6, 7, 8, 9, 2, 5, 3, 4, 1}
circleSort(array)
print(table.concat(array, " "))</langsyntaxhighlight>
{{out}}
<pre>1 2 3 4 5 6 7 8 9</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">ClearAll[CircleSort, NestedCircleSort]
CircleSort[d_List, l_, h_] :=
Module[{high, low, mid, lo = l, hi = h, data = d},
If[lo == hi, Return[data]];
high = hi;
low = lo;
mid = Floor[(hi - lo)/2];
While[lo < hi,
If[data[[lo]] > data[[hi]],
data[[{lo, hi}]] //= Reverse;
];
lo++;
hi--
];
If[lo == hi,
If[data[[lo]] > data[[hi + 1]],
data[[{lo, hi + 1}]] //= Reverse;
]
];
data = CircleSort[data, low, low + mid];
data = CircleSort[data, low + mid + 1, high];
data
]
NestedCircleSort[{}] := {}
NestedCircleSort[d_List] := FixedPoint[CircleSort[#, 1, Length[#]] &, d]
NestedCircleSort[Echo@{6, 7, 8, 9, 2, 5, 3, 4, 1}]
NestedCircleSort[Echo@{6, 7, 8, 2, 5, 3, 4, 1}]
NestedCircleSort[Echo@{6, 2, 5, 7, 3, 4, 1}]
NestedCircleSort[Echo@{4, 6, 3, 5, 2, 1}]
NestedCircleSort[Echo@{1, 2, 3, 4, 5}]
NestedCircleSort[Echo@{2, 4, 3, 1}]
NestedCircleSort[Echo@{2, 3, 1}]
NestedCircleSort[Echo@{2, 1}]
NestedCircleSort[Echo@{1}]
NestedCircleSort[Echo@{}]</syntaxhighlight>
{{out}}
<pre>>>{6,7,8,9,2,5,3,4,1}
{1,2,3,4,5,6,7,8,9}
>>{6,7,8,2,5,3,4,1}
{1,2,3,4,5,6,7,8}
>>{6,2,5,7,3,4,1}
{1,2,3,4,5,6,7}
>>{4,6,3,5,2,1}
{1,2,3,4,5,6}
>>{1,2,3,4,5}
{1,2,3,4,5}
>>{2,4,3,1}
{1,2,3,4}
>>{2,3,1}
{1,2,3}
>>{2,1}
{1,2}
>>{1}
{1}
>>{}
{}</pre>
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">proc innerCircleSort[T](a: var openArray[T], lo, hi, swaps: int): int =
var localSwaps: int = swaps
var localHi: int = hi
var localLo: int = lo
if localLo == localHi:
return swaps
var `high` = localHi
var `low` = localLo
var mid = (localHi - localLo) div 2
 
while localLo < localHi:
if a[localLo] > a[localHi]:
swap a[localLo], a[localHi]
inc localSwaps
inc localLo
dec localHi
if localLo == localHi:
if a[localLo] > a[localHi + 1]:
swap a[localLo], a[localHi + 1]
inc localSwaps
 
localswaps = a.innerCircleSort(`low`, `low` + mid, localSwaps)
localSwaps = a.innerCircleSort(`low` + mid + 1, `high`, localSwaps)
result = localSwaps
 
proc circleSort[T](a: var openArray[T]) =
while a.innerCircleSort(0, a.high, 0) != 0:
discard
 
var arr = @[@[6, 7, 8, 9, 2, 5, 3, 4, 1],
@[2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1]]
 
for i in 0..arr.high:
echo "Original: ", $arr[i]
arr[i].circleSort()
echo "Sorted: ", $arr[i], if i != arr.high: "\n" else: ""</syntaxhighlight>
 
{{out}}
<pre>Original: @[6, 7, 8, 9, 2, 5, 3, 4, 1]
Sorted: @[1, 2, 3, 4, 5, 6, 7, 8, 9]
 
Original: @[2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1]
Sorted: @[-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14]</pre>
 
=={{header|Objeck}}==
{{trans|Objeck}}
<syntaxhighlight lang="objeck">class CircleSort {
function : Main(args : String[]) ~ Nil {
circleSort([2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1]);
}
function : circleSort(arr : Int[]) ~ Nil {
if(arr->Size() > 0) {
do {
arr->ToString()->PrintLine();
}
while(CircleSort(arr, 0, arr->Size() - 1, 0) <> 0);
};
}
function : CircleSort( arr : Int[], lo : Int, hi : Int, num_swaps : Int) ~ Int {
if(lo = hi) {
return num_swaps;
};
 
 
high := hi;
low := lo;
mid := (hi - lo) / 2;
while (lo < hi) {
if(arr[lo] > arr[hi]) {
Swap(arr, lo, hi);
num_swaps++;
};
lo++;
hi--;
};
if(lo = hi & arr[lo] > arr[hi + 1]) {
Swap(arr, lo, hi + 1);
num_swaps++;
};
num_swaps := CircleSort(arr, low, low + mid, num_swaps);
num_swaps := CircleSort(arr, low + mid + 1, high, num_swaps);
return num_swaps;
}
function : Swap(arr : Int[], idx1 : Int, idx2 : Int) ~ Nil {
tmp := arr[idx1];
arr[idx1] := arr[idx2];
arr[idx2] := tmp;
}
}
</syntaxhighlight>
 
Output:
<pre>
[2,14,4,6,8,1,3,5,7,11,0,13,12,-1]
[-1,1,0,4,3,8,12,2,7,6,11,5,13,14]
[-1,0,1,3,2,4,7,5,6,8,12,11,13,14]
[-1,0,1,2,3,4,5,6,7,8,11,12,13,14]
</pre>
 
=={{header|PARI/GP}}==
This follows the pseudocode pretty closely.
<langsyntaxhighlight lang="parigp">circlesort(v)=
{
local(v=v); \\ share with cs
Line 712 ⟶ 1,877:
}
print(example=[6,7,8,9,2,5,3,4,1]);
print(circlesort(example));</langsyntaxhighlight>
{{out}}
<pre>[6, 7, 8, 9, 2, 5, 3, 4, 1]
Line 718 ⟶ 1,883:
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">
{
source file name on linux is ./p.p
Line 796 ⟶ 1,961:
writeln();
end.
</syntaxhighlight>
</lang>
 
=={{header|Perl 6}}==
Less flexible than the Raku version, as written does only numeric comparisons.
{{trans|Raku}}
<syntaxhighlight lang="perl">sub circlesort {
our @x; local *x = shift;
my($beg,$end) = @_;
 
The given algorithm can be simplified in several ways. There's no need to compute the midpoint, since the hi/lo will end up there. The extra swap conditional can be eliminated by incrementing hi at the correct moment inside the loop. There's no need to
pass accumulated swaps down the call stack.
 
This does generic comparisons, so it works on any ordered type, including numbers or strings.
<lang perl6>sub circlesort (@x, $beg, $end) {
my $swaps = 0;
if ($beg < $end) {
my ($lo, $hi) = $beg, $end;
repeatmy {$hi = $end;
while if @x[($lo] after< @x[$hi]) {
if @($x[$lo,] > $x[$hi]) { # 'gt' here for .=string reverse;comparison
@x[$lo,$hi] = @x[$hi,$lo];
++$swaps;
}
++$hi if --$hi == ++$lo
} while $lo < $hi;
$swaps += circlesort(\@x, $beg, $hi);
$swaps += circlesort(\@x, $lo, $end);
}
$swaps;
}
 
my @a = <16 35 -64 -29 46 36 -1 -99 20 100 59 26 76 -78 39 85 -7 -81 25 88>;
say my @x = (-100..100).roll(20);
say @x while (circlesort(\@xa, 0, $#a)) { print join(' ', @x.enda);, "\n" }</syntaxhighlight>
 
say @x = <The quick brown fox jumps over the lazy dog.>;
say @x while circlesort(@x, 0, @x.end);</lang>
{{out}}
<pre>16 35 -6499 -2978 4616 20 36 -181 -9929 2046 10025 59 26 76-64 -787 39 8526 -788 -811 2535 8885 76 100
-99 -78 16 20 36 -81 -29 46 25 59 -64 -7 39 26 88 -1 35 85 76 100
-99 -78 -29 -81 16 -64 -7 20 -1 39 25 26 36 46 59 35 76 88 85 100
-99 -81 -78 -64 -29 -7 -1 16 20 25 26 35 36 39 46 59 76 85 88 100
-99 -81 -78 -64 -29 -7 -1 16 20 25 26 35 36 39 46 59 76 85 88 100</pre>
The quick brown fox jumps over the lazy dog.
 
The brown fox jumps lazy dog. quick over the
=={{header|Phix}}==
The brown dog. fox jumps lazy over quick the</pre>
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">array</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">circle_sort_inner</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">lo</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">hi</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">swaps</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">level</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;">lo</span><span style="color: #0000FF;">!=</span><span style="color: #000000;">hi</span> <span style="color: #008080;">then</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">high</span> <span style="color: #0000FF;">:=</span> <span style="color: #000000;">hi</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">low</span> <span style="color: #0000FF;">:=</span> <span style="color: #000000;">lo</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">mid</span> <span style="color: #0000FF;">:=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">((</span><span style="color: #000000;">high</span><span style="color: #0000FF;">-</span><span style="color: #000000;">low</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">lo</span> <span style="color: #0000FF;"><=</span> <span style="color: #000000;">hi</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">hi</span> <span style="color: #0000FF;">+=</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">lo</span><span style="color: #0000FF;">=</span><span style="color: #000000;">hi</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">object</span> <span style="color: #000000;">alo</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">array</span><span style="color: #0000FF;">[</span><span style="color: #000000;">lo</span><span style="color: #0000FF;">],</span>
<span style="color: #000000;">ahi</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">array</span><span style="color: #0000FF;">[</span><span style="color: #000000;">hi</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">alo</span> <span style="color: #0000FF;">></span> <span style="color: #000000;">ahi</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">array</span><span style="color: #0000FF;">[</span><span style="color: #000000;">lo</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">ahi</span>
<span style="color: #000000;">array</span><span style="color: #0000FF;">[</span><span style="color: #000000;">hi</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">alo</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;">"%V level %d, low %d, high %d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">array</span><span style="color: #0000FF;">,</span><span style="color: #000000;">level</span><span style="color: #0000FF;">,</span><span style="color: #000000;">low</span><span style="color: #0000FF;">,</span><span style="color: #000000;">high</span><span style="color: #0000FF;">})</span>
<span style="color: #000000;">swaps</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: #000000;">lo</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #000000;">hi</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #000000;">swaps</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">circle_sort_inner</span><span style="color: #0000FF;">(</span><span style="color: #000000;">low</span><span style="color: #0000FF;">,</span><span style="color: #000000;">low</span><span style="color: #0000FF;">+</span><span style="color: #000000;">mid</span><span style="color: #0000FF;">,</span><span style="color: #000000;">swaps</span><span style="color: #0000FF;">,</span><span style="color: #000000;">level</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">swaps</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">circle_sort_inner</span><span style="color: #0000FF;">(</span><span style="color: #000000;">low</span><span style="color: #0000FF;">+</span><span style="color: #000000;">mid</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">high</span><span style="color: #0000FF;">,</span><span style="color: #000000;">swaps</span><span style="color: #0000FF;">,</span><span style="color: #000000;">level</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">swaps</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">circle_sort</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;">"%V &lt;== (initial)\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">array</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">circle_sort_inner</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">array</span><span style="color: #0000FF;">),</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span> <span style="color: #0000FF;">?</span><span style="color: #008000;">"loop"</span> <span style="color: #008080;">end</span> <span style="color: #008080;">while</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;">"%V &lt;== (sorted)\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">array</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">array</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">101</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">8</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">6</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">}</span>
<span style="color: #000080;font-style:italic;">--array = {-4,-1,1,0,5,-7,-2,4,-6,-3,2,6,3,7,-5}
--array = {6, 7, 8, 9, 2, 5, 3, 4, 1}
--array = {2,14,4,6,8,1,3,5,7,9,10,11,0,13,12,-1}
--array = {"the","quick","brown","fox","jumps","over","the","lazy","dog"}
--array = {0.603704, 0.293639, 0.513965, 0.746246, 0.245282, 0.930508, 0.550878, 0.622534, 0.006089, 0.270426}
--array = shuffle(deep_copy(array))</span>
<span style="color: #000000;">circle_sort</span><span style="color: #0000FF;">()</span>
<!--</syntaxhighlight>-->
{{out}}
Shows the full inner workings: call depth and range being considered, after each swap made.
<pre>
{5,-1,101,-4,0,1,8,6,2,3} <== (initial)
{3,-1,101,-4,0,1,8,6,2,5} level 1, low 1, high 10
{3,-1,6,-4,0,1,8,101,2,5} level 1, low 1, high 10
{0,-1,6,-4,3,1,8,101,2,5} level 2, low 1, high 5
{0,-4,6,-1,3,1,8,101,2,5} level 2, low 1, high 5
{0,-4,-1,6,3,1,8,101,2,5} level 2, low 1, high 5
{-1,-4,0,6,3,1,8,101,2,5} level 3, low 1, high 3
{-4,-1,0,6,3,1,8,101,2,5} level 4, low 1, high 2
{-4,-1,0,3,6,1,8,101,2,5} level 3, low 4, high 5
{-4,-1,0,3,6,1,2,101,8,5} level 2, low 6, high 10
{-4,-1,0,3,6,1,2,8,101,5} level 2, low 6, high 10
{-4,-1,0,3,6,1,2,8,5,101} level 3, low 9, high 10
"loop"
{-4,-1,0,2,6,1,3,8,5,101} level 1, low 1, high 10
{-4,-1,0,2,1,6,3,8,5,101} level 1, low 1, high 10
{-4,-1,0,1,2,6,3,8,5,101} level 3, low 4, high 5
{-4,-1,0,1,2,6,3,5,8,101} level 2, low 6, high 10
{-4,-1,0,1,2,5,3,6,8,101} level 3, low 6, high 8
{-4,-1,0,1,2,3,5,6,8,101} level 4, low 6, high 7
"loop"
{-4,-1,0,1,2,3,5,6,8,101} <== (sorted)
</pre>
 
=={{header|Python}}==
The doctest passes with odd and even length lists. As do the random tests. Please see circle_sort.__doc__ for example use and output.
<langsyntaxhighlight lang="python">
#python3
#tests: expect no output.
Line 891 ⟶ 2,122:
print(N)
print(L)
</syntaxhighlight>
</lang>
 
=={{header|Quackery}}==
 
Having read the information on [http://sourceforge.net/p/forth-4th/wiki/Circle%20sort/ Sourceforge] mentioned in the task description, I note that the circle sort is most elegant when sorting an array the length of which is a power of two. Rather than mess with the central element of an odd length array and forego potential parallelisation I chose to pad the array to the nearest power of two with elements that were guaranteed to be in the right place (here, numbers one larger than the largest item in the array and trim it down to size after sorting. Additionally, rather than flagging exchanges, I use an O(n) test to see if a subarray is sorted to avoid unnecessary recursive calls.
 
The link at the end of the Sourceforge page to a paper on the subject is broken. [https://www.cscjournals.org/manuscript/Journals/IJEA/Volume6/Issue2/IJEA-48.pdf This link works.]
 
In the demonstration, I sort the characters in a string. In Quackery a string is a particular use of a nest of numbers (dynamic array of bignums). The string is a word from a famously circular novel. It seemed appropriate for such a novel "circle sort".
 
 
<syntaxhighlight lang="quackery"> [ dup size 2 < iff
[ drop true ] done
true swap
dup [] != if
[ behead swap witheach
[ tuck > if
[ dip not
conclude ] ] ]
drop ] is sorted ( [ --> b )
 
[ behead swap witheach
[ 2dup < iff
nip else drop ] ] is largest ( [ --> n )
 
[ dup largest 1+
over size
dup 1
[ 2dup > while
1 << again ]
nip swap -
dup dip [ of join ]
swap ] is pad ( [ --> n [ )
 
[ swap dup if
[ negate split drop ] ] is unpad ( n [ --> [ )
 
[ dup size times
[ i i^ > not iff
conclude done
dup i peek
over i^ peek
2dup < iff
[ rot i poke
i^ poke ]
else 2drop ] ] is reorder ( [ --> [ )
[ pad
[ [ dup sorted if done
reorder
dup size 2 / split
recurse swap
recurse swap join ]
dup sorted until ]
unpad ] is circlesort ( [ --> [ )
 
$ "bababadalgharaghtakamminarronnkonnbronntonnerronntuonnthunntrovarrhounawnskawntoohoohoordenenthurnuk"
dup echo$ cr
circlesort echo$ cr</syntaxhighlight>
 
{{out}}
 
<pre>bababadalgharaghtakamminarronnkonnbronntonnerronntuonnthunntrovarrhounawnskawntoohoohoordenenthurnuk
aaaaaaaaaaaabbbbddeeegghhhhhhhikkkklmmnnnnnnnnnnnnnnnnnnnnnoooooooooooooorrrrrrrrrrrstttttttuuuuuvww
</pre>
 
 
=={{header|Racket}}==
Line 898 ⟶ 2,194:
(diadic) function can be used to compare... e.g. <code>string&lt;?</code>.
 
<langsyntaxhighlight lang="racket">#lang racket
(define (circle-sort v0 [<? <])
(define v (vector-copy v0))
Line 932 ⟶ 2,228:
(for ([_ 10]) (sort-random-vector))
 
(circle-sort '#("table" "chair" "cat" "sponge") string<?)</langsyntaxhighlight>
 
{{out}}
Line 968 ⟶ 2,264:
'#("cat" "chair" "sponge" "table")
</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
 
The given algorithm can be simplified in several ways. There's no need to compute the midpoint, since the hi/lo will end up there. The extra swap conditional can be eliminated by incrementing hi at the correct moment inside the loop. There's no need to
pass accumulated swaps down the call stack.
 
This does generic comparisons, so it works on any ordered type, including numbers or strings.
<syntaxhighlight lang="raku" line>sub circlesort (@x, $beg, $end) {
my $swaps = 0;
if $beg < $end {
my ($lo, $hi) = $beg, $end;
repeat {
if @x[$lo] after @x[$hi] {
@x[$lo,$hi] .= reverse;
++$swaps;
}
++$hi if --$hi == ++$lo
} while $lo < $hi;
$swaps += circlesort(@x, $beg, $hi);
$swaps += circlesort(@x, $lo, $end);
}
$swaps;
}
 
say my @x = (-100..100).roll(20);
say @x while circlesort(@x, 0, @x.end);
 
say @x = <The quick brown fox jumps over the lazy dog.>;
say @x while circlesort(@x, 0, @x.end);</syntaxhighlight>
{{out}}
<pre>16 35 -64 -29 46 36 -1 -99 20 100 59 26 76 -78 39 85 -7 -81 25 88
-99 -78 16 20 36 -81 -29 46 25 59 -64 -7 39 26 88 -1 35 85 76 100
-99 -78 -29 -81 16 -64 -7 20 -1 39 25 26 36 46 59 35 76 88 85 100
-99 -81 -78 -64 -29 -7 -1 16 20 25 26 35 36 39 46 59 76 85 88 100
The quick brown fox jumps over the lazy dog.
The brown fox jumps lazy dog. quick over the
The brown dog. fox jumps lazy over quick the</pre>
 
=={{header|REXX}}==
This REXX version will work with any numbers that REXX supports, including negative and/or floating point numbers.;
<br>it also will work with character strings.
<lang rexx>/*REXX program uses a circle sort algorithm to sort an array (or list) of numbers. */
<syntaxhighlight lang="rexx">/*REXX program uses a circle sort algorithm to sort an array (or list) of numbers. */
parse arg x /*obtain optional arguments from the CL*/
if x='' | x="," then x= 6 7 8 9 2 5 3 4 1 /*Not specified? Then use the default.*/
call make_array 'before sort:' /*display the list and make an array. */
call circleSort # # /*invoke the circle sort subroutine. */
call make_list ' after sort:' /*make a list and display it to console*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
circleSort: do while .circleSrt(1, arg(1), 0)\==0; end; return
make_array: #= words(x); do i=1 for #; @.i= word(x, i); end; say arg(1) x; return
make_list: y= @.1; do j=2 tofor #-1; y= y @.j; end; say arg(1) y; return
.swap: parse arg a,b; parse value @.a @.b with @.b @.a; swaps= swaps+1; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
.circleSrt: procedure expose @.; parse arg loLO,hiHI,swaps /*obtain LO & HI arguments.*/
if loLO==hiHI then return swaps /*1 element? Done with sort.*/
high=hi HI; low=lo LO; mid= (hiHI-loLO) % 2 /*assign some indices. */
/* [↓] sort a section of #'s*/
do while loLO<hiHI /*sort within a section. */
if @.loLO>@.hiHI then call .swap loLO,hiHI /*are numbers out of order ? */
loLO=lo LO + 1; hi=hi-1 HI= HI - 1 /*add to LO; shrink the HI. */
end /*while ··· */ /*just process one section. */
_=hi+1 HI + 1 /*point to HI plus one. */
if loLO==hiHI & @.loLO>@._ then call .swap loLO, _ /*numbers still out of order?*/
swaps= .circleSrt(low, low+mid, swaps) /*sort the lower section. */
swaps= .circleSrt(low+mid+1, high, swaps) /* " " higher " */
return swaps /*the section sorting is done*/</langsyntaxhighlight>
'''{{out|output''' |text=&nbsp; when using the default input:}}
<pre>
before sort: 6 7 8 9 2 5 3 4 1
after sort: 1 2 3 4 5 6 7 8 9
</pre>
'''{{out|output''' |text=&nbsp; when using the input of: &nbsp; <tt> 2 3 3 5 5 1 1 7 7 6 6 4 4 0 0 </tt> }}
<pre>
before sort: 2 3 3 5 5 1 1 7 7 6 6 4 4 0 0
after sort: 0 0 1 1 2 3 3 4 4 5 5 6 6 7 7
</pre>
'''{{out|output''' |text=&nbsp; when using the input of: &nbsp; <tt> 2 3 44 44 5.77 +1 -12345 -3 -3.9 1e7 9 </tt> }}
<pre>
before sort: 2 3 44 44 5.77 +1 -12345 -3 -3.9 1e7 0
before after sort: -12345 -3.9 -3 0 +1 2 3 5.77 44 44 1e7
</pre>
'''{{out|output''' |text=&nbsp; when using the using the input of: &nbsp; <tt> assinine donkey bovine cattle canine dog corvine crow equine horse feline cat hircine goat leporine hare lupine wolf murine rodent piscine fish porcine pig ursine bear vulpine fox </tt>}}
<pre>
before sort: assinine donkey bovine cattle canine dog corvine crow equine horse feline cat hircine goat leporine hare lupine wolf murine rodent piscine fish porcine pig ursine bear vulpine fox
Line 1,019 ⟶ 2,354:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Sorting Algorithms/Circle Sort
# Date : 2017/10/23
# Author : Gal Zsolt (~ CalmoSoft ~)
# Email : <calmosoft@gmail.com>
 
test = [-4, -1, 1, 0, 5, -7, -2, 4, -6, -3, 2, 6, 3, 7, -5]
Line 1,067 ⟶ 2,399:
see svect
see "]" + nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,074 ⟶ 2,406:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">class Array
def circle_sort!
while _circle_sort!(0, size-1) > 0
Line 1,104 ⟶ 2,436:
ary = [6, 7, 8, 9, 2, 5, 3, 4, 1]
puts "before sort: #{ary}"
puts " after sort: #{ary.circle_sort!}"</langsyntaxhighlight>
 
{{out}}
before sort: [6, 7, 8, 9, 2, 5, 3, 4, 1]
after sort: [1, 2, 3, 4, 5, 6, 7, 8, 9]
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">fn _circle_sort<T: PartialOrd>(a: &mut [T], low: usize, high: usize, swaps: usize) -> usize {
if low == high {
return swaps;
}
let mut lo = low;
let mut hi = high;
let mid = (hi - lo) / 2;
let mut s = swaps;
while lo < hi {
if a[lo] > a[hi] {
a.swap(lo, hi);
s += 1;
}
lo += 1;
hi -= 1;
}
if lo == hi {
if a[lo] > a[hi + 1] {
a.swap(lo, hi + 1);
s += 1;
}
}
s = _circle_sort(a, low, low + mid, s);
s = _circle_sort(a, low + mid + 1, high, s);
return s;
}
 
fn circle_sort<T: PartialOrd>(a: &mut [T]) {
let len = a.len();
loop {
if _circle_sort(a, 0, len - 1, 0) == 0 {
break;
}
}
}
 
fn main() {
let mut v = vec![10, 8, 4, 3, 1, 9, 0, 2, 7, 5, 6];
println!("before: {:?}", v);
circle_sort(&mut v);
println!("after: {:?}", v);
}</syntaxhighlight>
 
{{out}}
<pre>
before sort: [610, 78, 84, 3, 1, 9, 20, 52, 37, 45, 16]
after sort: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
</pre>
 
=={{header|Scala}}==
<syntaxhighlight lang="scala">object CircleSort extends App {
 
def sort(arr: Array[Int]): Array[Int] = {
def circleSortR(arr: Array[Int], _lo: Int, _hi: Int, _numSwaps: Int): Int = {
var lo = _lo
var hi = _hi
var numSwaps = _numSwaps
 
def swap(arr: Array[Int], idx1: Int, idx2: Int): Unit = {
val tmp = arr(idx1)
arr(idx1) = arr(idx2)
arr(idx2) = tmp
}
 
if (lo == hi) return numSwaps
val (high, low) = (hi, lo)
val mid = (hi - lo) / 2
while ( lo < hi) {
if (arr(lo) > arr(hi)) {
swap(arr, lo, hi)
numSwaps += 1
}
lo += 1
hi -= 1
}
if (lo == hi && arr(lo) > arr(hi + 1)) {
swap(arr, lo, hi + 1)
numSwaps += 1
}
 
circleSortR(arr, low + mid + 1, high, circleSortR(arr, low, low + mid, numSwaps))
}
 
while (circleSortR(arr, 0, arr.length - 1, 0) != 0)()
arr
}
 
println(sort(Array[Int](2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1)).mkString(", "))
 
}</syntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func circlesort(arr, beg=0, end=arr.end) {
var swaps = 0
if (beg < end) {
Line 1,134 ⟶ 2,556:
 
var strs = ["John", "Kate", "Zerg", "Alice", "Joe", "Jane", "Alice"]
do { say strs } while circlesort(strs)</langsyntaxhighlight>
{{out}}
<pre>
Line 1,144 ⟶ 2,566:
["Alice", "Jane", "Alice", "Joe", "John", "Kate", "Zerg"]
["Alice", "Alice", "Jane", "Joe", "John", "Kate", "Zerg"]
</pre>
 
=={{header|Swift}}==
<syntaxhighlight lang="swift">func circleSort<T: Comparable>(_ array: inout [T]) {
func circSort(low: Int, high: Int, swaps: Int) -> Int {
if low == high {
return swaps
}
var lo = low
var hi = high
let mid = (hi - lo) / 2
var s = swaps
while lo < hi {
if array[lo] > array[hi] {
array.swapAt(lo, hi)
s += 1
}
lo += 1
hi -= 1
}
if lo == hi {
if array[lo] > array[hi + 1] {
array.swapAt(lo, hi + 1)
s += 1
}
}
s = circSort(low: low, high: low + mid, swaps: s)
s = circSort(low: low + mid + 1, high: high, swaps: s)
return s
}
while circSort(low: 0, high: array.count - 1, swaps: 0) != 0 {}
}
 
var array = [10, 8, 4, 3, 1, 9, 0, 2, 7, 5, 6]
print("before: \(array)")
circleSort(&array)
print(" after: \(array)")
 
var array2 = ["one", "two", "three", "four", "five", "six", "seven", "eight"]
print("before: \(array2)")
circleSort(&array2)
print(" after: \(array2)")</syntaxhighlight>
 
{{out}}
<pre>
before: [10, 8, 4, 3, 1, 9, 0, 2, 7, 5, 6]
after: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
before: ["one", "two", "three", "four", "five", "six", "seven", "eight"]
after: ["eight", "five", "four", "one", "seven", "six", "three", "two"]
</pre>
 
=={{header|uBasic/4tH}}==
This one uses the optimized version featured at [http://sourceforge.net/p/forth-4th/wiki/Circle%20sort/ Sourceforge].
<syntaxhighlight lang="text">PRINT "Circle sort:"
n = FUNC (_InitArray)
PROC _ShowArray (n)
Line 1,205 ⟶ 2,676:
 
PRINT
RETURN</langsyntaxhighlight>
 
=={{header|V (Vlang)}}==
{{trans|go}}
<syntaxhighlight lang="vlang">fn circle_sort(mut a []int, l int, h int, s int) int {
mut hi := h
mut lo := l
mut swaps := s
if lo == hi {
return swaps
}
high, low := hi, lo
mid := (hi - lo) / 2
for lo < hi {
if a[lo] > a[hi] {
a[lo], a[hi] = a[hi], a[lo]
swaps++
}
lo++
hi--
}
if lo == hi {
if a[lo] > a[hi+1] {
a[lo], a[hi+1] = a[hi+1], a[lo]
swaps++
}
}
swaps = circle_sort(mut a, low, low+mid, swaps)
swaps = circle_sort(mut a, low+mid+1, high, swaps)
return swaps
}
fn main() {
aa := [
[6, 7, 8, 9, 2, 5, 3, 4, 1],
[2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1],
]
for a1 in aa {
mut a:=a1.clone()
println("Original: $a")
for circle_sort(mut a, 0, a.len-1, 0) != 0 {
// empty block
}
println("Sorted : $a\n")
}
}</syntaxhighlight>
 
{{out}}
<pre>
Original: [6, 7, 8, 9, 2, 5, 3, 4, 1]
Sorted : [1, 2, 3, 4, 5, 6, 7, 8, 9]
 
Original: [2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1]
Sorted : [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14]
</pre>
 
=={{header|Wren}}==
<syntaxhighlight lang="wren">var circleSort // recursive
circleSort = Fn.new { |a, lo, hi, swaps|
if (lo == hi) return swaps
var high = hi
var low = lo
var mid = ((hi-lo)/2).floor
while (lo < hi) {
if (a[lo] > a[hi]) {
var t = a[lo]
a[lo] = a[hi]
a[hi] = t
swaps = swaps + 1
}
lo = lo + 1
hi = hi - 1
}
if (lo == hi) {
if (a[lo] > a[hi+1]) {
var t = a[lo]
a[lo] = a[hi+1]
a[hi+1] = t
swaps = swaps + 1
}
}
swaps = circleSort.call(a, low, low + mid, swaps)
swaps = circleSort.call(a, low + mid + 1, high, swaps)
return swaps
}
 
var array = [ [6, 7, 8, 9, 2, 5, 3, 4, 1], [2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1] ]
for (a in array) {
System.print("Before: %(a)")
while (circleSort.call(a, 0, a.count-1, 0) != 0) {}
System.print("After : %(a)")
System.print()
}</syntaxhighlight>
 
{{out}}
<pre>
Before: [6, 7, 8, 9, 2, 5, 3, 4, 1]
After : [1, 2, 3, 4, 5, 6, 7, 8, 9]
 
Before: [2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1]
After : [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 11, 12, 13, 14]
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang "XPL0">int Array;
 
func CircleSort(Lo, Hi, Swaps);
int Lo, Hi, Swaps;
int Low, High, Mid, T;
[if Lo = Hi then return Swaps;
Low:= Lo;
High:= Hi;
Mid:= (Hi-Lo)/2;
while Lo < Hi do
[if Array(Lo) > Array(Hi) then
[T:= Array(Lo); Array(Lo):= Array(Hi); Array(Hi):= T;
Swaps:= Swaps+1;
];
Lo:= Lo+1;
Hi:= Hi-1;
];
if Lo = Hi then
if Array(Lo) > Array(Hi+1) then
[T:= Array(Lo); Array(Lo):= Array(Hi+1); Array(Hi+1):= T;
Swaps:= Swaps+1;
];
Swaps:= CircleSort(Low, Low+Mid, Swaps);
Swaps:= CircleSort(Low+Mid+1, High, Swaps);
return Swaps;
];
 
int I;
[Array:= [5, -1, 101, -4, 0, 1, 8, 6, 2, 3];
while CircleSort(0, 10-1, 0) # 0 do [];
for I:= 0 to 10-1 do
[IntOut(0, Array(I)); ChOut(0, ^ )];
]</syntaxhighlight>
{{out}}
<pre>
-4 -1 0 1 2 3 5 6 8 101
</pre>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn circleSort(list){
csort:=fcn(list,lo,hi,swaps){
if(lo==hi) return(swaps);
Line 1,231 ⟶ 2,842:
while(csort(list,0,list.len()-1,0)){ list.println() }
list
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">circleSort(L(6,7,8,9,2,5,3,4,1));
circleSort(L(5,-1,101,-4,0,1,8,6,2,3));</langsyntaxhighlight>
{{out}}
<pre>
Line 1,251 ⟶ 2,862:
This version of Circle sort was based on the optimized version on [http://sourceforge.net/p/forth-4th/wiki/Circle%20sort/ Sourceforge]. It will also show a few asterisks while running, because it will take some time to finish (about two minutes).
 
<langsyntaxhighlight lang="zxbasic">
10 DIM a(100): DIM s(32): RANDOMIZE : LET p=1: GO SUB 3000: GO SUB 2000: GO SUB 4000
20 STOP
Line 1,263 ⟶ 2,874:
3000 FOR x=1 TO 100: LET a(x)=RND: NEXT x: RETURN
4000 FOR x=1 TO 100: PRINT x,a(x): NEXT x: RETURN
</syntaxhighlight>
</lang>
9,482

edits