Sorting algorithms/Comb sort: Difference between revisions

m
(add task to arm assembly raspberry pi)
m (→‎{{header|Wren}}: Minor tidy)
 
(24 intermediate revisions by 16 users not shown)
Line 1:
{{clarified-review}}
{{task|Sorting Algorithms}}
[[Category:Sorting]]
{{Sorting Algorithm}}
 
Line 50 ⟶ 51:
'''end function'''
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F combsort(&input)
V gap = input.len
V swaps = 1B
L gap > 1 | swaps
gap = max(1, Int(gap / 1.25))
swaps = 0B
L(i) 0 .< input.len - gap
V j = i + gap
I input[i] > input[j]
swap(&input[i], &input[j])
swaps = 1B
 
V y = [88, 18, 31, 44, 4, 0, 8, 81, 14, 78, 20, 76, 84, 33, 73, 75, 82, 5, 62, 70]
combsort(&y)
assert(y == sorted(y))
print(y)</syntaxhighlight>
 
{{out}}
<pre>
[0, 4, 5, 8, 14, 18, 20, 31, 33, 44, 62, 70, 73, 75, 76, 78, 81, 82, 84, 88]
</pre>
 
=={{header|360 Assembly}}==
Translation from prototype.<br>
The program uses ASM structured macros and two ASSIST macros to keep the code as short as possible.
<langsyntaxhighlight lang="360asm">* Comb sort 23/06/2016
COMBSORT CSECT
USING COMBSORT,R13 base register
Line 121 ⟶ 147:
YREGS
RI EQU 6 i
END COMBSORT</langsyntaxhighlight>
{{out}}
<pre>
-31 0 1 2 2 4 45 58 65 69 74 82 82 83 88 89 99 104 112 782
</pre>
 
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program combSort64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeConstantesARM64.inc"
 
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessSortOk: .asciz "Table sorted.\n"
szMessSortNok: .asciz "Table not sorted !!!!!.\n"
sMessResult: .asciz "Value : @ \n"
szCarriageReturn: .asciz "\n"
.align 4
#TableNumber: .quad 1,3,6,2,5,9,10,8,4,7
TableNumber: .quad 10,9,8,7,6,-5,4,3,2,1
.equ NBELEMENTS, (. - TableNumber) / 8
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrTableNumber // address number table
mov x1,0
mov x2,NBELEMENTS // number of élements
bl combSort
ldr x0,qAdrTableNumber // address number table
bl displayTable
ldr x0,qAdrTableNumber // address number table
mov x1,NBELEMENTS // number of élements
bl isSorted // control sort
cmp x0,1 // sorted ?
beq 1f
ldr x0,qAdrszMessSortNok // no !! error sort
bl affichageMess
b 100f
1: // yes
ldr x0,qAdrszMessSortOk
bl affichageMess
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrsZoneConv: .quad sZoneConv
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsMessResult: .quad sMessResult
qAdrTableNumber: .quad TableNumber
qAdrszMessSortOk: .quad szMessSortOk
qAdrszMessSortNok: .quad szMessSortNok
/******************************************************************/
/* control sorted table */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains the number of elements > 0 */
/* x0 return 0 if not sorted 1 if sorted */
isSorted:
stp x2,lr,[sp,-16]! // save registers
stp x3,x4,[sp,-16]! // save registers
mov x2,0
ldr x4,[x0,x2,lsl 3]
1:
add x2,x2,1
cmp x2,x1
bge 99f
ldr x3,[x0,x2, lsl 3]
cmp x3,x4
blt 98f
mov x4,x3
b 1b
98:
mov x0,0 // not sorted
b 100f
99:
mov x0,1 // sorted
100:
ldp x3,x4,[sp],16 // restaur 2 registers
ldp x2,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* comb sort */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains the first element */
/* x2 contains the number of element */
/* this routine use à factor to 1.28 see wikipedia for best factor */
combSort:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
stp x6,x7,[sp,-16]! // save registers
stp x8,x9,[sp,-16]! // save registers
sub x9,x2,x1 // compute gap
sub x2,x2,1 // compute end index n - 1
mov x7,100
1: // start loop 1
mul x9,x7,x9 // gap multiply by 100
lsr x9,x9,7 // divide by 128
cmp x9,0
mov x3,1
csel x9,x9,x3,ne
mov x3,x1 // start index
mov x8,0 // swaps
2: // start loop 2
add x4,x3,x9 // add gap to indice
cmp x4,x2
bgt 4f
ldr x5,[x0,x3,lsl 3] // load value A[j]
ldr x6,[x0,x4,lsl 3] // load value A[j+1]
cmp x6,x5 // compare value
bge 3f
str x6,[x0,x3,lsl 3] // if smaller inversion
str x5,[x0,x4,lsl 3]
mov x8,1 // swaps
3:
add x3,x3,1 // increment index j
b 2b
 
4:
//bl displayTable
cmp x9,1 // gap = 1 ?
bne 1b // no loop
cmp x8,1 // swaps ?
beq 1b // yes -> loop 1
100:
ldp x8,x9,[sp],16 // restaur 2 registers
ldp x6,x7,[sp],16 // restaur 2 registers
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* Display table elements */
/******************************************************************/
/* x0 contains the address of table */
displayTable:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
mov x2,x0 // table address
mov x3,0
1: // loop display table
ldr x0,[x2,x3,lsl 3]
ldr x1,qAdrsZoneConv
bl conversion10S // décimal conversion
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
add x3,x3,1
cmp x3,NBELEMENTS - 1
ble 1b
ldr x0,qAdrszCarriageReturn
bl affichageMess
mov x0,x2
100:
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC PrintArray(INT ARRAY a INT size)
INT i
 
