Sorting Algorithms/Circle Sort: Difference between revisions

m
m (Rust - replace Ord by PartialOrd)
m (→‎{{header|Wren}}: Minor tidy)
(21 intermediate revisions by 17 users not shown)
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 89 ⟶ 800:
-4 -1 0 3 6 1 2 8 5 101
-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++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
 
int circlesort(int* arr, int lo, int hi, int swaps) {
Line 138 ⟶ 918:
circlesortDriver(arr, sizeof(arr)/sizeof(int));
return 0;
}</langsyntaxhighlight>
Output:
<pre>6 7 8 9 2 5 3 4 1
Line 145 ⟶ 925:
 
=={{header|CoffeeScript}}==
<syntaxhighlight lang="text">circlesort = (arr, lo, hi, swaps) ->
if lo == hi
return (swaps)
Line 177 ⟶ 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 184 ⟶ 964:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.array, std.traits;
 
void circlesort(T)(T[] items) if (isMutable!T) {
Line 233 ⟶ 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 280 ⟶ 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 290 ⟶ 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 322 ⟶ 1,176:
: .sample sample /sample cells bounds do i ? 1 cells +loop ;
sample /sample sort .sample</langsyntaxhighlight>
 
=={{header|Fortran}}==
<langsyntaxhighlight lang="fortran">
!
module circlesort
Line 402 ⟶ 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 469 ⟶ 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
Line 475 ⟶ 1,329:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 516 ⟶ 1,370:
fmt.Printf("Sorted : %v\n\n", a)
}
}</langsyntaxhighlight>
 
{{out}}
Line 525 ⟶ 1,379:
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>
 
Line 530 ⟶ 1,419:
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 536 ⟶ 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 556 ⟶ 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 607 ⟶ 1,496:
arr[idx2] = tmp;
}
}</langsyntaxhighlight>
 
<pre>[2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1]
Line 620 ⟶ 1,509:
 
"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 656 ⟶ 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 697 ⟶ 1,586:
 
v = rand(10)
println("# $v\n -> ", ciclesort!(v))</langsyntaxhighlight>
 
{{out}}
Line 704 ⟶ 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 747 ⟶ 1,636:
while (circleSort(array2, 0, array2.size - 1, 0) != 0) ;
println("Sorted : ${array2.asList()}")
}</langsyntaxhighlight>
 
{{out}}
Line 760 ⟶ 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 791 ⟶ 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}}==
<langsyntaxhighlight lang="nim">proc innerCircleSort[T](a: var openArray[T], lo, hi, swaps: int): int =
var localSwaps: int = swaps
var localHi: int = hi
Line 832 ⟶ 1,779:
echo "Original: ", $arr[i]
arr[i].circleSort()
echo "Sorted: ", $arr[i], if i != arr.high: "\n" else: ""</langsyntaxhighlight>
 
{{out}}
Line 843 ⟶ 1,790:
=={{header|Objeck}}==
{{trans|Objeck}}
<langsyntaxhighlight lang="objeck">class CircleSort {
function : Main(args : String[]) ~ Nil {
circleSort([2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1]);
Line 893 ⟶ 1,840:
}
}
</syntaxhighlight>
</lang>
 
