Sorting algorithms/Shell sort: Difference between revisions

m
No edit summary
m (→‎{{header|Wren}}: Minor tidy)
 
(46 intermediate revisions by 26 users not shown)
Line 1:
{{task|Sorting Algorithms}}{{Sorting Algorithm}}
{{Sorting Algorithm}}
[[Category:Sorting]]
 
;Task:
Line 18 ⟶ 20:
Other good sequences are found at the [https://oeis.org/search?q=shell+sort On-Line Encyclopedia of Integer Sequences].
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F shell_sort(&seq)
V inc = seq.len I/ 2
L inc != 0
L(el) seq[inc..]
V i = L.index + inc
L i >= inc & seq[i - inc] > el
seq[i] = seq[i - inc]
i -= inc
seq[i] = el
inc = I inc == 2 {1} E inc * 5 I/ 11
 
V data = [22, 7, 2, -5, 8, 4]
shell_sort(&data)
print(data)</syntaxhighlight>
 
{{out}}
<pre>
[-5, 2, 4, 7, 8, 22]
</pre>
 
=={{header|360 Assembly}}==
{{trans|PL/I}}
The program uses ASM structured macros and two ASSIST macros to keep the code as short as possible.
<langsyntaxhighlight lang="360asm">* Shell sort 24/06/2016
SHELLSRT CSECT
USING SHELLSRT,R13 base register
Line 97 ⟶ 122:
RK EQU 8 incr
RT EQU 9 temp
END SHELLSRT</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 shellSort64.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
1:
ldr x0,qAdrTableNumber // address number table
mov x1,0 // not use in routine
mov x2,NBELEMENTS // number of élements
bl shellSort
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 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
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 x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[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 // error not sorted
b 100f
99:
mov x0,1 // sorted
100:
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
/***************************************************/
/* shell Sort */
/***************************************************/
 
/* x0 contains the address of table */
/* x1 contains the first element but not use !! */
/* this routine use first element at index zero !!! */
/* x2 contains the number of element */
shellSort:
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
sub x2,x2,1 // index last item
mov x1,x2 // init gap = last item
1: // start loop 1
lsr x1,x1,1 // gap = gap / 2
cbz x1,100f // if gap = 0 -> end
mov x3,x1 // init loop indice 1
2: // start loop 2
ldr x4,[x0,x3,lsl 3] // load first value
mov x5,x3 // init loop indice 2
3: // start loop 3
cmp x5,x1 // indice < gap
blt 4f // yes -> end loop 2
sub x6,x5,x1 // index = indice - gap
ldr x7,[x0,x6,lsl 3] // load second value
cmp x4,x7 // compare values
bge 4f
str x7,[x0,x5,lsl 3] // store if <
sub x5,x5,x1 // indice = indice - gap
b 3b // and loop
4: // end loop 3
str x4,[x0,x5,lsl 3] // store value 1 at indice 2
add x3,x3,1 // increment indice 1
cmp x3,x2 // end ?
ble 2b // no -> loop 2
b 1b // yes loop for new gap
100: // end function
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 // display value
bl conversion10 // call function
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
add x3,x3,1
cmp x3,#NBELEMENTS - 1
ble 1b
ldr x0,qAdrszCarriageReturn
bl affichageMess
100:
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
=={{header|Action!}}==
<syntaxhighlight lang="action!">PROC PrintArray(INT ARRAY a INT size)
INT i
 
Put('[)
FOR i=0 TO size-1
DO
IF i>0 THEN Put(' ) FI
PrintI(a(i))
OD
Put(']) PutE()
RETURN
 
PROC ShellSort(INT ARRAY a INT size)
INT stp,i,j,tmp,v
 
stp=size/2
WHILE stp>0
DO
FOR i=stp TO size-1
DO
tmp=a(i)
j=i
 
WHILE j>=stp
DO
v=a(j-stp)
IF v<=tmp THEN EXIT FI
 
a(j-stp)=a(j)
a(j)=v
j==-stp
OD
 
a(j)=tmp
OD
 
stp=stp/2
OD
RETURN
 
PROC Test(INT ARRAY a INT size)
PrintE("Array before sort:")
PrintArray(a,size)
ShellSort(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/Shell_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 shellSort(data:Array):Array
{
var inc:uint = data.length/2;
Line 122 ⟶ 412:
return data;
}
</syntaxhighlight>
</lang>
 
=={{header|Ada}}==
This is a generic implementation of the shell sort. Ada allows arrays to be indexed by integer or enumeration types starting at any value. This version deals with any kind or value of valid index type.
<langsyntaxhighlight lang="ada">generic
type Element_Type is digits <>;
type Index_Type is (<>);
Line 132 ⟶ 422:
package Shell_Sort is
procedure Sort(Item : in out Array_Type);
end Shell_Sort;</langsyntaxhighlight>
<langsyntaxhighlight lang="ada">package body Shell_Sort is
----------
Line 162 ⟶ 452:
end Sort;
 
end Shell_Sort;</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 169 ⟶ 459:
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}}
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-2.8 algol68g-2.8].}}
'''File: prelude/sort/shell.a68'''<langsyntaxhighlight lang="algol68"># -*- coding: utf-8 -*- #
 
COMMENT
Line 229 ⟶ 519:
shell sort in place(LOC[LWB seq: UPB seq]SORTELEMENT:=seq, sort cmp rev);
 
SKIP</langsyntaxhighlight>'''File: test/sort/shell.a68'''<langsyntaxhighlight lang="algol68">#!/usr/bin/a68g --script #
# -*- coding: utf-8 -*- #
 
Line 236 ⟶ 526:
 
[]SORTELEMENT char array data = "big fjords vex quick waltz nymph";
print((shell sort(char array data), new line))</langsyntaxhighlight>
{{out}}
<pre>
abcdefghiijklmnopqrstuvwxyz
</pre>
 
=={{header|AppleScript}}==
 
<syntaxhighlight lang="applescript">-- In-place Shell sort.
-- Algorithm: Donald Shell, 1959.
on ShellSort(theList, l, r) -- Sort items l thru r of theList.
set listLength to (count theList)
if (listLength < 2) then return
-- Convert negative and/or transposed range indices.
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}
-- The list as a script property to allow faster references to its items.
script o
property lst : theList
end script
set stepSize to (r - l + 1) div 2
repeat while (stepSize > 0)
repeat with i from (l + stepSize) to r
set currentValue to o's lst's item i
repeat with j from (i - stepSize) to l by -stepSize
set thisValue to o's lst's item j
if (thisValue > currentValue) then
set o's lst's item (j + stepSize) to thisValue
else
set j to j + stepSize
exit repeat
end if
end repeat
if (j < i) then set o's lst's item j to currentValue
end repeat
set stepSize to (stepSize / 2.2) as integer
end repeat
return -- nothing.
end ShellSort
property sort : ShellSort
 
-- Demo:
local aList
set aList to {56, 44, 72, 4, 93, 26, 61, 72, 52, 9, 87, 26, 73, 75, 94, 91, 30, 18, 63, 16}
sort(aList, 1, -1) -- Sort items 1 thru -1 of aList.
return aList</syntaxhighlight>
 