Put('[)
FOR i=0 TO size-1
DO
IF i>0 THEN Put(' ) FI
PrintI(a(i))
OD
Put(']) PutE()
RETURN
 
PROC CombSort(INT ARRAY a INT size)
INT gap,i,tmp
BYTE swaps
 
gap=size swaps=0
WHILE gap#1 OR swaps#0
DO
gap=(gap*5)/4
IF gap<1 THEN gap=1 FI
 
i=0
swaps=0
 
WHILE i+gap<size
DO
IF a(i)>a(i+1) THEN
tmp=a(i) a(i)=a(i+1) a(i+1)=tmp
swaps=1
FI
i==+1
OD
OD
RETURN
 
PROC Test(INT ARRAY a INT size)
PrintE("Array before sort:")
PrintArray(a,size)
CombSort(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/Comb_sort.png Screenshot from Atari 8-bit computer]
<pre>
Array before sort:
[1 4 -1 0 3 7 4 8 20 -6]
Array after sort:
[-6 -1 0 1 3 4 4 7 8 20]
 
Array before sort:
[10 9 8 7 6 5 4 3 2 1 0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10]
Array after sort:
[-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9 10]
 
Array before sort:
[101 102 103 104 105 106 107 108]
Array after sort:
[101 102 103 104 105 106 107 108]
 
Array before sort:
[1 -1 1 -1 1 -1 1 -1 1 -1 1 -1]
Array after sort:
[-1 -1 -1 -1 -1 -1 1 1 1 1 1 1]
</pre>
 
=={{header|ActionScript}}==
<langsyntaxhighlight ActionScriptlang="actionscript">function combSort(input:Array)
{
var gap:uint = input.length;
Line 148 ⟶ 440:
}
return input;
}</langsyntaxhighlight>
 
=={{header|Ada}}==
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
procedure Comb_Sort is
generic
Line 198 ⟶ 490:
end loop;
Ada.Text_IO.New_Line;
end Comb_Sort;</langsyntaxhighlight>
 
Output:
<pre>-1 0 1 3 3 4 256</pre>
 
=={{header|ALGOL 68}}==
{{libheader|ALGOL 68-rows}}
<syntaxhighlight lang="algol68">BEGIN # comb sort #
PR read "rows.incl.a68" PR # include row (array) utilities - SHOW is used to display the array #
# comb-sorts in-place the array of integers input #
PROC comb sort = ( REF[]INT input )VOID:
IF INT input size = ( UPB input - LWB input ) + 1;
input size > 1
THEN # more than one element, so must sort #
INT gap := input size; # initial gap is the whole array size #
BOOL swapped := TRUE;
WHILE gap /= 1 OR swapped DO
# update the gap value for a next comb #
gap := ENTIER ( gap / 1.25 );
IF gap < 1 THEN
# ensure the gap is at least 1 #
gap := 1
FI;
INT i := LWB input;
swapped := FALSE;
# a single "comb" over the input list #
FOR i FROM LWB input WHILE i + gap <= UPB input DO
INT t = input[ i ];
INT i gap = i + gap;
IF t > input[ i gap ] THEN
# need to swap out-of-order items #
input[ i ] := input[ i gap ];
input[ i gap ] := t;
swapped := TRUE # Flag a swap has occurred, so the list is not guaranteed sorted yet #
FI
OD
OD
FI # comb sort # ;
# test #
[ 1 : 7 ]INT data := ( 9, -4, 0, 2, 3, 77, 1 ); # data to sort #
SHOW data;
comb sort( data );
print( ( " -> " ) );
SHOW data
END</syntaxhighlight>
{{out}}
<pre>
9 -4 0 2 3 77 1 -> -4 0 1 2 3 9 77
</pre>
 
=={{header|ALGOL W}}==
{{Trans|ALGOL 68}}
<syntaxhighlight lang="algolw">begin % comb sort %
% comb-sorts in-place the array of integers input with bounds lb :: ub %
procedure combSort ( integer array input ( * )
; integer value lb, ub
) ;
begin
integer inputSize, gap, i;
inputSize := ( ub - lb ) + 1;
if inputSize > 1 then begin
% more than one element, so must sort %
logical swapped;
gap := inputSize; % initial gap is the whole array size %
swapped := true;
while gap not = 1 or swapped do begin
% update the gap value for a next comb %
gap := entier( gap / 1.25 );
if gap < 1 then begin
% ensure the gap is at least 1 %
gap := 1
end if_gap_lt_1 ;
swapped := false;
% a single "comb" over the input list %
i := lb;
while i + gap <= ub do begin
integer t, iGap;
t := input( i );
iGap := i + gap;
if t > input( iGap ) then begin
% need to swap out-of-order items %
input( i ) := input( iGap );
input( iGap ) := t;
swapped := true % Flag a swap has occurred, so the list is not guaranteed sorted yet %
end if_t_gt_input__iGap ;
i := i + 1
end while_i_plus_gap_le_ub
end while_gap_ne_1_or_swapped
end if_inputSize_gt_1
end combSort ;
begin % test %
integer array data ( 1 :: 7 );
integer dPos;
dPos := 0;
for v := 9, -4, 0, 2, 3, 77, 1 do begin dPos := dPos + 1; data( dPos ) := v end;
for i := 1 until 7 do writeon( i_w := 1, s_w := 0, " ", data( i ) );
combSort( data, 1, 7 );
writeon( ( " -> " ) );
for i := 1 until 7 do writeon( i_w := 1, s_w := 0, " ", data( i ) )
end
end.</syntaxhighlight>
{{out}}
<pre>
9 -4 0 2 3 77 1 -> -4 0 1 2 3 9 77
</pre>
 
=={{header|AppleScript}}==
<syntaxhighlight lang="applescript">-- Comb sort with insertion sort finish.
-- Comb sort algorithm: Włodzimierz Dobosiewicz and Artur Borowy, 1980. Stephen Lacey and Richard Box, 1991.
 
on combSort(theList, l, r) -- Sort items l thru r of theLIst.
set listLen to (count theList)
if (listLen < 2) then return
-- Negative and/or transposed range indices.
if (l < 0) then set l to listLen + l + 1
if (r < 0) then set r to listLen + r + 1
if (l > r) then set {l, r} to {r, l}
script o
property lst : theList
end script
-- This implementation performs fastest with a comb gap divisor of 1.4
-- and the insertion sort taking over when the gap's down to 8 or less.
set divisor to 1.4
set gap to (r - l + 1) div divisor
repeat while (gap > 8)
repeat with i from l to (r - gap)
set j to i + gap
set lv to o's lst's item i
set rv to o's lst's item j
if (lv > rv) then
set o's lst's item i to rv
set o's lst's item j to lv
end if
end repeat
set gap to gap div divisor
end repeat
insertionSort(theList, l, r)
return -- nothing.
end combSort
 
on insertionSort(theList, l, r) -- Sort items l thru r of theList.
set listLength to (count theList)
if (listLength < 2) then return
if (l < 0) then set l to listLength + l + 1
if (r < 0) then set r to listLength + r + 1
if (l > r) then set {l, r} to {r, l}
script o
property lst : theList
end script
set highestSoFar to o's lst's item l
set rv to o's lst's item (l + 1)
if (highestSoFar > rv) then
set o's lst's item l to rv
else
set highestSoFar to rv
end if
repeat with j from (l + 2) to r
set rv to o's lst's item j
if (highestSoFar > rv) then
repeat with i from (j - 2) to l by -1
set lv to o's lst's item i
if (lv > rv) then
set o's lst's item (i + 1) to lv
else
set i to i + 1
exit repeat
end if
end repeat
set o's lst's item i to rv
else
set o's lst's item (j - 1) to highestSoFar
set highestSoFar to rv
end if
end repeat
set o's lst's item r to highestSoFar
return -- nothing.
end insertionSort
 
-- Demo:
local aList
set aList to {7, 56, 70, 22, 94, 42, 5, 25, 54, 90, 29, 65, 87, 27, 4, 5, 86, 8, 2, 30, 87, 12, 85, 86, 7}
combSort(aList, 1, -1) -- Sort items 1 thru -1 of aList.
aList</syntaxhighlight>
 
{{output}}
<syntaxhighlight lang="applescript">{2, 4, 5, 5, 7, 7, 8, 12, 22, 25, 27, 29, 30, 42, 54, 56, 65, 70, 85, 86, 86, 87, 87, 90, 94}</syntaxhighlight>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* program combSort.s */
Line 367 ⟶ 849:
/***************************************************/
.include "../affichage.inc"
</syntaxhighlight>
</lang>
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">combSort: function [items][
a: new items
gap: size a
swapped: true
 
while [or? gap > 1 swapped][
gap: (gap * 10) / 13
if or? gap=9 gap=10 -> gap: 11
if gap<1 -> gap: 1
swapped: false
i: 0
loop gap..dec size items 'j [
if a\[i] > a\[j] [
tmp: a\[i]
a\[i]: a\[j]
a\[j]: tmp
swapped: true
]
i: i + 1
]
]
return a
]
 