Output:
Line 905 ⟶ 1,852:
=={{header|PARI/GP}}==
This follows the pseudocode pretty closely.
<langsyntaxhighlight lang="parigp">circlesort(v)=
{
local(v=v); \\ share with cs
Line 930 ⟶ 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 936 ⟶ 1,883:
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">
{
source file name on linux is ./p.p
Line 1,014 ⟶ 1,961:
writeln();
end.
</syntaxhighlight>
</lang>
 
=={{header|Perl}}==
Less flexible than the Raku version, as written does only numeric comparisons.
{{trans|Raku}}
<langsyntaxhighlight lang="perl">sub circlesort {
our @x; local *x = shift;
my($beg,$end) = @_;
Line 1,041 ⟶ 1,988:
 
my @a = <16 35 -64 -29 46 36 -1 -99 20 100 59 26 76 -78 39 85 -7 -81 25 88>;
while (circlesort(\@a, 0, $#a)) { print join(' ', @a), "\n" }</langsyntaxhighlight>
{{out}}
<pre>-99 -78 16 20 36 -81 -29 46 25 59 -64 -7 39 26 88 -1 35 85 76 100
Line 1,049 ⟶ 1,996:
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>sequence array
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
 
function circle_sort_inner(integer lo, hi, swaps, level=1)
<span style="color: #004080;">sequence</span> <span style="color: #000000;">array</span>
if lo!=hi then
integer high := hi,
<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>
low := lo,
<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>
mid := floor((high-low)/2)
<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>
while lo <= hi do
<span style="color: #000000;">low</span> <span style="color: #0000FF;">:=</span> <span style="color: #000000;">lo</span><span style="color: #0000FF;">,</span>
hi += (lo=hi)
<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>
if array[lo] > array[hi] then
<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>
{array[lo],array[hi]} = {array[hi],array[lo]}
<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>
?{array,"level",level,{low,high}}
<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>
swaps += 1
<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>
end if
<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>
lo += 1
<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>
hi -= 1
<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>
end while
<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>
swaps = circle_sort_inner(low,low+mid,swaps,level+1)
<span style="color: #000000;">swaps</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
swaps = circle_sort_inner(low+mid+1,high,swaps,level+1)
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end if
<span style="color: #000000;">lo</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
return swaps
<span style="color: #000000;">hi</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">1</span>
end function
<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>
procedure circle_sort()
<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>
?{array,"<== (initial)"}
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
while circle_sort_inner(1, length(array), 0) do ?"loop" end while
<span style="color: #008080;">return</span> <span style="color: #000000;">swaps</span>
?{array,"<== (sorted)"}
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
end procedure
 
<span style="color: #008080;">procedure</span> <span style="color: #000000;">circle_sort</span><span style="color: #0000FF;">()</span>
array = {5, -1, 101, -4, 0, 1, 8, 6, 2, 3}
<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>
--array = {-4,-1,1,0,5,-7,-2,4,-6,-3,2,6,3,7,-5}
<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>
--array = {6, 7, 8, 9, 2, 5, 3, 4, 1}
<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>
--array = {2,14,4,6,8,1,3,5,7,9,10,11,0,13,12,-1}
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
--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}
<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>
--array = shuffle(array)
<span style="color: #000080;font-style:italic;">--array = {-4,-1,1,0,5,-7,-2,4,-6,-3,2,6,3,7,-5}
circle_sort()</lang>
--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 1,168 ⟶ 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 1,175 ⟶ 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 1,209 ⟶ 2,228:
(for ([_ 10]) (sort-random-vector))
 
(circle-sort '#("table" "chair" "cat" "sponge") string<?)</langsyntaxhighlight>
 
{{out}}
Line 1,253 ⟶ 2,272:
 
This does generic comparisons, so it works on any ordered type, including numbers or strings.
<syntaxhighlight lang="raku" perl6line>sub circlesort (@x, $beg, $end) {
my $swaps = 0;
if $beg < $end {
Line 1,274 ⟶ 2,293:
 
say @x = <The quick brown fox jumps over the lazy dog.>;
say @x while circlesort(@x, 0, @x.end);</langsyntaxhighlight>
{{out}}
<pre>16 35 -64 -29 46 36 -1 -99 20 100 59 26 76 -78 39 85 -7 -81 25 88
Line 1,285 ⟶ 2,304:
 
=={{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 for #-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 LO,HI,swaps /*obtain LO & HI arguments.*/
if LO==HI then return swaps /*1 element? Done with sort.*/
high= HI; low= LO; mid= (HI-LO) % 2 /*assign some indices. */
/* [↓] sort a section of #'s*/
do while LO<HI /*sort within a section. */
if @.LO>@.HI then call .swap LO,HI /*are numbers out of order ? */
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 LO==HI & @.LO>@._ then call .swap LO, _ /*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>
Line 1,334 ⟶ 2,354:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Sorting Algorithms/Circle Sort
 
Line 1,379 ⟶ 2,399:
see svect
see "]" + nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,386 ⟶ 2,406:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">class Array
def circle_sort!
while _circle_sort!(0, size-1) > 0
Line 1,416 ⟶ 2,436:
ary = [6, 7, 8, 9, 2, 5, 3, 4, 1]
puts "before sort: #{ary}"
puts " after sort: #{ary.circle_sort!}"</langsyntaxhighlight>
 
{{out}}
Line 1,423 ⟶ 2,443:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn _circle_sort<T: PartialOrd>(a: &mut [T], low: usize, high: usize, swaps: usize) -> usize {
if low == high {
return swaps;
Line 1,464 ⟶ 2,484:
circle_sort(&mut v);
println!("after: {:?}", v);
}</langsyntaxhighlight>
 
{{out}}
Line 1,473 ⟶ 2,493:
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">object CircleSort extends App {
 
def sort(arr: Array[Int]): Array[Int] = {
Line 1,512 ⟶ 2,532:
println(sort(Array[Int](2, 14, 4, 6, 8, 1, 3, 5, 7, 11, 0, 13, 12, -1)).mkString(", "))
 
}</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func circlesort(arr, beg=0, end=arr.end) {
var swaps = 0
if (beg < end) {
Line 1,536 ⟶ 2,556:
 
var strs = ["John", "Kate", "Zerg", "Alice", "Joe", "Jane", "Alice"]
do { say strs } while circlesort(strs)</langsyntaxhighlight>
{{out}}
<pre>
Line 1,546 ⟶ 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,607 ⟶ 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}}==
<langsyntaxhighlight ecmascriptlang="wren">var circleSort // recursive
circleSort = Fn.new { |a, lo, hi, swaps|
if (lo == hi) return swaps
Line 1,639 ⟶ 2,762:
}
 
var asarray = [ [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 asarray) {
System.print("Before: %(a)")
while (circleSort.call(a, 0, a.count-1, 0) != 0) {}
System.print("After : %(a)")
System.print()
}</langsyntaxhighlight>
 
{{out}}
Line 1,654 ⟶ 2,777:
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,680 ⟶ 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,700 ⟶ 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,712 ⟶ 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