{{output}}
<syntaxhighlight lang="applescript">{4, 9, 16, 18, 26, 26, 30, 44, 52, 56, 61, 63, 72, 72, 73, 75, 87, 91, 93, 94}</syntaxhighlight>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program shellSort.s */
/************************************/
/* Constantes */
/************************************/
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessSortOk: .asciz "Table sorted.\n"
szMessSortNok: .asciz "Table not sorted !!!!!.\n"
sMessResult: .ascii "Value : "
sMessValeur: .fill 11, 1, ' ' @ size => 11
szCarriageReturn: .asciz "\n"
.align 4
iGraine: .int 123456
.equ NBELEMENTS, 10
#TableNumber: .int 1,3,6,2,5,9,10,8,4,7
TableNumber: .int 10,9,8,7,6,5,4,3,2,1
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
1:
ldr r0,iAdrTableNumber @ address number table
mov r1,#0 @ not use in routine
mov r2,#NBELEMENTS @ number of élements
bl shellSort
ldr r0,iAdrTableNumber @ address number table
bl displayTable
ldr r0,iAdrTableNumber @ address number table
mov r1,#NBELEMENTS @ number of élements
bl isSorted @ control sort
cmp r0,#1 @ sorted ?
beq 2f
ldr r0,iAdrszMessSortNok @ no !! error sort
bl affichageMess
b 100f
2: @ yes
ldr r0,iAdrszMessSortOk
bl affichageMess
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrsMessValeur: .int sMessValeur
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsMessResult: .int sMessResult
iAdrTableNumber: .int TableNumber
iAdrszMessSortOk: .int szMessSortOk
iAdrszMessSortNok: .int szMessSortNok
/******************************************************************/
/* control sorted table */
/******************************************************************/
/* r0 contains the address of table */
/* r1 contains the number of elements > 0 */
/* r0 return 0 if not sorted 1 if sorted */
isSorted:
push {r2-r4,lr} @ save registers
mov r2,#0
ldr r4,[r0,r2,lsl #2]
1:
add r2,#1
cmp r2,r1
movge r0,#1
bge 100f
ldr r3,[r0,r2, lsl #2]
cmp r3,r4
movlt r0,#0
blt 100f
mov r4,r3
b 1b
100:
pop {r2-r4,lr}
bx lr @ return
/***************************************************/
/* shell Sort */
/***************************************************/
 
/* r0 contains the address of table */
/* r1 contains the first element but not use !! */
/* this routine use first element at index zero !!! */
/* r2 contains the number of element */
shellSort:
push {r0-r7,lr} @save registers
 
sub r2,#1 @ index last item
mov r1,r2 @ init gap = last item
1: @ start loop 1
lsrs r1,#1 @ gap = gap / 2
beq 100f @ if gap = 0 -> end
mov r3,r1 @ init loop indice 1
2: @ start loop 2
ldr r4,[r0,r3,lsl #2] @ load first value
mov r5,r3 @ init loop indice 2
3: @ start loop 3
cmp r5,r1 @ indice < gap
blt 4f @ yes -> end loop 2
sub r6,r5,r1 @ index = indice - gap
ldr r7,[r0,r6,lsl #2] @ load second value
cmp r4,r7 @ compare values
strlt r7,[r0,r5,lsl #2] @ store if <
sublt r5,r1 @ indice = indice - gap
blt 3b @ and loop
4: @ end loop 3
str r4,[r0,r5,lsl #2] @ store value 1 at indice 2
add r3,#1 @ increment indice 1
cmp r3,r2 @ end ?
ble 2b @ no -> loop 2
b 1b @ yes loop for new gap
100: @ end function
pop {r0-r7,lr} @ restaur registers
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,iAdrsMessValeur @ display value
bl conversion10 @ call function
ldr r0,iAdrsMessResult
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
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registres
mov r2,#0 @ counter length
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call systeme
pop {r0,r1,r2,r7,lr} @ restaur des 2 registres */
bx lr @ return
/******************************************************************/
/* Converting a register to a decimal unsigned */
/******************************************************************/
/* r0 contains value and r1 address area */
/* r0 return size of result (no zero final in area) */
/* area size => 11 bytes */
.equ LGZONECAL, 10
conversion10:
push {r1-r4,lr} @ save registers
mov r3,r1
mov r2,#LGZONECAL
1: @ start loop
bl divisionpar10U @ unsigned r0 <- dividende. quotient ->r0 reste -> r1
add r1,#48 @ digit
strb r1,[r3,r2] @ store digit on area
cmp r0,#0 @ stop if quotient = 0
subne r2,#1 @ else previous position
bne 1b @ and loop
@ and move digit from left of area
mov r4,#0
2:
ldrb r1,[r3,r2]
strb r1,[r3,r4]
add r2,#1
add r4,#1
cmp r2,#LGZONECAL
ble 2b
@ and move spaces in end on area
mov r0,r4 @ result length
mov r1,#' ' @ space
3:
strb r1,[r3,r4] @ store space in area
add r4,#1 @ next position
cmp r4,#LGZONECAL
ble 3b @ loop if r4 <= area size
100:
pop {r1-r4,lr} @ restaur registres
bx lr @return
/***************************************************/
/* division par 10 unsigned */
/***************************************************/
/* r0 dividende */
/* r0 quotient */
/* r1 remainder */
divisionpar10U:
push {r2,r3,r4, lr}
mov r4,r0 @ save value
//mov r3,#0xCCCD @ r3 <- magic_number lower raspberry 3
//movt r3,#0xCCCC @ r3 <- magic_number higter raspberry 3
ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2
umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0)
mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3
add r2,r0,r0, lsl #2 @ r2 <- r0 * 5
sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)
pop {r2,r3,r4,lr}
bx lr @ leave function
iMagicNumber: .int 0xCCCCCCCD
</syntaxhighlight>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">shellSort: function [items][
a: new items
h: size a
 
while [h > 0][
h: h / 2
loop h..dec size a 'i [
k: a\[i]
j: i
 
while [and? [j >= h] [k < a\[j-h]]][
a\[j]: a\[j-h]
j: j - h
]
a\[j]: k
]
]
return a
]
 
print shellSort [3 1 2 8 5 7 9 4 6]</syntaxhighlight>
 
{{out}}
 
<pre>1 2 3 4 5 6 7 8 9</pre>
 
=={{header|ATS}}==
 
===For arrays whose elements may be of linear type===
 
<syntaxhighlight lang="ats">(* Shell sort with both the gap sequence and the order predicate
selected by templates. *)
 
#include "share/atspre_staload.hats"
 
(*------------------------------------------------------------------*)
(* Interface *)
 
extern fn {a : vt@ype} (* The "less than" template. *)
shell_sort$lt : (&a, &a) -<> bool
 
extern fn {} (* Maps array size to a gap sequence. *)
shell_sort$gaps : {n : int} size_t n -<> List1 ([i : pos] size_t i)
 
extern fn {a : vt@ype}
shell_sort {n : int}
(arr : &array (a, n) >> _,
n : size_t n)
:<!wrt> void
 
(*------------------------------------------------------------------*)
(* Implementation *)
 
extern praxi
array_v_takeout2 (* Get views for two distinct array elements.*)
{a : vt@ype}
{p : addr}
{n : int}
{i, j : nat | i < n; j < n; i != j}
(pfarr : array_v (a, p, n))
:<prf> @(a @ p + (i * sizeof a),
a @ p + (j * sizeof a),
(a @ p + (i * sizeof a),
a @ p + (j * sizeof a)) -<prf,lin> array_v (a, p, n))
 
implement {a}
shell_sort {n} (arr, n) =
let
fun
gapped_sort {gap : pos | gap < n}
{i : int | gap <= i; i <= n}
{p_arr : addr}
.<n - i>.
(pf_arr : !array_v (a, p_arr, n) >> _ |
p_arr : ptr p_arr,
gap : size_t gap,
i : size_t i)
:<!wrt> void =
if i <> n then
let
fun
move_elems {j : nat | j <= i}
.<j>.
(pf_arr : !array_v (a, p_arr, n) >> _ |
j : size_t j)
:<!wrt> void =
(* For simplicity in the safe use of an array, use
interchanges of array elements, instead of a temporary
variable and moves. *)
if gap <= j then
let
stadef k = j - gap
prval () = prop_verify {0 <= k} ()
prval () = prop_verify {k < j} ()
val k : size_t k = j - gap
 
val pk = ptr_add<a> (p_arr, k)
and pj = ptr_add<a> (p_arr, j)
 
prval @(pfk, pfj, fpf) =
array_v_takeout2 {a} {p_arr} {n} {k, j} pf_arr
val is_less = shell_sort$lt<a> (!pj, !pk)
prval () = pf_arr := fpf (pfk, pfj)
in
if is_less then
begin
array_interchange (!p_arr, k, j);
move_elems (pf_arr | k)
end
end
in
move_elems (pf_arr | i);
gapped_sort (pf_arr | p_arr, gap, succ i)
end
 
fun
go_through_gaps
{num_gaps : nat}
.<num_gaps>.
(arr : &array (a, n) >> _,
gaps : list ([i : pos] size_t i, num_gaps))
:<!wrt> void =
case+ gaps of
| list_nil () => ()
| list_cons (gap, more_gaps) =>
if n <= gap then
go_through_gaps (arr, more_gaps)
else
begin
gapped_sort (view@ arr | addr@ arr, gap, gap);
go_through_gaps (arr, more_gaps)
end
in
go_through_gaps (arr, shell_sort$gaps<> n)
end
 
(*------------------------------------------------------------------*)
 
implement
shell_sort$lt<int> (x, y) =
x < y
 
implement
main0 () =
let
(* Gaps by Marcin Ciura. https://oeis.org/A102549 *)
val ciura_gaps =
$list{[i : pos] size_t i}
(i2sz 1750,
i2sz 701, i2sz 301,
i2sz 132, i2sz 57,
i2sz 23, i2sz 10,
i2sz 4, i2sz 1)
 
implement
shell_sort$gaps<> n =
(* Use Ciura's gaps, regardless of array size. *)
ciura_gaps
 
#define SIZE 30
var i : [i : nat] int i
var arr : array (int, SIZE)
in
array_initize_elt<int> (arr, i2sz SIZE, 0);
for (i := 0; i < SIZE; i := succ i)
arr[i] := $extfcall (int, "rand") % 10;
 
for (i := 0; i < SIZE; i := succ i)
print! (" ", arr[i]);
println! ();
 
shell_sort<int> (arr, i2sz SIZE);
 
for (i := 0; i < SIZE; i := succ i)
print! (" ", arr[i]);
println! ()
end</syntaxhighlight>
 
{{out}}
<pre>$ patscc -DATS_MEMALLOC_GCBDW -O3 shell_sort_task.dats -lgc && ./a.out
3 6 7 5 3 5 6 2 9 1 2 7 0 9 3 6 0 6 2 6 1 8 7 9 2 0 2 3 7 5
0 0 0 1 1 2 2 2 2 2 3 3 3 3 5 5 5 6 6 6 6 6 7 7 7 7 8 9 9 9</pre>
 
Comments:
 
Because the value of a[i] ends up in a particular spot earlier in the array, it is common to store that value in a temporary variable, rather than use interchanges (swaps) to move the value through the array. Writing "safe" code to do it with a temporary variable, however, would have been tedious, so I used interchanges. One can always write the implementation "unsafely", however. This will still leave you with about as much "safety" as one would expect from most other languages.
 
Furthermore, there is no difficulty in using the temporary-variable approach, if the elements of the array are assumed to be non-linear ('''t@ype''' instead of '''vt@ype'''). For example, the element type used in the demonstration ('''int''') is not linear. And so the next version of the sort ...
 
===For arrays whose elements must be of non-linear type===
 
The differences from the previous implementation are mainly in the '''gapped_sort''' function. Note that the order predicate now gets its arguments by value instead of by reference.
 
<syntaxhighlight lang="ats">(* Shell sort with both the gap sequence and the order predicate
selected by templates. *)
(* This version is only for arrays of non-linear elements (whose
values may freely be copied). Thus the code looks more like what
one would write in most other programming languages. *)
 
#include "share/atspre_staload.hats"
 
(*------------------------------------------------------------------*)
(* Interface *)
 
extern fn {a : t@ype} (* The "less than" template. *)
shell_sort2$lt : (a, a) -<> bool
 
extern fn {} (* Maps array size to a gap sequence. *)
shell_sort2$gaps : {n : int} size_t n -<> List1 ([i : pos] size_t i)
 
extern fn {a : t@ype}
shell_sort2 {n : int}
(arr : &array (a, n) >> _,
n : size_t n)
:<!wrt> void
 
(*------------------------------------------------------------------*)
(* Implementation *)
 
implement {a}
shell_sort2 {n} (arr, n) =
let
macdef lt = shell_sort2$lt<a>
 
fun
gapped_sort {gap : pos | gap < n}
{i : int | gap <= i; i <= n}
.<n - i>.
(arr : &array (a, n) >> _,
gap : size_t gap,
i : size_t i)
:<!wrt> void =
if i <> n then
let
fun
move_elems {j : nat | j <= i}
.<j>.
(arr : &array (a, n) >> _,
temp : a,
j : size_t j)
:<!wrt> void =
if j < gap then
arr[j] := temp
else if ~(temp \lt arr[j - gap]) then
arr[j] := temp
else
begin
arr[j] := arr[j - gap];
move_elems (arr, temp, j - gap)
end
in
move_elems (arr, arr[i], i);
gapped_sort (arr, gap, succ i)
end
 
fun
go_through_gaps
{num_gaps : nat}
.<num_gaps>.
(arr : &array (a, n) >> _,
gaps : list ([i : pos] size_t i, num_gaps))
:<!wrt> void =
case+ gaps of
| list_nil () => ()
| list_cons (gap, more_gaps) =>
if n <= gap then
go_through_gaps (arr, more_gaps)
else
begin
gapped_sort (arr, gap, gap);
go_through_gaps (arr, more_gaps)
end
in
go_through_gaps (arr, shell_sort2$gaps<> n)
end
 
(*------------------------------------------------------------------*)
 
implement
shell_sort2$lt<int> (x, y) =
x < y
 
implement
main0 () =
let
(* Gaps by Marcin Ciura. https://oeis.org/A102549 *)
val ciura_gaps =
$list{[i : pos] size_t i}
(i2sz 1750,
i2sz 701, i2sz 301,
i2sz 132, i2sz 57,
i2sz 23, i2sz 10,
i2sz 4, i2sz 1)
 
implement
shell_sort2$gaps<> n =
(* Use Ciura's gaps, regardless of array size. *)
ciura_gaps
 
#define SIZE 30
var i : [i : nat] int i
var arr : array (int, SIZE)
in
array_initize_elt<int> (arr, i2sz SIZE, 0);
for (i := 0; i < SIZE; i := succ i)
arr[i] := $extfcall (int, "rand") % 10;
 
for (i := 0; i < SIZE; i := succ i)
print! (" ", arr[i]);
println! ();
 
shell_sort2<int> (arr, i2sz SIZE);
 
for (i := 0; i < SIZE; i := succ i)
print! (" ", arr[i]);
println! ()
end</syntaxhighlight>
 
{{out}}
<pre>$ patscc -DATS_MEMALLOC_GCBDW -O3 shell_sort_task_nonlinear.dats -lgc && ./a.out
3 6 7 5 3 5 6 2 9 1 2 7 0 9 3 6 0 6 2 6 1 8 7 9 2 0 2 3 7 5
0 0 0 1 1 2 2 2 2 2 3 3 3 3 5 5 5 6 6 6 6 6 7 7 7 7 8 9 9 9</pre>
 
=={{header|AutoHotkey}}==
ahk forum: [http://www.autohotkey.com/forum/viewtopic.php?t=44657&postdays=0&postorder=asc&start=131 discussion]
<langsyntaxhighlight AutoHotkeylang="autohotkey">MsgBox % ShellSort("")
MsgBox % ShellSort("xxx")
MsgBox % ShellSort("3,2,1")
Line 263 ⟶ 1,163:
s .= "," . a%A_Index%
Return SubStr(s,2) ; drop leading comma
}</syntaxhighlight>
}</lang>
 
=={{header|AWK}}==
{{trans|Fortran}}
<langsyntaxhighlight lang="awk">{
line[NR] = $0
}
Line 291 ⟶ 1,191:
print line[i]
}
}</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
Note that the array index is assumed to start at zero.
<langsyntaxhighlight lang="bbcbasic"> DIM test(9)
test() = 4, 65, 2, -31, 0, 99, 2, 83, 782, 1
PROCshellsort(test(), 10)
Line 319 ⟶ 1,219:
NEXT
ENDWHILE
ENDPROC</langsyntaxhighlight>
{{out}}
<pre>
Line 326 ⟶ 1,226:
 
=={{header|BCPL}}==
<langsyntaxhighlight BCPLlang="bcpl">GET "libhdr"
 
LET shellsort(v, upb) BE
Line 374 ⟶ 1,274:
{ //FOR i = 1 TO n-1 UNLESS v!i<=v!(i+1) RESULTIS FALSE
RESULTIS TRUE
}</langsyntaxhighlight>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
 
void shell_sort (int *a, int n) {
Line 403 ⟶ 1,303:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
4 65 2 -31 0 99 2 83 782 1
-31 0 1 2 2 4 65 83 99 782
</pre>
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="c sharp|c#">
public static class ShellSorter
{
public static void Sort<T>(IList<T> list) where T : IComparable
{
int n = list.Count;
int h = 1;
 
while (h < (n >> 1))
{
h = (h << 1) + 1;
}
 
while (h >= 1)
{
for (int i = h; i < n; i++)
{
int k = i - h;
for (int j = i; j >= h && list[j].CompareTo(list[k]) < 0; k -= h)
{
T temp = list[j];
list[j] = list[k];
list[k] = temp;
j = k;
}
}
h >>= 1;
}
}
}
</syntaxhighlight>
{{out}}
<pre>
Before:
=======
-28 64 51 96 24 -51 15 4 51 37 -28 64 -18 -45 63 -64 -75 16
32 -44 -26 -50 -30 94 -55 -60 51 -30 14 -16 -42 22 91 -85 100 -14
-35 20 -73 11 -65 53 -25 -21 -65 16 -36 35 -69 -16 -13 -21 -103 80
-51 40 2 -7 11 29 65 -28 63 -108 -45 -8 -11 73 -8 -34 41 -20
-55 -64 4 41 5 -13 37 -39 -11 20 -24 -62 30 -19 30 -17 -11 -15
104 -14 -35 14 5 20 58 -38 6 -41 -23 88 49 -7 -54 -40 10 6
-57 -77 -6 -72 122 23 -39 67 121 63 28 31 43 -33 -1 59 -5 -91
 
After:
======
-108 -103 -91 -85 -77 -75 -73 -72 -69 -65 -65 -64 -64 -62 -60 -57 -55 -55
-54 -51 -51 -50 -45 -45 -44 -42 -41 -40 -39 -39 -38 -36 -35 -35 -34 -33
-30 -30 -28 -28 -28 -26 -25 -24 -23 -21 -21 -20 -19 -18 -17 -16 -16 -15
-14 -14 -13 -13 -11 -11 -11 -8 -8 -7 -7 -6 -5 -1 2 4 4 5
5 6 6 10 11 11 14 14 15 16 16 20 20 20 22 23 24 28
29 30 30 31 32 35 37 37 40 41 41 43 49 51 51 51 53 58
59 63 63 63 64 64 65 67 73 80 88 91 94 96 100 104 121 122
</pre>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">
#include <time.h>
#include <iostream>
Line 485 ⟶ 1,440:
}
//--------------------------------------------------------------------------------------------------
</syntaxhighlight>
</lang>
{{out}}
<pre>
Before:
=======
-28 64 51 96 24 -51 15 4 51 37 -28 64 -18 -45 63 -64 -75 16
32 -44 -26 -50 -30 94 -55 -60 51 -30 14 -16 -42 22 91 -85 100 -14
-35 20 -73 11 -65 53 -25 -21 -65 16 -36 35 -69 -16 -13 -21 -103 80
-51 40 2 -7 11 29 65 -28 63 -108 -45 -8 -11 73 -8 -34 41 -20
-55 -64 4 41 5 -13 37 -39 -11 20 -24 -62 30 -19 30 -17 -11 -15
104 -14 -35 14 5 20 58 -38 6 -41 -23 88 49 -7 -54 -40 10 6
-57 -77 -6 -72 122 23 -39 67 121 63 28 31 43 -33 -1 59 -5 -91
 
After:
======
-108 -103 -91 -85 -77 -75 -73 -72 -69 -65 -65 -64 -64 -62 -60 -57 -55 -55
-54 -51 -51 -50 -45 -45 -44 -42 -41 -40 -39 -39 -38 -36 -35 -35 -34 -33
-30 -30 -28 -28 -28 -26 -25 -24 -23 -21 -21 -20 -19 -18 -17 -16 -16 -15
-14 -14 -13 -13 -11 -11 -11 -8 -8 -7 -7 -6 -5 -1 2 4 4 5
5 6 6 10 11 11 14 14 15 16 16 20 20 20 22 23 24 28
29 30 30 31 32 35 37 37 40 41 41 43 49 51 51 51 53 58
59 63 63 63 64 64 65 67 73 80 88 91 94 96 100 104 121 122
</pre>
 
=={{header|C sharp|C#}}==
<lang C sharp|C#>
public static class ShellSorter
{
public static void Sort<T>(IList<T> list) where T : IComparable
{
int n = list.Count;
int h = 1;
 
while (h < (n >> 1))
{
h = (h << 1) + 1;
}
 
while (h >= 1)
{
for (int i = h; i < n; i++)
{
int k = i - h;
for (int j = i; j >= h && list[j].CompareTo(list[k]) < 0; k -= h)
{
T temp = list[j];
list[j] = list[k];
list[k] = temp;
j = k;
}
}
h >>= 1;
}
}
}
</lang>
{{out}}
<pre>
Line 570 ⟶ 1,470:
Program will sort any array using standard EBCDIC sequence (won't work properly with signed packed variables). In addition to the "usual" array and array lenght parameters, you need to supply an area (initialized to low-values) to detail row-length and up to 10 sort keys defined as follows: start position (1 based), length and sequence (Ascending/Descending).
 
<langsyntaxhighlight lang="cobol"> *******************************************************
IDENTIFICATION DIVISION.
*******************************************************
Line 669 ⟶ 1,569:
IF KEY-RESULT = ' '
MOVE '=' TO KEY-RESULT
END-IF.</langsyntaxhighlight>
 
===Sorting Process===
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 727 ⟶ 1,627:
 
G-999.
EXIT.</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
 
<langsyntaxhighlight lang="lisp">(defun gap-insertion-sort (array predicate gap)
(let ((length (length array)))
(if (< length 2) array
Line 750 ⟶ 1,650:
"Last gap of ~w is not 1." gaps)
(dolist (gap gaps array)
(gap-insertion-sort array predicate gap)))</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio: writeln;
 
void shellSort(T)(T[] seq) pure nothrow {
Line 773 ⟶ 1,673:
shellSort(data);
writeln(data);
}</langsyntaxhighlight>
{{out}}
<pre>[-5, 2, 4, 7, 8, 22]</pre>
 
=={{header|Dart}}==
 
<syntaxhighlight lang="dart">
void main() {
List<int> a = shellSort([1100, 2, 56, 200, -52, 3, 99, 33, 177, -199]);
print('$a');
}
 
shellSort(List<int> array) {
int n = array.length;
// Start with a big gap, then reduce the gap
for (int gap = n~/2; gap > 0; gap ~/= 2)
{
// Do a gapped insertion sort for this gap size.
// The first gap elements a[0..gap-1] are already
// in gapped order keep adding one more element
// until the entire array is gap sorted
for (int i = gap; i < n; i += 1)
{
// add a[i] to the elements that have been gap
// sorted save a[i] in temp and make a hole at
// position i
int temp = array[i];
// shift earlier gap-sorted elements up until
// the correct location for a[i] is found
int j;
for (j = i; j >= gap && array[j - gap] > temp; j -= gap)
array[j] = array[j - gap];
// put temp (the original a[i]) in its correct
// location
array[j] = temp;
}
}
return array;
}
</syntaxhighlight>
 
{{out}}
<pre>[-199, -52, 2, 3, 33, 56, 99, 177, 200, 1100]</pre>
 
 
=={{header|Delphi}}==
<langsyntaxhighlight lang="delphi">Procedure ShellSort(var buf:Array of Integer);
const
gaps:array[0..7] of Integer = (701, 301, 132, 57, 23, 10, 4, 1);
Line 800 ⟶ 1,744:
end;
end;
end;</langsyntaxhighlight>
 
=={{header|E}}==
Line 806 ⟶ 1,750:
{{trans|Python}}
 
<langsyntaxhighlight lang="e">/** Shell sort (in-place) */
def shellSort(array) {
var inc := array.size() // 2
Line 819 ⟶ 1,763:
inc := if (inc <=> 2) { 1 } else { (inc * 5.0 / 11).floor() }
}
}</langsyntaxhighlight>
 
=={{header|Eiffel}}==
Line 830 ⟶ 1,774:
For a more complete explanation of the Eiffel sort examples, see [[Sorting algorithms/Bubble sort#Eiffel|Bubble sort]].
 
<langsyntaxhighlight lang="eiffel">class
MY_SORTED_SET [G -> COMPARABLE]
inherit
Line 871 ⟶ 1,815:
end
 
end</langsyntaxhighlight>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Sort do
def shell_sort(list) when length(list)<=1, do: list
def shell_sort(list), do: shell_sort(list, div(length(list),2))
Line 910 ⟶ 1,854:
 
list = [0, 14, 11, 8, 13, 15, 5, 7, 16, 17, 1, 6, 12, 2, 10, 4, 19, 9, 18, 3]
IO.inspect Sort.shell_sort(list)</langsyntaxhighlight>
 
{{out}}
Line 918 ⟶ 1,862:
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">function shell_sort(sequence s)
integer gap,j
object temp
Line 941 ⟶ 1,885:
? s
puts(1,"After: ")
? shell_sort(s)</langsyntaxhighlight>
 
{{out}}
Line 950 ⟶ 1,894:
=={{header|Forth}}==
{{works with|GNU Forth}}
<langsyntaxhighlight lang="forth">defer less? ' < is less?
 
: shell { array len -- }
Line 970 ⟶ 1,914:
 
array 10 shell
array 10 cells dump</langsyntaxhighlight>
 
A version without local variables:
<langsyntaxhighlight lang="forth">defer precedes ' < is precedes
 
: (shell) ( a n h -- a n h)
Line 1,000 ⟶ 1,944:
array 10 shell
array 10 cells dump</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">MODULE sort
 
CONTAINS
Line 1,054 ⟶ 1,998:
WRITE (*,*) array
END PROGRAM Shellsort</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
modified bubble sort code
<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 1,110 ⟶ 2,054:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>unsorted 1 -4 -1 7 -6 3 6 -7 -5 2 -2 0 5 4 -3
Line 1,117 ⟶ 2,061:
=={{header|Go}}==
Following WP pseudocode:
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,135 ⟶ 2,079:
}
fmt.Println("after: ", a)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,145 ⟶ 2,089:
Adapted version from [http://en.wikibooks.org/wiki/Algorithm_Implementation/Sorting/Shell_sort#Haskell]
 
<langsyntaxhighlight lang="haskell">import Data.List
 
shellSort xs = foldr (invColumnize (map (foldr insert []))) xs gaps
where gaps = takeWhile (< length xs) $ iterate (succ.(3*)) 1
invColumnize f k = concat. transpose. f. transpose
. takeWhile (not.null). unfoldr (Just. splitAt k)</langsyntaxhighlight>
 
=={{header|IoHaxe}}==
<syntaxhighlight lang="haxe">class ShellSort {
Translated from pseudocode at [[wp:Shell_sort#Shell_sort_algorithm_in_pseudocode|Wikipedia]]
@:generic
<lang io>List do(
public static function sort<T>(arr:Array<T>) {
shellSortInPlace := method(
var h gap := (size / 2) roundarr.length;
while while(gaph > 0,) {
h for(i, gap, size ->>= 1,;
for (i in h...arr.length) {
key := at(i)
var k j := arr[i];
var j = i;
while (j >= h && Reflect.compare(k, arr[j - h]) < 0) {
arr[j] = arr[j - h];
j -= h;
}
arr[j] = k;
}
}
}
}
 
class Main {
while(j >= gap and at(j - gap) > key,
static function main() {
atPut(j, at(j - gap))
var integerArray = [1, 10, 2, 5, -1, 5, -19, 4, 23, j = j - gap0];
var floatArray = [1.0, -3.2, 5.2, 10.8, -5.7, 7.3, )
atPut(j 3.5, 0.0, -4.1, key)-9.5];
var stringArray = ['We', 'hold', 'these', 'truths', 'to',
)
gap = (gap / 2.2) round 'be', 'self-evident', 'that', 'all',
'men', 'are', 'created', 'equal'];
)
Sys.println('Unsorted Integers: ' + integerArray);
self)
ShellSort.sort(integerArray);
)
Sys.println('Sorted Integers: ' + integerArray);
Sys.println('Unsorted Floats: ' + floatArray);
ShellSort.sort(floatArray);
Sys.println('Sorted Floats: ' + floatArray);
Sys.println('Unsorted Strings: ' + stringArray);
ShellSort.sort(stringArray);
Sys.println('Sorted Strings: ' + stringArray);
}
}</syntaxhighlight>
 
{{out}}
l := list(2, 3, 4, 5, 1)
<pre>
l shellSortInPlace println # ==> list(1, 2, 3, 4, 5)</lang>
Unsorted Integers: [1,10,2,5,-1,5,-19,4,23,0]
Sorted Integers: [-19,-1,0,1,2,4,5,5,10,23]
Unsorted Floats: [1,-3.2,5.2,10.8,-5.7,7.3,3.5,0,-4.1,-9.5]
Sorted Floats: [-9.5,-5.7,-4.1,-3.2,0,1,3.5,5.2,7.3,10.8]
Unsorted Strings: [We,hold,these,truths,to,be,self-evident,that,all,men,are,created,equal]
Sorted Strings: [We,all,are,be,created,equal,hold,men,self-evident,that,these,to,truths]
</pre>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">procedure main() #: demonstrate various ways to sort a list and string
demosort(shellsort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty")
end
Line 1,197 ⟶ 2,167:
}
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,208 ⟶ 2,178:
on string : "qwerty"
with op = &null: "eqrtwy" (0 ms)</pre>
 
=={{header|Io}}==
Translated from pseudocode at [[wp:Shell_sort#Shell_sort_algorithm_in_pseudocode|Wikipedia]]
<syntaxhighlight lang="io">List do(
shellSortInPlace := method(
gap := (size / 2) round
while(gap > 0,
for(i, gap, size - 1,
key := at(i)
j := i
 
while(j >= gap and at(j - gap) > key,
atPut(j, at(j - gap))
j = j - gap
)
atPut(j, key)
)
gap = (gap / 2.2) round
)
self)
)
 
l := list(2, 3, 4, 5, 1)
l shellSortInPlace println # ==> list(1, 2, 3, 4, 5)</syntaxhighlight>
 
=={{header|IS-BASIC}}==
<syntaxhighlight lang="is-basic">100 PROGRAM "ShellSrt.bas"
110 RANDOMIZE
120 LET N=20 ! Number of elements
130 NUMERIC ARRAY(1 TO N)
140 CALL INIT(ARRAY)
150 CALL WRITE(ARRAY)
160 CALL SHELLSORT(ARRAY)
170 CALL WRITE(ARRAY)
180 DEF INIT(REF A)
190 FOR I=LBOUND(A) TO UBOUND(A)
200 LET A(I)=RND(N)+1
210 NEXT
220 END DEF
230 DEF WRITE(REF A)
240 FOR I=LBOUND(A) TO UBOUND(A)
250 PRINT A(I);
260 NEXT
270 PRINT
280 END DEF
290 DEF SHELLSORT(REF A)
300 LET D=2^INT(LOG(N)/LOG(2))-1
310 DO
320 LET I=1
330 DO WHILE I<=D AND I+D<=N
340 FOR J=I+D TO N STEP D
350 LET AH=A(J):LET BH=J-D
360 DO WHILE BH>0 AND AH<A(BH)
370 LET A(BH+D)=A(BH):LET BH=BH-D
380 LOOP
390 LET A(BH+D)=AH
400 NEXT
410 LET I=I+1
420 LOOP
430 LET D=INT(D/2)
440 LOOP WHILE D>0
450 END DEF</syntaxhighlight>
 
=={{header|J}}==
Line 1,214 ⟶ 2,246:
 
'''Solution'''
<langsyntaxhighlight lang="j">gaps =: [: }: 1 (1+3*])^:(> {:)^:a:~ #
insert =: (I.~ {. ]) , [ , ] }.~ I.~
gapinss =: #@] {. ,@|:@(] insert//.~ #@] $ i.@[)
shellSort =: [: ; gapinss &.>/@(< ,~ ]&.>@gaps)</langsyntaxhighlight>
 
Example:
 
<langsyntaxhighlight Jlang="j"> shellSort 8 6 4 2 1 3 5 7 9
1 2 3 4 5 6 7 8 9</langsyntaxhighlight>
 
=={{header|Java}}==
Line 1,228 ⟶ 2,260:
 
This method will sort in place. If you want to preserve your unsorted array, use a copy of the array as an argument to this method.
<langsyntaxhighlight lang="java">public static void shell(int[] a) {
int increment = a.length / 2;
while (increment > 0) {
Line 1,246 ⟶ 2,278:
}
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
<langsyntaxhighlight Javascriptlang="javascript">function shellSort (a) {
for (var h = a.length; h > 0; h = parseInt(h / 2)) {
for (var i = h; i < a.length; i++) {
Line 1,266 ⟶ 2,298:
a.push(parseInt(Math.random() * 100));
shellSort(a);
document.write(a.join(" "));</langsyntaxhighlight>
 
=={{header|jq}}==
Line 1,273 ⟶ 2,305:
 
shellSort as defined here can be used to sort an array of arbitrary JSON entities.
<langsyntaxhighlight lang="jq"># The "while" loops are implemented using the following jq function:
 
# As soon as "condition" is true, then emit . and stop:
Line 1,296 ⟶ 2,328:
)
| [(($h+1)*5/11 | floor), .] )
| .[1] ;</langsyntaxhighlight>
'''Example''':
<langsyntaxhighlight lang="jq">([],
[5,null,3,1,2,0,4.4,5]
) | shellSort</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight lang="sh">$ jq -M -c -n -f Shell_sort.jq
[]
[null,0,1,2,3,4.4,5,5]</langsyntaxhighlight>
 
=={{header|Julia}}==
{{trans|Java}}
<langsyntaxhighlight lang="julia"># v0.6
 
function shellsort!(a::Array{Int})::Array{Int}
Line 1,333 ⟶ 2,365:
x = rand(1:10, 10)
@show x shellsort!(x)
@assert issorted(x)</langsyntaxhighlight>
 
{{out}}
Line 1,340 ⟶ 2,372:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.0
 
val gaps = listOf(701, 301, 132, 57, 23, 10, 4, 1) // Marcin Ciura's gap sequence
Line 1,368 ⟶ 2,400:
println(a.joinToString(", "))
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,378 ⟶ 2,410:
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
siz = 100
dim a(siz)
Line 1,409 ⟶ 2,441:
print a(i)
next
</syntaxhighlight>
</lang>
 
=={{header|Lisaac}}==
<langsyntaxhighlight Lisaaclang="lisaac">Section Header
 
+ name := SHELL_SORT;
Line 1,457 ⟶ 2,489:
};
};
);</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function shellsort( a )
local inc = math.ceil( #a / 2 )
while inc > 0 do
Line 1,483 ⟶ 2,515:
for _, i in pairs(a) do
print(i)
end</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
{{trans|BBC BASIC}}
 
We use & for passing by reference. Variables with % are integers, and can be any type, a double by default with no decimals, or Decimal, Currency, Long, Integer, Float. When we change value, using operators ++ -- += -= /= *= the final value round to integer using 0.5 where 1.5 give 2. So A%=1/2 give A%=1 and A%=-1/2 give A%=-1. A%=Int(1/2) give A%=0, A%=Int(-1/2) give A%=-1 (int is same as floor() and there is ceil() too, and there is a Bank() for bank type rounding)
 
For Next in M2000 always execute at least one time the code inside (we can change it using a switch, in M2000 environment, to act as in BASIC). From step get the absolute value, and direction get from starting and ending value. So For i=1 to 0 { } execute two times the block with standard switch "-For" or no execute if switch is "+For".
A For statement can be as in this example or the faster For { } without Next
 
<syntaxhighlight lang="m2000 interpreter">
Module ShellSortExample {
Module shellsort(&a()) {
DEf h%, i%, j%, k, n%
n%=LEN(a())
h% = n%
WHILE h% {
IF h% = 2 THEN {h% = 1 }ELSE h%= h% DIV 2.2
FOR i% = h% TO n% - 1
k = a(i%)
j% = i%
WHILE j% >= h% AND k < a(ABS(j% - h%)) {
a(j%) = a(j% - h%)
j% -= h%
}
a(j%) = k
NEXT i%
}
}
Dim numbers(10)
numbers(0)=4, 65, 2, -31, 0, 99, 2, 83, 782, 1
shellsort &numbers()
Print numbers()
}
ShellSortExample
</syntaxhighlight>
 
=={{header|Maple}}==
<syntaxhighlight lang="text">shellsort := proc(arr)
local n, gap, i, val, j;
n := numelems(arr):
Line 1,505 ⟶ 2,573:
arr := Array([17,3,72,0,36,2,3,8,40,0]);
shellsort(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">shellSort[ lst_ ] := Module[ {list = lst, incr, temp, i, j},
incr = Round[Length[list]/2];
While[incr > 0,
Line 1,525 ⟶ 2,593:
If[incr == 2, incr = 1, incr = Round[incr/2.2]]
]; list
]</langsyntaxhighlight>
 
<pre>shellSort[{2,1,4,6,8}]
Line 1,532 ⟶ 2,600:
=={{header|MATLAB}} / {{header|Octave}}==
This is a translation of the FORTRAN solution into MATLAB.
<langsyntaxhighlight MATLABlang="matlab">function list = shellSort(list)
 
N = numel(list);
Line 1,557 ⟶ 2,625:
end
end %while
end %shellSort</langsyntaxhighlight>
 
Sample Usage:
<langsyntaxhighlight MATLABlang="matlab">>> shellSort([4 3 1 5 6 2])
 
ans =
 
1 2 3 4 5 6</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols binary
 
Line 1,612 ⟶ 2,680:
method isFalse public constant binary returns boolean
return \isTrue
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,635 ⟶ 2,703:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">proc shellSort[T](a: var openarray[T]) =
var h = a.len
while h > 0:
h = h div 2
for i in h .. < a.len:
let k = a[i]
var j = i
Line 1,649 ⟶ 2,717:
var a = @[4, 65, 2, -31, 0, 99, 2, 83, 782]
shellSort a
echo a</langsyntaxhighlight>
 
=={{header|Objeck}}==
{{trans|C sharp}}
<langsyntaxhighlight lang="objeck">
bundle Default {
class ShellSort {
Line 1,688 ⟶ 2,756:
}
}
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
{{trans|C}}
<langsyntaxhighlight lang="ocaml">let shellsort a =
let len = Array.length a in
let incSequence = [| 412771; 165103; 66041; 26417; 10567;
Line 1,712 ⟶ 2,780:
done;
) incSequence;
;;</langsyntaxhighlight>
and the main:
<langsyntaxhighlight lang="ocaml">let () =
let arraysize = 1000 in (* or whatever *)
Random.self_init();
Line 1,723 ⟶ 2,791:
Array.iter (Printf.printf " %d") intArray;
print_newline();
;;</langsyntaxhighlight>
 
=={{header|ooRexx}}==
{{Trans|NetRexx}}
<langsyntaxhighlight ooRexxlang="oorexx">/* Rexx */
-- --- Main --------------------------------------------------------------------
call demo
Line 1,804 ⟶ 2,872:
self~put(item, ix)
return
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,827 ⟶ 2,895:
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">shellSort(v)={
my(inc=#v\2);
while(inc,
Line 1,840 ⟶ 2,908:
);
v
};</langsyntaxhighlight>
 
=={{header|Pascal}}==
 
<langsyntaxhighlight lang="pascal">Const
MaxN = 100; { number of elements (my example is 100) }
Type
Line 1,867 ⟶ 2,935:
End;
End;
</syntaxhighlight>
</lang>
 
=={{header|Perl}}==
 
<langsyntaxhighlight lang="perl">sub shell_sort {
my (@a, $h, $i, $j, $k) = @_;
for ($h = @a; $h = int $h / 2;) {
Line 1,889 ⟶ 2,957:
@a = shell_sort @a;
say "@a";
</syntaxhighlight>
</lang>
 
=={{header|Perl 6}}==
<lang perl6>sub shell_sort ( @a is copy ) {
loop ( my $gap = (@a/2).round; $gap > 0; $gap = ( $gap * 5 / 11 ).round ) {
for $gap .. @a.end -> $i {
my $temp = @a[$i];
 
my $j;
loop ( $j = $i; $j >= $gap; $j -= $gap ) {
my $v = @a[$j - $gap];
last if $v <= $temp;
@a[$j] = $v;
}
 
@a[$j] = $temp;
}
}
return @a;
}
my @data = 22, 7, 2, -5, 8, 4;
say 'input = ' ~ @data;
say 'output = ' ~ @data.&shell_sort;
</lang>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">shell_sort</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">gap</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</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;">2</span><span style="color: #0000FF;">),</span> <span style="color: #000000;">j</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">gap</span><span style="color: #0000FF;">></span><span style="color: #000000;">0</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">gap</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: #008080;">do</span>
<span style="color: #004080;">object</span> <span style="color: #000000;">si</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
<span style="color: #000000;">j</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: #008080;">while</span> <span style="color: #000000;">j</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">1</span> <span style="color: #008080;">and</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;">j</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</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;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</span><span style="color: #0000FF;">]</span>
<span style="color: #000000;">j</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">gap</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">j</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>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000000;">gap</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;">2</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">shell_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}
input = 22 7 2 -5 8 4
output = -5 2 4 7 8 22
</pre>
 
=={{header|Phix}}==
Copy of [[Sorting_algorithms/Shell_sort#Euphoria|Euphoria]]
<lang Phix>function shell_sort(sequence s)
integer gap = floor(length(s)/2), j
object temp
while gap>0 do
for i=gap to length(s) do
temp = s[i]
j = i-gap
while j>=1 and temp<=s[j] do
s[j+gap] = s[j]
j -= gap
end while
s[j+gap] = temp
end for
gap = floor(gap/2)
end while
return s
end function</lang>
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">
function shellSort($arr)
{
Line 1,961 ⟶ 3,008:
return $arr;
}
</syntaxhighlight>
</lang>
 
=={{header|Picat}}==
Using the algorithm from the Wikipedia page, inline sort.
<syntaxhighlight lang="picat">go =>
A = [23, 76, 99, 58, 97, 57, 35, 89, 51, 38, 95, 92, 24, 46, 31, 24, 14, 12, 57, 78],
println(A),
shell_sort(A),
println(A),
nl.
 
% Inline sort
shell_sort(A) =>
Inc = round(A.length/2),
while (Inc > 0)
foreach(I in Inc+1..A.length)
Temp = A[I],
J := I,
while (J > Inc, A[J-Inc] > Temp)
A[J] := A[J-Inc],
J := J - Inc
end,
A[J] := Temp
end,
Inc := round(Inc/2.2)
end.</syntaxhighlight>
 
{{out}}
<pre>[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]</pre>
 
 
=={{header|PicoLisp}}==
<syntaxhighlight lang="picolisp">(de shellSort (A)
(for (Inc (*/ (length A) 2) (gt0 Inc) (*/ Inc 10 22))
(for (I Inc (get A I) (inc I))
(let (Tmp @ J I)
(while (and (>= J Inc) (> (get A (- J Inc)) Tmp))
(set (nth A J) (get A (- J Inc)))
(dec 'J Inc) )
(set (nth A J) Tmp) ) ) )
A )</syntaxhighlight>
{{out}}
<pre>: (shellSort (make (do 9 (link (rand 1 999)))))
-> (1 167 183 282 524 556 638 891 902)
 
: (shellSort (make (do 9 (link (rand 1 999)))))
-> (82 120 160 168 205 226 408 708 719)
 
: (shellSort (make (do 9 (link (rand 1 999)))))
-> (108 212 330 471 667 716 739 769 938)</pre>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
/* Based on Rosetta Fortran */
Shell_Sort: PROCEDURE (A);
Line 1,988 ⟶ 3,085:
END;
END SHELL_SORT;
</syntaxhighlight>
</lang>
 
=={{header|PicoLisp}}==
<lang PicoLisp>(de shellSort (A)
(for (Inc (*/ (length A) 2) (gt0 Inc) (*/ Inc 10 22))
(for (I Inc (get A I) (inc I))
(let (Tmp @ J I)
(while (and (>= J Inc) (> (get A (- J Inc)) Tmp))
(set (nth A J) (get A (- J Inc)))
(dec 'J Inc) )
(set (nth A J) Tmp) ) ) )
A )</lang>
{{out}}
<pre>: (shellSort (make (do 9 (link (rand 1 999)))))
-> (1 167 183 282 524 556 638 891 902)
 
: (shellSort (make (do 9 (link (rand 1 999)))))
-> (82 120 160 168 205 226 408 708 719)
 
: (shellSort (make (do 9 (link (rand 1 999)))))
-> (108 212 330 471 667 716 739 769 938)</pre>
 
=={{header|PowerShell}}==
<langsyntaxhighlight PowerShelllang="powershell">Function ShellSort( [Array] $data )
{
# http://oeis.org/A108870
Line 2,036 ⟶ 3,113:
}
 
$l = 10000; ShellSort( ( 1..$l | ForEach-Object { $Rand = New-Object Random }{ $Rand.Next( 0, $l - 1 ) } ) )</langsyntaxhighlight>
 
=={{header|PureBasic}}==
{{trans|Fortran}}
<langsyntaxhighlight PureBasiclang="purebasic">#STEP=2.2
 
Procedure Shell_sort(Array A(1))
Line 2,061 ⟶ 3,138:
EndIf
Wend
EndProcedure</langsyntaxhighlight>
 
=={{header|Python}}==
Line 2,068 ⟶ 3,145:
This method sorts in place.
If you want to preserve your unsorted list, copy it first.
<syntaxhighlight lang="python">def shell(seq):
<lang python>
 
def shell(seq):
inc = len(seq) // 2
while inc:
for i, el in enumerate(seq[inc:], inc):
while i >= inc and seq[i - inc] > el:
seq[i] = seq[i - inc]
i -= inc
seq[i] = el
inc = 1 if inc == 2 else int(inc * 5.0 // 11)</syntaxhighlight>
 
{{output}}
data = [22, 7, 2, -5, 8, 4]
<pre>
shell(data)
print>>> data #= [-522, 27, 42, 7-5, 8, 224]</lang>
>>> shell(data)
>>> print(data)
[-5, 2, 4, 7, 8, 22]
</pre>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(define (shell-sort! xs)
Line 2,100 ⟶ 3,179:
(loop (new Δ))))
xs)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>sub shell_sort ( @a is copy ) {
loop ( my $gap = (@a/2).round; $gap > 0; $gap = ( $gap * 5 / 11 ).round ) {
for $gap .. @a.end -> $i {
my $temp = @a[$i];
 
my $j;
loop ( $j = $i; $j >= $gap; $j -= $gap ) {
my $v = @a[$j - $gap];
last if $v <= $temp;
@a[$j] = $v;
}
 
@a[$j] = $temp;
}
}
return @a;
}
my @data = 22, 7, 2, -5, 8, 4;
say 'input = ' ~ @data;
say 'output = ' ~ @data.&shell_sort;
</syntaxhighlight>
 
{{out}}
<pre>
input = 22 7 2 -5 8 4
output = -5 2 4 7 8 22
</pre>
 
=={{header|REXX}}==
Historical data note: &nbsp; the three-character abbreviations were (and probably still are) the
<br>official three-character abbreviations for the states of the USA before the advent of ZIP codes.
 
<br>'''ZIP''' = '''Z'''one '''I'''mprovement '''P'''lan. &nbsp; &nbsp; Now-a-days, the USA uses two-character abbreviations.
'''ZIP''' = '''Z'''one '''I'''mprovement '''P'''lan. &nbsp; &nbsp; Now-a-days, the USA uses two-character abbreviations.
<lang rexx>/*REXX program sorts a stemmed array using the shell sort (shellsort) algorithm. */
<syntaxhighlight lang="rexx">/*REXX program sorts a stemmed array using the shell sort (shellsort) algorithm. */
call gen /*generate the array elements. */
call show 'before sort' /*display the before array elements. */
say copies('▒', 75) say copies('▒', 75) /*displat a separator line (a fence). */
call shellSort # /*invoke the shell sort. */
call show ' after sort' /*display the after array elements. */
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
gen: @.= /*assign a default value to stem array.*/
@.1= '3 character abbreviations for states of the USA' /*predates ZIP code.*/
@.2= '==============================================='
@.3= 'RHO Rhode Island and Providence Plantations' ; @.36= 'NMX New Mexico'
@.4= 'CAL California' ; @.20=' "NEV Nevada'" ; @.37= 'IND Indiana'
@.5= 'KAN Kansas' ; @.21=' "TEX Texas'" ; @.38= 'MOE Missouri'
@.6= 'MAS Massachusetts' ; @.22=' "VGI Virginia'" ; @.39= 'COL Colorado'
@.7= 'WAS Washington' ; @.23=' "OHI Ohio'" ; @.40= 'CON Connecticut'
@.8= 'HAW Hawaii' ; @.24=' "NHM New Hampshire'"; @.41= 'MON Montana'
@.9= 'NCR North Carolina'; @.25=' "MAE Maine'" ; @.42= 'LOU Louisiana'
@.10= 'SCR South Carolina'; @.26=' "MIC Michigan'" ; @.43= 'IOW Iowa'
@.11= 'IDA Idaho' ; @.27=' "MIN Minnesota'" ; @.44= 'ORE Oregon'
@.12= 'NDK North Dakota' ; @.28=' "MIS Mississippi'" ; @.45= 'ARK Arkansas'
@.13= 'SDK South Dakota' ; @.29=' "WIS Wisconsin'" ; @.46= 'ARZ Arizona'
@.14= 'NEB Nebraska' ; @.30=' "OKA Oklahoma'" ; @.47= 'UTH Utah'
@.15= 'DEL Delaware' ; @.31=' "ALA Alabama'" ; @.48= 'KTY Kentucky'
@.16= 'PEN Pennsylvania' ; @.32=' "FLA Florida'" ; @.49= 'WVG West Virginia'
@.17= 'TEN Tennessee' ; @.33=' "MLD Maryland'" ; @.50= 'NWJ New Jersey'
@.18= 'GEO Georgia' ; @.34=' "ALK Alaska'" ; @.51= 'NYK New York'
@.19= 'VER Vermont' ; @.35=' "ILL Illinois'" ; @.52= 'WYO Wyoming'
do #=1 whileuntil @.#\==''; end; #= #-1 /*determine number of entries in array.*/
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
shellSort: procedure expose @.; parse arg Nn /*obtain the Nn from the argument list*/
i=N%2 n % 2 /*% is integer division in REXX. */
do while i\==0
do j=i+1 to Nn; k= j; p= k - i /*P: previous item*/
_= @.j
do while k>=i+1 & @.p>_; @.k= @.p; k= k-i; p= k-i
end /*while k≥i+1*/
@.k= _
end end /*j*/
if i==2 then i= 1
else i= i * 5 % 11
end /*while i¬==0*/
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
show: do j=1 for #; say 'element' right(j, length(#) ) arg(1)": " @.j; end; return</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the (internal) inputs:}}
<pre style="height:65ex85ex">
element 1 before sort: 3 character abbreviations for states of the USA
element 2 before sort: ===============================================
Line 2,263 ⟶ 3,373:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
aList = [-12, 3, 0, 4, 7, 4, 8, -5, 9]
shellSort(aList)
Line 2,285 ⟶ 3,395:
end
return a
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
Line 2,291 ⟶ 3,401:
 
This method sorts in place. If you want to preserve your unsorted list, copy it first.
<langsyntaxhighlight lang="ruby">class Array
def shellsort!
inc = length / 2
Line 2,311 ⟶ 3,421:
data = [22, 7, 2, -5, 8, 4]
data.shellsort!
p data # [-5, 2, 4, 7, 8, 22]</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
{{works with|QBasic}}
<lang runbasic>siz = 100
<syntaxhighlight lang="runbasic">siz = 100
dim a(siz)
for i = 1 to siz
Line 2,335 ⟶ 3,446:
next i
incr = int(incr / 2.2)
WEND</langsyntaxhighlight>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">
fn shell_sort<T: Ord + Copy>(v: &mut [T]) {
let mut gap = v.len() / 2;
let len = v.len();
while gap > 0 {
for i in gap..len {
let temp = v[i];
let mut j = i;
while j >= gap && v[j - gap] > temp {
v[j] = v[j - gap];
j -= gap;
}
v[j] = temp;
}
gap /= 2;
}
}
 
fn main() {
let mut numbers = [4i32, 65, 2, -31, 0, 99, 2, 83, 782, 1];
println!("Before: {:?}", numbers);
shell_sort(&mut numbers);
println!("After: {:?}", numbers);
}
 
</syntaxhighlight>
{{out}}
<pre>
Before: [4, 65, 2, -31, 0, 99, 2, 83, 782, 1]
After: [-31, 0, 1, 2, 2, 4, 65, 83, 99, 782]
</pre>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">object ShellSort {
def incSeq(len:Int)=new Iterator[Int]{
private[this] var x:Int=len/2
Line 2,364 ⟶ 3,508:
println(a.mkString(","))
}
}</langsyntaxhighlight>
{{out}}
<pre>2,5,3,4,3,9,3,2,5,4,1,3,22,7,2,-5,8,4
Line 2,370 ⟶ 3,514:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">const proc: shellSort (inout array elemType: arr) is func
local
var integer: i is 0;
Line 2,390 ⟶ 3,534:
increment := increment div 2;
end while;
end func;</langsyntaxhighlight>
 
Original source: [http://seed7.sourceforge.net/algorith/sorting.htm#shellSort]
Line 2,396 ⟶ 3,540:
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">func shell_sort(a) {
var h = a.len;
while (h >>= 1) {
Line 2,413 ⟶ 3,557:
say a;
shell_sort(a);
say a;</langsyntaxhighlight>
{{out}}
<pre>[54, 67, 65, 8, 56, 83, 64, 42, 20, 17]
Line 2,420 ⟶ 3,564:
=={{header|Swift}}==
{{works with|Swift|2.1}}
<langsyntaxhighlight lang="swift">func shellsort<T where T : Comparable>(inout seq: [T]) {
var inc = seq.count / 2
while inc > 0 {
Line 2,436 ⟶ 3,580:
}
}
}</langsyntaxhighlight>
 
{{in}}
Line 2,445 ⟶ 3,589:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
 
proc shellsort {m} {
Line 2,465 ⟶ 3,609:
}
 
puts [shellsort {8 6 4 2 1 3 5 7 9}] ;# => 1 2 3 4 5 6 7 8 9</langsyntaxhighlight>
 
=={{header|uBasic/4tH}}==
<syntaxhighlight lang="text">PRINT "Shell sort:"
n = FUNC (_InitArray)
PROC _ShowArray (n)
Line 2,520 ⟶ 3,664:
PRINT
RETURN</langsyntaxhighlight>
 
=={{header|Visual Basic}}==
<syntaxhighlight lang="vb">Sub arrShellSort(ByVal arrData As Variant)
Dim lngHold, lngGap As Long
Dim lngCount, lngMin, lngMax As Long
Dim varItem As Variant
'
lngMin = LBound(arrData)
lngMax = UBound(arrData)
lngGap = lngMin
Do While (lngGap < lngMax)
lngGap = 3 * lngGap + 1
Loop
Do While (lngGap > 1)
lngGap = lngGap \ 3
For lngCount = lngGap + lngMin To lngMax
varItem = arrData(lngCount)
lngHold = lngCount
Do While ((arrData(lngHold - lngGap) > varItem))
arrData(lngHold) = arrData(lngHold - lngGap)
lngHold = lngHold - lngGap
If (lngHold < lngMin + lngGap) Then Exit Do
Loop
arrData(lngHold) = varItem
Next
Loop
arrShellSort = arrData
End Sub'</syntaxhighlight>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">fn shell(mut arr []int, n int) {
mut j := 0
for h := n; h /= 2; {
for i := h; i < n; i++ {
t := arr[i]
for j = i; j >= h && t < arr[j - h]; j -= h {
arr[j] = arr[j - h]
}
arr[j] = t
}
}
}
 
fn main() {
mut arr := [4, 65, 2, -31, 0, 99, 2, 83, 782, 1]
n := arr.len
println('Input: ' + arr.str())
shell(mut arr, n)
println('Output: ' + arr.str())
}</syntaxhighlight>
{{out}}
<pre>Input: [4, 65, 2, -31, 0, 99, 2, 83, 782, 1]
Output: [-31, 0, 1, 2, 2, 4, 65, 83, 99, 782]</pre>
 
=={{header|Whitespace}}==
 
[[/Whitespace|Implementation in Whitespace]].
 
=={{header|Wren}}==
Based on the Wikipedia article pseudo-code.
<syntaxhighlight lang="wren">var shellSort = Fn.new { |a|
var n = a.count
var gaps = [701, 301, 132, 57, 23, 10, 4, 1]
for (gap in gaps) {
if (gap < n) {
for (i in gap...n) {
var t = a[i]
var j = i
while (j >= gap && a[j-gap] > t) {
a[j] = a[j - gap]
j = j - gap
}
a[j] = t
}
}
}
}
 
var array = [ [4, 65, 2, -31, 0, 99, 2, 83, 782, 1], [7, 5, 2, 6, 1, 4, 2, 6, 3] ]
for (a in array) {
System.print("Before: %(a)")
shellSort.call(a)
System.print("After : %(a)")
System.print()
}</syntaxhighlight>
 
{{out}}
<pre>
Before: [4, 65, 2, -31, 0, 99, 2, 83, 782, 1]
After : [-31, 0, 1, 2, 2, 4, 65, 83, 99, 782]
 
Before: [7, 5, 2, 6, 1, 4, 2, 6, 3]
After : [1, 2, 2, 3, 4, 5, 6, 6, 7]
</pre>
<br>
Alternatively we can just call a library method.
{{libheader|Wren-sort}}
<syntaxhighlight lang="wren">import "./sort" for Sort
 
var array = [ [4, 65, 2, -31, 0, 99, 2, 83, 782, 1], [7, 5, 2, 6, 1, 4, 2, 6, 3] ]
for (a in array) {
System.print("Before: %(a)")
Sort.shell(a)
System.print("After : %(a)")
System.print()
}</syntaxhighlight>
 
{{out}}
<pre>
As above.
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">
<lang XPL0>
include c:\cxpl\codes; \intrinsic 'code' declarations
string 0; \use zero-terminated strings
Line 2,563 ⟶ 3,814:
SSort(Str, StrLen(Str));
Text(0, Str); CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
Line 2,569 ⟶ 3,820:
" .Pabcdeefghiiijklmnoooqrstuuvwxyz"
</pre>
 
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">export sub shell_sort(x())
// Shell sort based on insertion sort
 
local gap, i, j, first, last, tempi, tempj
 
last = arraysize(x(),1)
gap = int(last / 10) + 1
while(TRUE)
first = gap + 1
for i = first to last
tempi = x(i)
j = i - gap
while(TRUE)
tempj = x(j)
if tempi >= tempj then
j = j + gap
break
end if
x(j+gap) = tempj
if j <= gap then
break
end if
j = j - gap
wend
x(j) = tempi
next i
if gap = 1 then
return
else
gap = int(gap / 3.5) + 1
end if
wend
end sub
 
if peek$("library") = "main" then
 
clear screen
ITEMS = 100
dim numeros(ITEMS)
for n = 1 to ITEMS
numeros(n) = ran(ITEMS + 1)
next n
print time$
shell_sort(numeros())
print time$
print "Press a key to see ordered numbers."
inkey$
for n = 1 to ITEMS
print numeros(n),", ";
next n
 
end if</syntaxhighlight>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl"> // Shell sort a sequence of objects in place
// Requires mutiable list
fcn shellSort(sequence){
Line 2,589 ⟶ 3,898:
}
return(sequence);
}</langsyntaxhighlight>
 
{{omit from|GUISS}}
9,476

edits