print combSort [3 1 2 8 5 7 9 4 6]</syntaxhighlight>
 
{{out}}
 
<pre>1 2 3 4 5 6 7 8 9</pre>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang="autohotkey">List1 = 23,76,99,58,97,57,35,89,51,38,95,92,24,46,31,24,14,12,57,78
List2 = 88,18,31,44,4,0,8,81,14,78,20,76,84,33,73,75,82,5,62,70
 
Line 416 ⟶ 930:
List .= (A_Index = 1 ? "" : ",") %Array%%A_Index%
Return, List
}</langsyntaxhighlight>
Message (1) box shows:
<pre>23,76,99,58,97,57,35,89,51,38,95,92,24,46,31,24,14,12,57,78
Line 425 ⟶ 939:
 
=={{header|AWK}}==
<langsyntaxhighlight lang="awk">function combsort( a, len, gap, igap, swap, swaps, i )
{
gap = len
Line 462 ⟶ 976:
for( i=0; i<length(a); i++ )
print a[i]
}</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight BBClang="bbc BASICbasic">DEF PROC_CombSort11(Size%)
 
gap%=Size%
Line 484 ⟶ 998:
UNTIL gap%=1 AND Finished%
 
ENDPROC</langsyntaxhighlight>
 
=={{header|C}}==
Implementation of Combsort11. Its efficiency can be improved by just switching to Insertion sort when the gap size becomes less than 10.
<langsyntaxhighlight lang="c">void Combsort11(double a[], int nElements)
{
int i, j, gap, swapped = 1;
Line 511 ⟶ 1,025:
}
}
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
 
namespace CombSort
Line 551 ⟶ 1,065:
}
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
This is copied from [[wp:Comb sort|the Wikipedia article]].
<langsyntaxhighlight lang="cpp">template<class ForwardIterator>
void combsort ( ForwardIterator first, ForwardIterator last )
{
Line 578 ⟶ 1,092:
}
}
}</langsyntaxhighlight>
 
=={{header|COBOL}}==
This excerpt contains just enough of the procedure division to show the workings. See the example for the bubble sort for a more complete program.
<langsyntaxhighlight COBOLlang="cobol"> C-PROCESS SECTION.
C-000.
DISPLAY "SORT STARTING".
Line 622 ⟶ 1,136:
 
F-999.
EXIT.</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defparameter *shrink* 1.3)
 
(defun comb-sort (input)
Line 640 ⟶ 1,154:
(setf swapped t))
while (or (> gap 1) swapped)
finally (return input)))</langsyntaxhighlight>
 
=={{header|D}}==
{{trans|Python}}
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm;
 
void combSort(T)(T[] input) pure nothrow @safe @nogc {
Line 665 ⟶ 1,179:
data.combSort;
data.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>[2, 4, 11, 17, 19, 24, 25, 28, 44, 46]</pre>
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| System.Types}}
'''Adaptation of Pascal'''
<syntaxhighlight lang="delphi">
program Comb_sort;
 
{$APPTYPE CONSOLE}
 
uses
System.SysUtils,
System.Types;
 
type
THelperIntegerDynArray = record helper for TIntegerDynArray
public
procedure CombSort;
procedure FillRange(Count: integer);
procedure Shuffle;
function ToString: string;
end;
 
{ THelperIntegerDynArray }
procedure THelperIntegerDynArray.CombSort;
var
i, gap, temp: integer;
swapped: boolean;
begin
gap := length(self);
swapped := true;
while (gap > 1) or swapped do
begin
gap := trunc(gap / 1.3);
if (gap < 1) then
gap := 1;
swapped := false;
for i := 0 to length(self) - gap - 1 do
if self[i] > self[i + gap] then
begin
temp := self[i];
self[i] := self[i + gap];
self[i + gap] := temp;
swapped := true;
end;
end;
end;
 
procedure THelperIntegerDynArray.FillRange(Count: integer);
var
i: Integer;
begin
SetLength(self, Count);
for i := 0 to Count - 1 do
Self[i] := i;
end;
 
procedure THelperIntegerDynArray.Shuffle;
var
i, j, tmp: integer;
count: integer;
begin
Randomize;
count := Length(self);
for i := 0 to count - 1 do
begin
j := i + Random(count - i);
tmp := self[i];
self[i] := self[j];
self[j] := tmp;
end;
end;
 
function THelperIntegerDynArray.ToString: string;
var
value: Integer;
begin
Result := '';
for value in self do
begin
Result := Result + ' ' + Format('%4d', [value]);
end;
Result := '[' + Result.Trim + ']';
end;
 
var
data: TIntegerDynArray;
 
begin
data.FillRange(10);
data.Shuffle;
writeln('The data before sorting:');
Writeln(data.ToString, #10);
 
data.CombSort;
 
writeln('The data after sorting:');
Writeln(data.ToString, #10);
 
Readln;
end.</syntaxhighlight>
{{out}}
<pre>
The data before sorting:
[1 9 0 6 2 7 3 5 4 8]
 
The data after sorting:
[0 1 2 3 4 5 6 7 8 9]
</pre>
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
 
class
Line 743 ⟶ 1,364:
end
 
</syntaxhighlight>
</lang>
Test:
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
APPLICATION
Line 778 ⟶ 1,399:
 
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 789 ⟶ 1,410:
=={{header|Elena}}==
ELENA 5.0 :
<langsyntaxhighlight lang="elena">import extensions;
import system'math;
import system'routines;
Line 830 ⟶ 1,451:
console.printLine("before:", list.asEnumerable());
console.printLine("after :", list.combSort().asEnumerable())
}</langsyntaxhighlight>
{{out}}
<pre>
Line 838 ⟶ 1,459:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Sort do
def comb_sort([]), do: []
def comb_sort(input) do
Line 858 ⟶ 1,479:
end
 
(for _ <- 1..20, do: :rand.uniform(20)) |> IO.inspect |> Sort.comb_sort |> IO.inspect</langsyntaxhighlight>
 
{{out}}
Line 868 ⟶ 1,489:
=={{header|Forth}}==
This is an implementation of Comb sort with a different ending. Here [[Gnome sort]] is used, since it is rather small. The dataset is rather large, because otherwise the Comb sort routine would never kick in, passing control to Gnome sort almost right away. Note Comb sort can be kept much simpler this way, because Combsort11 optimizations and swapped flags can be discarded.
<langsyntaxhighlight lang="forth">defer precedes
defer exchange
Line 914 ⟶ 1,535:
: .array 100 0 do example i cells + ? loop cr ;
.array example 100 combsort .array</langsyntaxhighlight>
 
===Less Clever Version===
This version is an academic demonstration that aligns with the algorithm. As is, it is limited to use one static array and sorts in ascending order only.
<langsyntaxhighlight lang="forth">\ combsort for the Forth Newbie (GForth)
 
HEX
\ gratuitous variables ( Addfor clarity but NOT re-entrant)
VARIABLE0 VALUE GAP
VARIABLE SORTED \ flag
 
DECIMAL
Line 929 ⟶ 1,549:
 
\ allocate a small array of cells
CREATE Q SIZE 2+ CELLS ALLOT
 
\ operator to index into the array
Line 935 ⟶ 1,555:
 
\ fill array and see array
: INITDATA ( -- ) SIZE 0 DO SIZE I - I ]Q ! LOOP ;
: SEEDATA ( -- ) CR SIZE 0 DO I ]Q @ U. LOOP ;
 
: SEEDATA ( -- ) CR SIZE 0 DO I ]Q @ U. LOOP ;
 
\ computedivide aby new gap1.35 using scaledForth's scaling divisionoperator
\ factored out forfound this example.ratio Couldto be a macro or inlinethe code.fastest
: /1.335/ ( n -- n' ) 100 10 13135 */ ;
 
: XCHG ( adr1 adr2 -- ) OVER @ OVER @ SWAP ROT ! SWAP ! ;
\ factored out for this example. Could be a macro or inline code.
: XCHG ( adr1 adr2 n1 n2-- ) SWAP ROT ! SWAP ! ;
 
: COMBSORT ( n -- )
DUP >R TO GAP \ copyset nGAP to return stackn
1+ GAP ! \ set GAP to n+1
BEGIN
GAP @ /1.335/ TO GAP ! \ re-compute the gap
SORTED ON
R@DUP GAP( @-- n) GAP - 0 \ n-gap is loop limit
DO
I GAP @ + ]Q @ I ]Q @ \ compute array addresses<
OVER @ OVER @ \ fetch the data in each cell
2DUP < \ compare a copy of the data
IF
XCHG I GAP + ]Q I ]Q XCHG \ Exchange the data in the cells
SORTED OFF \ flag we are not sorted
ELSE
2DROP 2DROP \ remove address and data
THEN
LOOP
SORTED @ GAP @ 0= AND \ test for complete
UNTIL
DROP
R> DROP ; \ remove 'n' from return stack </lang>
;</syntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">program Combsort_Demo
implicit none
Line 1,011 ⟶ 1,625:
end subroutine combsort
end program Combsort_Demo</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight Freebasiclang="freebasic">' version 21-10-2016
' compile with: fbc -s console
' for boundary checks on array's compile with: fbc -s console -exx
Line 1,100 ⟶ 1,714:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>normal comb sort
Line 1,112 ⟶ 1,726:
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=ade780ac2893fcfc95bf0d3feff6a3a8 Click this link to run this code]'''
<langsyntaxhighlight lang="gambas">Public Sub Main()
Dim siToSort As Short[] = [249, 28, 111, 36, 171, 98, 29, 448, 44, 147, 154, 46, 102, 183, 24,
120, 19, 123, 2, 17, 226, 11, 211, 25, 191, 205, 77]
Line 1,154 ⟶ 1,768:
Print
 
End</langsyntaxhighlight>
Output:
<pre>
Line 1,173 ⟶ 1,787:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,207 ⟶ 1,821:
}
}
}</langsyntaxhighlight>
 
More generic version that sorts anything that implements <code>sort.Interface</code>:
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,247 ⟶ 1,861:
}
}
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
Combsort solution:
<langsyntaxhighlight lang="groovy">def makeSwap = { a, i, j -> print "."; a[i] ^= a[j]; a[j] ^= a[i]; a[i] ^= a[j] }
 
def checkSwap = { a, i, j -> [(a[i] > a[j])].find { it }.each { makeSwap(a, i, j) } }
Line 1,266 ⟶ 1,880:
}
input
}</langsyntaxhighlight>
 
Combsort11 solution:
<langsyntaxhighlight lang="groovy">def combSort11 = { input ->
def swap = checkSwap.curry(input)
def size = input.size()
Line 1,280 ⟶ 1,894:
}
input
}</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="groovy">println (combSort([23,76,99,58,97,57,35,89,51,38,95,92,24,46,31,24,14,12,57,78,4]))
println (combSort11([23,76,99,58,97,57,35,89,51,38,95,92,24,46,31,24,14,12,57,78,4]))
println ()
println (combSort([88,18,31,44,4,0,8,81,14,78,20,76,84,33,73,75,82,5,62,70,12,7,1]))
println (combSort11([88,18,31,44,4,0,8,81,14,78,20,76,84,33,73,75,82,5,62,70,12,7,1]))</langsyntaxhighlight>
 
Output:
Line 1,298 ⟶ 1,912:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.List
import Control.Arrow
import Control.Monad
Line 1,310 ⟶ 1,924:
combSort xs = (snd. fst) $ until (\((b,_),g)-> b && g==1)
(\((_,xs),g) ->(gapSwapping g xs, fg g)) ((False,xs), fg $ length xs)
where fg = max 1. truncate. (/1.25). fromIntegral</langsyntaxhighlight>
Example:
<langsyntaxhighlight lang="haskell">*Main> combSort [23,76,99,58,97,57,35,89,51,38,95,92,24,46,31,24,14,12,57,78]
[12,14,23,24,24,31,35,38,46,51,57,57,58,76,78,89,92,95,97,99]</langsyntaxhighlight>
 
=={{header|Haxe}}==
<langsyntaxhighlight lang="haxe">class CombSort {
@:generic
public static function sort<T>(arr:Array<T>) {
Line 1,358 ⟶ 1,972:
Sys.println('Sorted Strings: ' + stringArray);
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,371 ⟶ 1,985:
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">procedure main() #: demonstrate various ways to sort a list and string
demosort(combsort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty")
end
Line 1,392 ⟶ 2,006:
}
return X
end</langsyntaxhighlight>
 
Note: This example relies on [[Sorting_algorithms/Bubble_sort#Icon| the supporting procedures 'sortop', and 'demosort' in Bubble Sort]]. The full demosort exercises the named sort of a list with op = "numeric", "string", ">>" (lexically gt, descending),">" (numerically gt, descending), a custom comparator, and also a string.
Line 1,404 ⟶ 2,018:
 
=={{header|Io}}==
<langsyntaxhighlight lang="io">List do(
combSortInPlace := method(
gap := size
Line 1,424 ⟶ 2,038:
 
lst := list(23, 76, 99, 58, 97, 57, 35, 89, 51, 38, 95, 92, 24, 46, 31, 24, 14, 12, 57, 78)
lst combSortInPlace println # ==> list(12, 14, 23, 24, 24, 31, 35, 38, 46, 51, 57, 57, 58, 76, 78, 89, 92, 95, 97, 99)</langsyntaxhighlight>
 
=={{header|IS-BASIC}}==
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "CombSrt.bas"
110 RANDOMIZE
120 NUMERIC ARRAY(11 TO 30)
Line 1,456 ⟶ 2,070:
370 NEXT
380 LOOP
390 END DEF</langsyntaxhighlight>
 
=={{header|J}}==
Line 1,462 ⟶ 2,076:
Large gap sizes allow some parallelism in comparisons and swaps. (If the gap size is G, then G pairs can be compared and swapped in parallel.) Beyond that, however, the data flow complexity of this algorithm requires a fair bit of micro-management.
 
<langsyntaxhighlight Jlang="j">combSort=:3 :0
gap=. #y
whilst.1 < gap+swaps do.
Line 1,474 ⟶ 2,088:
end.
y
)</langsyntaxhighlight>
 
Example use:
Line 1,484 ⟶ 2,098:
=={{header|Java}}==
This is copied from [[wp:Comb sort|the Wikipedia article]].
<langsyntaxhighlight lang="java">public static <E extends Comparable<? super E>> void sort(E[] input) {
int gap = input.length;
boolean swapped = true;
Line 1,501 ⟶ 2,115:
}
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">
// Node 5.4.1 tested implementation (ES6)
function is_array_sorted(arr) {
Line 1,551 ⟶ 2,165:
// Print the sorted array
console.log(arr);
}</langsyntaxhighlight>
 
 
Line 1,562 ⟶ 2,176:
{{works with|jq|1.4}}
An implementation of the pseudo-code in the task description:
<langsyntaxhighlight lang="jq"># Input should be the array to be sorted.
def combsort:
 
Line 1,595 ⟶ 2,209:
end)
| .[0] = $gap )
| .[2] ;</langsyntaxhighlight>
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia"># v0.6
 
function combsort!(x::Array)::Array
Line 1,618 ⟶ 2,232:
x = randn(100)
@show x combsort!(x)
@assert issorted(x)</langsyntaxhighlight>
 
{{out}}
Line 1,625 ⟶ 2,239:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
fun <T : Comparable<T>> combSort(input: Array<T>) {
Line 1,658 ⟶ 2,272:
combSort(ca)
println("Sorted : ${ca.contentToString()}")
}</langsyntaxhighlight>
 
{{out}}
Line 1,670 ⟶ 2,284:
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
'randomize 0.5
itemCount = 20
Line 1,709 ⟶ 2,323:
next i
end
</syntaxhighlight>
</lang>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function combsort(t)
local gapd, gap, swaps = 1.2473, #t, 0
while gap + swaps > 1 do
Line 1,727 ⟶ 2,341:
end
 
print(unpack(combsort{3,5,1,2,7,4,8,3,6,4,1}))</langsyntaxhighlight>
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">swap := proc(arr, a, b)
local temp;
temp := arr[a]:
Line 1,761 ⟶ 2,375:
arr := Array([17,3,72,0,36,2,3,8,40,0]);
combsort(arr, numelems(arr));
arr;</langsyntaxhighlight>
{{Out|Output}}
<pre>[0,0,2,3,3,8,17,36,40,72]</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">combSort[list_] := Module[{ gap = 0, listSize = 0, swaps = True},
gap = listSize = Length[list];
While[ !((gap <= 1) && (swaps == False)),
Line 1,780 ⟶ 2,394:
]
]
]</langsyntaxhighlight>
 
<pre>combSort@{2, 1, 3, 7, 6}
->{1, 2, 3, 6, 7}</pre>
</pre>
 
=={{header|MATLAB}} / {{header|Octave}}==
<langsyntaxhighlight MATLABlang="matlab">function list = combSort(list)
listSize = numel(list);
Line 1,816 ⟶ 2,428:
end %while
end %while
end %combSort</langsyntaxhighlight>
 
Sample Output:
<langsyntaxhighlight MATLABlang="matlab">>> combSort([4 3 1 5 6 2])
 
ans =
 
1 2 3 4 5 6</langsyntaxhighlight>
 
=={{header|MAXScript}}==
<langsyntaxhighlight MAXScriptlang="maxscript">fn combSort arr =
(
local gap = arr.count
Line 1,853 ⟶ 2,465:
)
return arr
)</langsyntaxhighlight>
Output:
<syntaxhighlight lang="maxscript">
<lang MAXScript>
a = for i in 1 to 10 collect random 1 10
#(2, 6, 5, 9, 10, 7, 2, 6, 1, 4)
combsort a
#(1, 2, 2, 4, 5, 6, 6, 7, 9, 10)
</syntaxhighlight>
</lang>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
 
options replace format comments java crossref savelog symbols binary
Line 1,914 ⟶ 2,526:
method isFalse public constant binary returns boolean
return \isTrue
</syntaxhighlight>
</lang>
;Output
<pre>
Line 1,937 ⟶ 2,549:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">proc combSort[T](a: var openarray[T]) =
var gap = a.len
var swapped = true
Line 1,946 ⟶ 2,558:
swapped = false
var i = 0
for j in gap .. < a.len:
if a[i] > a[j]:
swap a[i], a[j]
Line 1,954 ⟶ 2,566:
var a = @[4, 65, 2, -31, 0, 99, 2, 83, 782]
combSort a
echo a</langsyntaxhighlight>
Output:
<pre>@[-31, 0, 2, 2, 4, 65, 83, 99, 782]</pre>
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
bundle Default {
class Stooge {
Line 1,993 ⟶ 2,605:
}
}
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">let comb_sort ~input =
let input_length = Array.length input in
let gap = ref(input_length) in
Line 2,015 ⟶ 2,627:
done
done
;;</langsyntaxhighlight>
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
proc {CombSort Arr}
Low = {Array.low Arr}
Line 2,045 ⟶ 2,657:
in
{CombSort Arr}
{Show {Array.toRecord unit Arr}}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">combSort(v)={
my(phi=(1+sqrt(5))/2,magic=1/(1-exp(-phi)),g=#v,swaps);
while(g>1 | swaps,
Line 2,063 ⟶ 2,675:
);
v
};</langsyntaxhighlight>
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">program CombSortDemo;
 
 
Line 2,118 ⟶ 2,730:
end;
writeln;
end.</langsyntaxhighlight>
Output:
<pre>
Line 2,127 ⟶ 2,739:
</pre>
 
<langsyntaxhighlight lang="pascal">program CombSortDemo;
 
 
Line 2,179 ⟶ 2,791:
end;
writeln;
end.</langsyntaxhighlight>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">sub combSort {
my @arr = @_;
my $gap = @arr;
Line 2,197 ⟶ 2,809:
}
return @arr;
}</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<lang Phix>function comb_sort(sequence s)
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
integer gap = length(s)-1
while 1 do
<span style="color: #008080;">function</span> <span style="color: #000000;">comb_sort</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
gap = max(floor(gap/1.3),1)
<span style="color: #004080;">integer</span> <span style="color: #000000;">gap</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)-</span><span style="color: #000000;">1</span>
integer swapped = 0
<span style="color: #008080;">while</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
for i=1 to length(s)-gap do
<span style="color: #000000;">gap</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">max</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">gap</span><span style="color: #0000FF;">/</span><span style="color: #000000;">1.3</span><span style="color: #0000FF;">),</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
object si = s[i]
<span style="color: #004080;">integer</span> <span style="color: #000000;">swapped</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
if si>s[i+gap] then
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)-</span><span style="color: #000000;">gap</span> <span style="color: #008080;">do</span>
s[i] = s[i+gap]
<span style="color: #004080;">object</span> <span style="color: #000000;">si</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
s[i+gap] = si
<span style="color: #008080;">if</span> <span style="color: #000000;">si</span><span style="color: #0000FF;">></span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">+</span><span style="color: #000000;">gap</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">then</span>
swapped = 1
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">+</span><span style="color: #000000;">gap</span><span style="color: #0000FF;">]</span>
end if
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">+</span><span style="color: #000000;">gap</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">si</span>
end for
<span style="color: #000000;">swapped</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span>
if gap=1 and swapped=0 then exit end if
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end while
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
return s
<span style="color: #008080;">if</span> <span style="color: #000000;">gap</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">and</span> <span style="color: #000000;">swapped</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
end function</lang>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">comb_sort</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">shuffle</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)))</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
{1,2,3,4,5,6,7,8,9,10}
</pre>
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">function combSort($arr){
$gap = count($arr);
$swap = true;
Line 2,236 ⟶ 2,858:
}
return $arr;
}</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de combSort (Lst)
(let (Gap (length Lst) Swaps NIL)
(while (or (> Gap 1) Swaps)
Line 2,250 ⟶ 2,872:
(on Swaps) )
(pop 'Lst) ) ) ) )
Lst )</langsyntaxhighlight>
Output:
<pre>: (combSort (88 18 31 44 4 0 8 81 14 78 20 76 84 33 73 75 82 5 62 70))
Line 2,256 ⟶ 2,878:
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
/* From the pseudocode. */
comb_sort: procedure (A);
Line 2,282 ⟶ 2,904:
end;
end comb_sort;
</syntaxhighlight>
</lang>
 
=={{header|PowerShell}}==
Massaging gap to always hit 11. Based on PowerShell from [[Cocktail Sort]]
<langsyntaxhighlight PowerShelllang="powershell">function CombSort ($a) {
$l = $a.Length
$gap = 11
Line 2,316 ⟶ 2,938:
}
 
$l = 100; CombSort ( 1..$l | ForEach-Object { $Rand = New-Object Random }{ $Rand.Next( -( $l - 1 ), $l - 1 ) } )</langsyntaxhighlight>
 
=={{header|PureBasic}}==
Implementation of CombSort11.
<langsyntaxhighlight PureBasiclang="purebasic">;sorts an array of integers
Procedure combSort11(Array a(1))
Protected i, gap, swaps = 1
Line 2,341 ⟶ 2,963:
Wend
Wend
EndProcedure</langsyntaxhighlight>
Implementation of CombSort.
<langsyntaxhighlight PureBasiclang="purebasic">;sorts an array of integers
Procedure combSort(Array a(1))
Protected i, gap, swaps = 1
Line 2,362 ⟶ 2,984:
Wend
Wend
EndProcedure</langsyntaxhighlight>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">>>> def combsort(input):
gap = len(input)
swaps = True
Line 2,383 ⟶ 3,005:
>>> y
[0, 4, 5, 8, 14, 18, 20, 31, 33, 44, 62, 70, 73, 75, 76, 78, 81, 82, 84, 88]
>>> </langsyntaxhighlight>
 
=={{header|R}}==
<syntaxhighlight lang="r">
<lang R>
comb.sort<-function(a){
gap<-length(a)
Line 2,408 ⟶ 3,030:
}
 
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(require (only-in srfi/43 vector-swap!))
Line 2,430 ⟶ 3,052:
[swaps])))))
xs)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
{{trans|Perl}}
<syntaxhighlight lang="raku" perl6line>sub comb_sort ( @a is copy ) {
my $gap = +@a;
my $swaps = 1;
Line 2,455 ⟶ 3,077:
my @weights = (^50).map: { 100 + ( 1000.rand.Int / 10 ) };
say @weights.sort.Str eq @weights.&comb_sort.Str ?? 'ok' !! 'not ok';
</syntaxhighlight>
</lang>
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX program sorts and displays a stemmed array using the comb sort algorithm. */
call gen /*generate the @ array elements. */
call show 'before sort' /*display the before array elements. */
Line 2,464 ⟶ 3,086:
call combSort # /*invoke the comb sort (with # entries)*/
call show ' after sort' /*display the after array elements. */
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
combSort: procedure expose @.; parse arg N /*N: is the number of @ elements. */
Line 2,492 ⟶ 3,114:
#= #-1; w= length(#); return /*adjust # because of DO loop.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
show: do k=1 for #; say right('element',15) right(k,w) arg(1)":" @.k; end; return</langsyntaxhighlight>
 
Data trivia: &nbsp; A &nbsp; ''hendecagon'' &nbsp; (also known as an &nbsp; ''undecagon'' &nbsp; or &nbsp; ''unidecagon'') &nbsp; is
Line 2,551 ⟶ 3,173:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
aList = [3,5,1,2,7,4,8,3,6,4,1]
see combsort(aList)
Line 2,572 ⟶ 3,194:
end
return t
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">class Array
def combsort!
gap = size
Line 2,593 ⟶ 3,215:
end
 
p [23, 76, 99, 58, 97, 57, 35, 89, 51, 38, 95, 92, 24, 46, 31, 24, 14, 12, 57, 78].combsort!</langsyntaxhighlight>
results in
<pre>[12, 14, 23, 24, 24, 31, 35, 38, 46, 51, 57, 57, 58, 76, 78, 89, 92, 95, 97, 99]</pre>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn comb_sort<T: PartialOrd>(a: &mut [T]) {
let len = a.len();
let mut gap = len;
Line 2,624 ⟶ 3,246:
comb_sort(&mut v);
println!("after: {:?}", v);
}</langsyntaxhighlight>
 
{{out}}
Line 2,633 ⟶ 3,255:
 
=={{header|Sather}}==
<langsyntaxhighlight lang="sather">class SORT{T < $IS_LT{T}} is
 
private swap(inout a, inout b:T) is
Line 2,669 ⟶ 3,291:
#OUT + b + "\n";
end;
end;</langsyntaxhighlight>
 
=={{header|Scala}}==
===Imperative version (Ugly, side effects)===
<langsyntaxhighlight Scalalang="scala">object CombSort extends App {
val ia = Array(28, 44, 46, 24, 19, 2, 17, 11, 25, 4)
val ca = Array('X', 'B', 'E', 'A', 'Z', 'M', 'S', 'L', 'Y', 'C')
Line 2,701 ⟶ 3,323:
println(s"Sorted : ${sorted(ca).mkString("[", ", ", "]")}")
 
}</langsyntaxhighlight>
{{Out}}See it in running in your browser by [https://scalafiddle.io/sf/7ykMPZx/0 ScalaFiddle (JavaScript)] or by [https://scastie.scala-lang.org/Gp1ZcxnPQAKvToWFZLU7OA Scastie (JVM)].
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func comb_sort(arr) {
var gap = arr.len;
var swaps = true;
Line 2,719 ⟶ 3,341:
}
return arr;
}</langsyntaxhighlight>
 
=={{header|Swift}}==
{{trans|C}}
<langsyntaxhighlight Swiftlang="swift">func combSort(inout list:[Int]) {
var swapped = true
var gap = list.count
Line 2,745 ⟶ 3,367:
}
}
}</langsyntaxhighlight>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">proc combsort {input} {
set gap [llength $input]
while 1 {
Line 2,768 ⟶ 3,390:
 
set data {23 76 99 58 97 57 35 89 51 38 95 92 24 46 31 24 14 12 57 78}
puts [combsort $data]</langsyntaxhighlight>
Produces this output:
<pre>12 14 23 24 24 31 35 38 46 51 57 57 58 76 78 89 92 95 97 99</pre>
Line 2,804 ⟶ 3,426:
 
=={{header|uBasic/4tH}}==
<syntaxhighlight lang="text">PRINT "Comb sort:"
n = FUNC (_InitArray)
PROC _ShowArray (n)
Line 2,862 ⟶ 3,484:
PRINT
RETURN</langsyntaxhighlight>
 
=={{header|VBA}}==
{[trans|Phix}}<langsyntaxhighlight lang="vb">Function comb_sort(ByVal s As Variant) As Variant
Dim gap As Integer: gap = UBound(s)
Dim swapped As Integer
Line 2,891 ⟶ 3,513:
Debug.Print Join(s, ", ")
Debug.Print Join(comb_sort(s), ", ")
End Sub</langsyntaxhighlight>{{out}}
<pre>45, 414, 862, 790, 373, 961, 871, 56, 949, 364
45, 56, 364, 373, 414, 790, 862, 871, 949, 961</pre>
 
=={{header|V (Vlang)}}==
{{trans|go}}
<syntaxhighlight lang="v (vlang)">fn main() {
mut a := [170, 45, 75, -90, -802, 24, 2, 66]
println("before: $a")
comb_sort(mut a)
println("after: $a")
}
fn comb_sort(mut a []int) {
if a.len < 2 {
return
}
for gap := a.len; ; {
if gap > 1 {
gap = gap * 4 / 5
}
mut swapped := false
for i := 0; ; {
if a[i] > a[i+gap] {
a[i], a[i+gap] = a[i+gap], a[i]
swapped = true
}
i++
if i+gap >= a.len {
break
}
}
if gap == 1 && !swapped {
break
}
}
}</syntaxhighlight>
 
=={{header|Wren}}==
<langsyntaxhighlight ecmascriptlang="wren">var combSort = Fn.new { |a|
var gap = a.count
while (true) {
Line 2,917 ⟶ 3,573:
}
 
var asarray = [ [4, 65, 2, -31, 0, 99, 2, 83, 782, 1], [7, 5, 2, 6, 1, 4, 2, 6, 3] ]
for (a in asarray) {
System.print("Before: %(a)")
combSort.call(a)
System.print("After : %(a)")
System.print()
}</langsyntaxhighlight>
 
{{out}}
Line 2,933 ⟶ 3,589:
After : [1, 2, 2, 3, 4, 5, 6, 6, 7]
</pre>
 
=={{header|XPL0}}==
{{trans|ALGOL W}}
<syntaxhighlight lang "XPL0">
\Comb sorts in-place the array of integers Input with bounds LB :: UB
procedure CombSort ( Input, LB, UB );
integer Input, LB, UB;
integer InputSize, Gap, I, Swapped, T, IGap;
begin
InputSize := ( UB - LB ) + 1;
if InputSize > 1 then begin
\more than one element, so must sort
Gap := InputSize; \initial Gap is the whole array size
Swapped := true;
while Gap # 1 or Swapped do begin
\update the Gap value for a next comb
Gap := fix( Floor(float(Gap) / 1.25) );
if Gap < 1 then begin
\ensure the Gap is at least 1
Gap := 1
end; \if_Gap_lt_1
Swapped := false;
\a single "comb" over the input list
I := LB;
while I + Gap <= UB do begin
T := Input( I );
IGap := I + Gap;
if T > Input( IGap ) then begin
\need to swap out-of-order items
Input( I ) := Input( IGap );
Input( IGap ) := T;
\Flag a swap has occurred, so the list is not guaranteed sorted yet
Swapped := true
end; \if_t_gt_input__iGap
I := I + 1
end \while_I_plus_Gap_le_UB
end \while_Gap_ne_1_or_swapped
end \if_inputSize_gt_1
end; \combSort
 
integer Data, I;
begin \test
Data:= [0, 9, -4, 0, 2, 3, 77, 1];
for I := 1 to 7 do begin Text(0, " "); IntOut(0, Data( I ) ) end;
CombSort( Data, 1, 7 );
Text(0, ( " -> " ) );
for I := 1 to 7 do begin Text(0, " "); IntOut(0, Data( I ) ) end;
end</syntaxhighlight>
{{out}}
<pre>
9 -4 0 2 3 77 1 -> -4 0 1 2 3 9 77</pre>
 
=={{header|zkl}}==
{{trans|D}}
<langsyntaxhighlight lang="zkl">fcn combSort(list){
len,gap,swaps:=list.len(),len,True;
while(gap>1 or swaps){
Line 2,948 ⟶ 3,655:
}
list
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">combSort(List(28, 44, 46, 24, 19, 2, 17, 11, 25, 4)).println();
combSort("This is a test".toData()).text.println();</langsyntaxhighlight>
{{out}}
<pre>
9,476

edits