Sorting algorithms/Selection sort: Difference between revisions

m
m (→‎{{header|Wren}}: Minor tidy)
 
(82 intermediate revisions by 46 users not shown)
Line 1:
{{task|Sorting Algorithms}}{{Sorting Algorithm}}
{{Sorting Algorithm}}
[[Category:Sorting]]
 
;Task:
Line 10 ⟶ 12:
 
 
Its asymptotic complexity is &nbsp; <big> [[O]](n<sup>2</sup>) </big> &nbsp; making it inefficient on large arrays.
 
Its primary purpose is for when writing data is very expensive (slow) when compared to reading, eg. writing to flash memory or EEPROM.
Line 17 ⟶ 19:
 
 
;References:
;Reference:
* &nbsp; Rosetta Code: &nbsp; [[O]] &nbsp; &nbsp; (complexity).
* Wikipedia: &nbsp; [[wp:Selection_sort|Selection sort]]
* &nbsp; Wikipedia: &nbsp; [[wp:Selection_sort|Selection sort]].
* &nbsp; Wikipedia: &nbsp; [[https://en.wikipedia.org/wiki/Big_O_notation Big O notation]].
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F selection_sort(&lst)
L(e) lst
V mn = min(L.index .< lst.len, key' x -> @lst[x])
(lst[L.index], lst[mn]) = (lst[mn], e)
 
V arr = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]
selection_sort(&arr)
print(arr)</syntaxhighlight>
 
{{out}}
<pre>
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</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.
<syntaxhighlight lang="360asm">* Selection sort 26/06/2016
<lang 360asm>
* Selection sort 26/06/2016
SELECSRT CSECT
USING SELECSRT,R13 base register
Line 85 ⟶ 105:
RK EQU 8 k
RT EQU 9 temp
END SELECSRT</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 92 ⟶ 111:
</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 selectionSort64.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 selectionSort
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
/******************************************************************/
/* selection sort */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains the first element */
/* x2 contains the number of element */
selectionSort:
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
mov x3,x1 // start index i
sub x7,x2,1 // compute n - 1
1: // start loop
mov x4,x3
add x5,x3,1 // init index 2
2:
ldr x1,[x0,x4,lsl 3] // load value A[mini]
ldr x6,[x0,x5,lsl 3] // load value A[j]
cmp x6,x1 // compare value
csel x4,x5,x4,lt // j -> mini
add x5,x5,1 // increment index j
cmp x5,x2 // end ?
blt 2b // no -> loop
cmp x4,x3 // mini <> j ?
beq 3f // no
ldr x1,[x0,x4,lsl 3] // yes swap A[i] A[mini]
ldr x6,[x0,x3,lsl 3]
str x1,[x0,x3,lsl 3]
str x6,[x0,x4,lsl 3]
3:
add x3,x3,1 // increment i
cmp x3,x7 // end ?
blt 1b // no -> loop
100:
ldp x6,x7,[sp],16 // restaur 2 registers
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* Display table elements */
/******************************************************************/
/* x0 contains the address of table */
displayTable:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
mov x2,x0 // table address
mov x3,0
1: // loop display table
ldr x0,[x2,x3,lsl 3]
ldr x1,qAdrsZoneConv
bl conversion10 // décimal conversion
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConv
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 SelectionSort(INT ARRAY a INT size)
INT i,j,minpos,tmp
 
FOR i=0 TO size-2
DO
minpos=i
FOR j=i+1 TO size-1
DO
IF a(minpos)>a(j) THEN
minpos=j
FI
OD
IF minpos#i THEN
tmp=a(i)
a(i)=a(minpos)
a(minpos)=tmp
FI
OD
RETURN
 
PROC Test(INT ARRAY a INT size)
PrintE("Array before sort:")
PrintArray(a,size)
SelectionSort(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/Selection_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 selectionSort(input: Array):Array {
//find the i'th element
for (var i:uint = 0; i < input.length; i++) {
Line 111 ⟶ 379:
}
return input;
}</langsyntaxhighlight>
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
 
procedure Test_Selection_Sort is
Line 144 ⟶ 412:
Put (Integer'Image (A (I)) & " ");
end loop;
end Test_Selection_Sort;</langsyntaxhighlight>
{{out}}
<pre>
Line 156 ⟶ 424:
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386}}
<langsyntaxhighlight lang="algol68">MODE DATA = REF CHAR;
 
PROC in place selection sort = (REF[]DATA a)VOID:
Line 181 ⟶ 449:
in place selection sort(ref data);
FOR i TO UPB ref data DO print(ref data[i]) OD; print(new line);
print((data))</langsyntaxhighlight>
{{out}}
<pre>
Line 187 ⟶ 455:
big fjords vex quick waltz nymph
</pre>
 
=={{header|AppleScript}}==
<syntaxhighlight lang="applescript">on selectionSort(theList, l, r) -- Sort items l thru r of theList in place.
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}
script o
property lst : theList
end script
repeat with i from l to (r - 1)
set iVal to o's lst's item i
set minVal to iVal
set minPos to i
repeat with j from (i + 1) to r
set jVal to o's lst's item j
if (minVal > jVal) then
set minVal to jVal
set minPos to j
end if
end repeat
set o's lst's item minPos to iVal
set o's lst's item i to minVal
end repeat
return -- nothing.
end selectionSort
property sort : selectionSort
 
on demo()
set theList to {988, 906, 151, 71, 712, 177, 945, 558, 31, 627}
sort(theList, 1, -1)
return theList
end demo
 
demo()</syntaxhighlight>
 
{{output}}
<syntaxhighlight lang="applescript">{31, 71, 151, 177, 558, 627, 712, 906, 945, 988}</syntaxhighlight>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program selectionSort.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
mov r2,#NBELEMENTS @ number of élements
bl selectionSort
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
/******************************************************************/
/* selection sort */
/******************************************************************/
/* r0 contains the address of table */
/* r1 contains the first element */
/* r2 contains the number of element */
selectionSort:
push {r1-r7,lr} @ save registers
mov r3,r1 @ start index i
sub r7,r2,#1 @ compute n - 1
1: @ start loop
mov r4,r3
add r5,r3,#1 @ init index 2
2:
ldr r1,[r0,r4,lsl #2] @ load value A[mini]
ldr r6,[r0,r5,lsl #2] @ load value A[j]
cmp r6,r1 @ compare value
movlt r4,r5 @ j -> mini
add r5,#1 @ increment index j
cmp r5,r2 @ end ?
blt 2b @ no -> loop
cmp r4,r3 @ mini <> j ?
beq 3f @ no
ldr r1,[r0,r4,lsl #2] @ yes swap A[i] A[mini]
ldr r6,[r0,r3,lsl #2]
str r1,[r0,r3,lsl #2]
str r6,[r0,r4,lsl #2]
3:
add r3,#1 @ increment i
cmp r3,r7 @ end ?
blt 1b @ no -> loop
 
100:
pop {r1-r7,lr}
bx lr @ return
 
/******************************************************************/
/* Display table elements */
/******************************************************************/
/* r0 contains the address of table */
displayTable:
push {r0-r3,lr} @ save registers
mov r2,r0 @ table address
mov r3,#0
1: @ loop display table
ldr r0,[r2,r3,lsl #2]
ldr r1,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">selectionSort: function [items][
sorted: new []
tmp: new items
while [not? empty? tmp][
minIndex: index tmp min tmp
'sorted ++ tmp\[minIndex]
remove 'tmp .index minIndex
]
return sorted
]
 
print selectionSort [3 1 2 8 5 7 9 4 6]</syntaxhighlight>
 
{{out}}
 
<pre>1 2 3 4 5 6 7 8 9</pre>
 
=={{header|AutoHotkey}}==
ahk forum: [http://www.autohotkey.com/forum/topic44657-105.html discussion]
<langsyntaxhighlight AutoHotkeylang="autohotkey">MsgBox % SelecSort("")
MsgBox % SelecSort("xxx")
MsgBox % SelecSort("3,2,1")
Line 210 ⟶ 773:
sorted .= "," . a%A_Index%
Return SubStr(sorted,2) ; drop leading comma
}</syntaxhighlight>
}</lang>
 
=={{header|AWK}}==
<langsyntaxhighlight lang="awk">function getminindex(gl, gi, gs)
{
min = gl[gi]
Line 240 ⟶ 803:
print line[i]
}
}</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight BBCBASIClang="bbcbasic">DEF PROC_SelectionSort(Size%)
FOR I% = 1 TO Size%-1
lowest% = I%
Line 251 ⟶ 814:
IF I%<>lowest% SWAP data%(I%),data%(lowest%)
NEXT I%
ENDPROC</langsyntaxhighlight>
 
=={{header|BASIC}}==
==={{header|GWBASIC}}===
Works with: QBASIC, QuickBASIC, VB-DOS
<syntaxhighlight lang="gwbasic">
10 'SAVE"SELSORT",A
20 ' Selection Sort Algorithm
30 '
40 ' VAR
50 DEFINT A-Z
60 OPTION BASE 1
70 I=0: J=0: IMINV = 0: IMAX = 0: TP! = 0: TL! = 0
80 '
90 CLS
100 PRINT "This program does the Selection Sort Algorithm"
110 INPUT "Number of elements to sort (Max=1000, Enter=10)";IMAX
120 IF IMAX = 0 THEN IMAX = 10
130 IF IMAX > 1000 THEN IMAX = 1000
140 DIM N(IMAX)
150 ' Creates and shows the unsorted list
160 RANDOMIZE TIMER
170 FOR I=1 TO IMAX: N(I) = I: NEXT I
180 FOR I=1 TO IMAX
190 J = INT(RND*IMAX)+1
200 SWAP N(I), N(J)
210 NEXT I
220 PRINT: PRINT "Unsorted list:";
230 FOR I=1 TO IMAX: PRINT N(I);: NEXT I
240 PRINT: PRINT
250 ' Sorts the list through the Selection Sort Algorithm and shows the results
260 TL! = TIMER
270 PRINT "Sorting"; IMAX; "numbers";
280 COLOR 7+16: X = POS(0): PRINT"...";: COLOR 7
290 ITP = 0
300 FOR I=1 TO IMAX-1
310 IMINV = I
320 FOR J=I+1 TO IMAX
330 IF N(IMINV)>N(J) THEN IMINV = J
340 NEXT J
350 IF IMINV>I THEN SWAP N(IMINV), N(I): TP! = TP! + 1
360 NEXT I
370 LOCATE ,X: PRINT ". Done!"
380 PRINT: PRINT "Sorted list:";
390 FOR I=1 TO IMAX: PRINT N(I);: NEXT I
400 ' Final results
410 PRINT: PRINT: PRINT "Numbers sorted:"; IMAX
420 PRINT "Total permutations done:";TP!
430 PRINT "Time lapse:"; TIMER-TL!; "seconds."
440 PRINT
450 PRINT "End of program"
460 END
</syntaxhighlight>
 
==={{header|IS-BASIC}}===
<syntaxhighlight lang="is-basic">100 PROGRAM "SelecSrt.bas"
110 RANDOMIZE
120 NUMERIC ARRAY(-5 TO 14)
130 CALL INIT(ARRAY)
140 CALL WRITE(ARRAY)
150 CALL SELECTIONSORT(ARRAY)
160 CALL WRITE(ARRAY)
170 DEF INIT(REF A)
180 FOR I=LBOUND(A) TO UBOUND(A)
190 LET A(I)=RND(98)+1
200 NEXT
210 END DEF
220 DEF WRITE(REF A)
230 FOR I=LBOUND(A) TO UBOUND(A)
240 PRINT A(I);
250 NEXT
260 PRINT
270 END DEF
280 DEF SELECTIONSORT(REF A)
290 FOR I=LBOUND(A) TO UBOUND(A)-1
300 LET MN=A(I):LET INDEX=I
310 FOR J=I+1 TO UBOUND(A)
320 IF MN>A(J) THEN LET MN=A(J):LET INDEX=J
330 NEXT
340 LET A(INDEX)=A(I):LET A(I)=MN
350 NEXT
360 END DEF</syntaxhighlight>
 
=={{header|BCPL}}==
<syntaxhighlight lang="bcpl">get "libhdr"
 
let selectionsort(A, len) be if len > 1
$( let minloc = A and t = ?
for i=0 to len-1
if !minloc > A!i do minloc := A+i
t := !A
!A := !minloc
!minloc := t
selectionsort(A+1, len-1)
$)
 
let writearray(A, len) be
for i=0 to len-1 do
writed(A!i, 6)
 
let start() be
$( let array = table 52, -5, -20, 199, 65, -3, 190, 25, 9999, -5342
let length = 10
writes("Input: ") ; writearray(array, length) ; wrch('*N')
selectionsort(array, length)
writes("Output: ") ; writearray(array, length) ; wrch('*N')
$)</syntaxhighlight>
{{out}}
<pre>Input: 52 -5 -20 199 65 -3 190 25 9999 -5342
Output: -5342 -20 -5 -3 25 52 65 190 199 9999</pre>
 
=={{header|C}}==
 
<langsyntaxhighlight lang="c">#include <stdio.h>
 
void selection_sort (int *a, int n) {
Line 282 ⟶ 955:
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++}}==
Uses C++11. Compile with
g++ -std=c++11 selection.cpp
<lang cpp>#include <algorithm>
#include <iterator>
#include <iostream>
 
template<typename ForwardIterator> void selection_sort(ForwardIterator begin,
ForwardIterator end) {
for(auto i = begin; i != end; ++i) {
std::iter_swap(i, std::min_element(i, end));
}
}
 
int main() {
int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};
selection_sort(std::begin(a), std::end(a));
copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
}</lang>
{{out}}
<pre>
-199 -52 2 3 33 56 99 100 177 200
</pre>
 
Line 317 ⟶ 965:
This is a generic implementation that works with any type that implements the IComparable interface
 
<langsyntaxhighlight lang="csharp">class SelectionSort<T> where T : IComparable {
public T[] Sort(T[] list) {
int k;
Line 336 ⟶ 984:
return list;
}
}</langsyntaxhighlight>
 
Example of usage:
<langsyntaxhighlight lang="csharp">String[] str = { "this", "is", "a", "test", "of", "generic", "selection", "sort" };
 
SelectionSort<String> mySort = new SelectionSort<string>();
Line 347 ⟶ 995:
for (int i = 0; i < result.Length; i++) {
Console.WriteLine(result[i]);
}</langsyntaxhighlight>
 
{{out}}
Line 358 ⟶ 1,006:
test
this</pre>
 
=={{header|C++}}==
Uses C++11. Compile with
g++ -std=c++11 selection.cpp
<syntaxhighlight lang="cpp">#include <algorithm>
#include <iterator>
#include <iostream>
 
template<typename ForwardIterator> void selection_sort(ForwardIterator begin,
ForwardIterator end) {
for(auto i = begin; i != end; ++i) {
std::iter_swap(i, std::min_element(i, end));
}
}
 
int main() {
int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199};
selection_sort(std::begin(a), std::end(a));
copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
}</syntaxhighlight>
{{out}}
<pre>
-199 -52 2 3 33 56 99 100 177 200
</pre>
 
=={{header|Clojure}}==
This is an implementation that mutates a Java arraylist in place.
<langsyntaxhighlight lang="lisp">(import 'java.util.ArrayList)
 
(defn arr-swap! [#^ArrayList arr i j]
Line 383 ⟶ 1,056:
(doseq [start-i (range (dec n))]
(move-min! start-i))
arr))))</langsyntaxhighlight>
 
=={{header|COBOL}}==
<langsyntaxhighlight COBOLlang="cobol"> PERFORM E-SELECTION VARYING WB-IX-1 FROM 1 BY 1
UNTIL WB-IX-1 = WC-SIZE.
 
Line 413 ⟶ 1,086:
 
F-999.
EXIT.</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
 
<langsyntaxhighlight lang="lisp">(defun selection-sort-vector (array predicate)
(do ((length (length array))
(i 0 (1+ i)))
Line 453 ⟶ 1,126:
(etypecase sequence
(list (selection-sort-list sequence predicate))
(vector (selection-sort-vector sequence predicate))))</langsyntaxhighlight>
 
Example use:
Line 462 ⟶ 1,135:
> (selection-sort (vector 8 7 4 3 2 0 9 1 5 6) '>)
#(9 8 7 6 5 4 3 2 1 0)</pre>
 
=={{header|Crystal}}==
This sorts the array in-place.
<syntaxhighlight lang="crystal">def selectionSort(array : Array)
(0...array.size-1).each do |i|
nextMinIndex = i
(i+1...array.size).each do |j|
if array[j] < array[nextMinIndex]
nextMinIndex = j
end
end
if i != nextMinIndex
array.swap(i, nextMinIndex)
end
end
end</syntaxhighlight>
 
=={{header|D}}==
The actual function is very short.
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.array, std.traits;
 
enum AreSortableArrayItems(T) = isMutable!T &&
Line 525 ⟶ 1,214:
a.selectionSort;
a.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>[1, 1, 2, 2, 3, 3, 3, 4, 5, 5, 5, 6, 7, 8, 9, 9, 9]</pre>
 
=={{header|Dart}}==
{{trans | Java}}
 
<syntaxhighlight lang="dart">
void main() {
List<int> a = selectionSort([1100, 2, 56, 200, -52, 3, 99, 33, 177, -199]);
print('$a');
}
 
selectionSort(List<int> array){
for(int currentPlace = 0;currentPlace<array.length-1;currentPlace++){
int smallest = 4294967296; //maxInt
int smallestAt = currentPlace+1;
for(int check = currentPlace; check<array.length;check++){
if(array[check]<smallest){
smallestAt = check;
smallest = array[check];
}
}
int temp = array[currentPlace];
array[currentPlace] = array[smallestAt];
array[smallestAt] = temp;
}
return array;
}
</syntaxhighlight>
 
{{out}}
<pre> unsorted array: [1100, 2, 56, 200, -52, 3, 99, 33, 177, -199]
a sorted: [-199, -52, 2, 3, 33, 56, 99, 177, 200, 1100] </pre>
 
=={{header|Delphi}}==
Line 535 ⟶ 1,255:
 
Static array is an arbitrary-based array of fixed length
<langsyntaxhighlight Delphilang="delphi">program TestSelectionSort;
 
{$APPTYPE CONSOLE}
Line 583 ⟶ 1,303:
Writeln;
Readln;
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 592 ⟶ 1,312:
===String sort===
// string is 1-based variable-length array of Char
<langsyntaxhighlight Delphilang="delphi">procedure SelectionSort(var S: string);
var
Lowest: Char;
Line 607 ⟶ 1,327:
S[I]:= Lowest;
end;
end;</langsyntaxhighlight>
<pre>
// in : S = 'the quick brown fox jumps over the lazy dog'
Line 615 ⟶ 1,335:
=={{header|E}}==
 
<langsyntaxhighlight lang="e">def selectionSort := {
def cswap(c, a, b) {
def t := c[a]
Line 642 ⟶ 1,362:
}
}
}</langsyntaxhighlight>
 
=={{header|EasyLang}}==
 
<syntaxhighlight lang="text">
proc sort . d[] .
for i = 1 to len d[] - 1
for j = i + 1 to len d[]
if d[j] < d[i]
swap d[j] d[i]
.
.
.
.
data[] = [ 29 4 72 44 55 26 27 77 92 5 ]
sort data[]
print data[]
</syntaxhighlight>
 
=={{header|EchoLisp}}==
===List sort===
<langsyntaxhighlight lang="scheme">
;; recursive version (adapted from Racket)
(lib 'list) ;; list-delete
Line 666 ⟶ 1,403:
→ (0 1 2 3 4 5 6 7 8 9 10 11 12)
</syntaxhighlight>
</lang>
===Array sort===
<langsyntaxhighlight lang="scheme">
;; sort an array in place
(define (sel-sort a (amin) (imin))
Line 682 ⟶ 1,419:
(sel-sort a)
→ #( 2 3 4 5 6 8 9)
</syntaxhighlight>
</lang>
 
 
=={{header|Eiffel}}==
 
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
SELECTION_SORT [G -> COMPARABLE]
Line 771 ⟶ 1,507:
 
end
</syntaxhighlight>
</lang>
Test:
<langsyntaxhighlight lang="eiffel">
class
APPLICATION
Line 806 ⟶ 1,542:
 
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Unsorted: 1 27 32 99 1 -7 3 5 7
Sorted: -7 1 1 3 5 7 27 32 99
</pre>
 
=={{header|Elena}}==
ELENA 6.x :
<syntaxhighlight lang="elena">import extensions;
import system'routines;
extension op
{
selectionSort()
{
var copy := self.clone();
for(int i := 0; i < copy.Length; i += 1)
{
int k := i;
for(int j := i + 1; j < copy.Length; j += 1)
{
if (copy[j] < copy[k])
{
k := j
}
};
copy.exchange(i,k)
};
^ copy
}
}
public program()
{
var list := new string[]{"this", "is", "a", "test", "of", "generic", "selection", "sort"};
console.printLine("before:",list.asEnumerable());
console.printLine("after:",list.selectionSort().asEnumerable())
}</syntaxhighlight>
{{out}}
<pre>
before:this,is,a,test,of,generic,selection,sort
after:a,generic,is,of,selection,sort,test,this
</pre>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Sort do
def selection_sort(list) when is_list(list), do: selection_sort(list, [])
Line 822 ⟶ 1,599:
selection_sort(List.delete(list, max), [max | sorted])
end
end</langsyntaxhighlight>
 
Example:
Line 829 ⟶ 1,606:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
</pre>
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
-module(solution).
-import(lists,[delete/2,max/1]).
-compile(export_all).
selection_sort([],Sort)-> Sort;
selection_sort(Ar,Sort)->
M=max(Ar),
Ad=delete(M,Ar),
selection_sort(Ad,[M|Sort]).
print_array([])->ok;
print_array([H|T])->
io:format("~p~n",[H]),
print_array(T).
 
main()->
Ans=selection_sort([1,5,7,8,4,10],[]),
print_array(Ans).
</syntaxhighlight>
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">function selection_sort(sequence s)
object tmp
integer m
Line 854 ⟶ 1,651:
pretty_print(1,s,{2})
puts(1,"\nAfter: ")
pretty_print(1,selection_sort(s),{2})</langsyntaxhighlight>
 
{{out}}
Line 891 ⟶ 1,688:
 
=={{header|F Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
let rec ssort = function
[] -> []
| x::xs ->
let min, rest =
List.fold_leftfold (fun (min,acc) x ->
if hx<min then (hx, min::acc)
else (min, hx::acc))
(x, []) xs
in min::ssort rest
</syntaxhighlight>
</lang>
 
=={{header|Factor}}==
<syntaxhighlight lang="factor">USING: kernel math sequences sequences.extras ;
 
: select ( m n seq -- )
[ dup ] 2dip [ <slice> [ ] infimum-by* drop over + ]
[ exchange ] bi ;
 
: selection-sort! ( seq -- seq' )
[ ] [ length dup ] [ ] tri [ select ] 2curry each-integer ;</syntaxhighlight>
Example use
<syntaxhighlight lang="factor">IN: scratchpad { 5 -6 3 9 -2 4 -1 -6 5 -5 } selection-sort!
 
--- Data stack:
{ -6 -6 -5 -2 -1 3 4 5 5 9 }</syntaxhighlight>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">defer less? ' < is less?
 
: least ( start end -- least )
Line 920 ⟶ 1,732:
array 10 selection
array 10 cells dump</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|95 and later}}
<langsyntaxhighlight lang="fortran">PROGRAM SELECTION
 
IMPLICIT NONE
Line 950 ⟶ 1,762:
END SUBROUTINE Selection_sort
 
END PROGRAM SELECTION</langsyntaxhighlight>
{{out}}
<pre>
Unsorted array: 4 9 3 -2 0 7 -5 1 6 8
Sorted array : -5 -2 0 1 3 4 6 7 8 9
</pre>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' version 03-12-2016
' compile with: fbc -s console
' for boundry checks on array's compile with: fbc -s console -exx
 
Sub selectionsort(arr() As Long)
 
' sort from lower bound to the highter bound
' array's can have subscript range from -2147483648 to +2147483647
 
Dim As Long i, j, x
Dim As Long lb = LBound(arr)
Dim As Long ub = UBound(arr)
 
For i = lb To ub -1
x = i
For j = i +1 To ub
If arr(j) < arr(x) Then x = j
Next
If x <> i Then
Swap arr(i), arr(x)
End If
Next
 
End Sub
 
' ------=< MAIN >=------
 
Dim As Long i, array(-7 To 7)
Dim As Long a = LBound(array), b = UBound(array)
 
Randomize Timer
For i = a To b : array(i) = i : Next
For i = a To b ' little shuffle
Swap array(i), array(Int(Rnd * (b - a +1)) + a)
Next
 
Print "unsort ";
For i = a To b : Print Using "####"; array(i); : Next : Print
selectionsort(array()) ' sort the array
Print " sort ";
For i = a To b : Print Using "####"; array(i); : Next : Print
 
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End</syntaxhighlight>
{{out}}
<pre>unsort 1 -7 -5 -4 6 5 -3 4 2 0 3 -6 -2 7 -1
sort -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7</pre>
 
=={{header|Gambas}}==
<syntaxhighlight lang="gambas">
siLow As Short = -99 'Set the lowest value number to create
siHigh As Short = 99 'Set the highest value number to create
siQty As Short = 20 'Set the quantity of numbers to create
 
Public Sub Main()
Dim siToSort As Short[] = CreateNumbersToSort()
Dim siPos, siLow, siChar, siCount As Short
 
PrintOut("To sort: ", siToSort)
 
For siCount = 0 To siToSort.Max
siChar = siCount
For siPos = siCount + 1 To siToSort.Max
If siToSort[siChar] > siToSort[siPos] Then siChar = siPos
Next
siLow = siToSort[siChar]
siToSort.Delete(siChar, 1)
siToSort.Add(siLow, siCount)
Next
 
PrintOut(" Sorted: ", siToSort)
 
End
'---------------------------------------------------------
Public Sub PrintOut(sText As String, siToSort As String[])
Dim siCount As Short
 
Print sText;
 
For siCount = 0 To siToSort.Max
Print siToSort[siCount];
If siCount <> siToSort.max Then Print ", ";
Next
 
Print
 
End
'---------------------------------------------------------
Public Sub CreateNumbersToSort() As Short[]
Dim siCount As Short
Dim siList As New Short[]
 
For siCount = 0 To siQty
siList.Add(Rand(siLow, siHigh))
Next
 
Return siList
 
End</syntaxhighlight>
 
Output:
<pre>
To sort: -11, -64, -20, -84, 94, -60, -82, -82, 37, -30, -75, 73, 19, -97, 81, -26, 55, 8, -15, -31, 36
Sorted: -97, -84, -82, -82, -75, -64, -60, -31, -30, -26, -20, -15, -11, 8, 19, 36, 37, 55, 73, 81, 94
</pre>
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap">SelectionSort := function(v)
local i, j, k, n, m;
n := Size(v);
Line 977 ⟶ 1,899:
v := List([1 .. 100], n -> Random([1 .. 100]));
SelectionSort(v);
v;</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,005 ⟶ 1,927:
a[i], a[iMin] = aMin, a[i]
}
}</langsyntaxhighlight>
 
More generic version that sorts anything that implements <code>sort.Interface</code>:
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,034 ⟶ 1,956:
a.Swap(i, iMin)
}
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
<syntaxhighlight lang ="haskell">selSortimport ::Data.List (Ord adelete) => [a] -> [a]
 
selSort :: (Ord a) => [a] -> [a]
selSort [] = []
selSort xs = let x = maximum xs in selSort (removedelete x xs) ++ [x]
where removex _= [] =maximum []xs</syntaxhighlight>
remove a (x:xs)
| x == a = xs
| otherwise = x : remove a xs
</lang>
 
=={{header|Haxe}}==
<syntaxhighlight lang="haxe">class SelectionSort {
<lang haxe>static function selectionSort(arr:Array<Int>) {
@:generic
var len = arr.length;
public static function sort<T>(arr:Array<T>) {
for (index in 0...len)
var len = arr.length;
{
for (index in 0...len) {
var minIndex = index;
var minIndex = index;
for (remainingIndex in (index+1)...len)
for (remainingIndex in (index+1)...len) {
{
if (Reflect.compare(arr[minIndex] >, arr[remainingIndex]) {> 0)
minIndex = remainingIndex;
}
}
if (index != minIndex) {
}
var temp = arr[index];
if (index != minIndex) {
var temp = arr[index] = arr[minIndex];
arr[index] = arr[minIndex] = temp;
}
arr[minIndex] = temp;
}
}
}
}
}</lang>
 
class Main {
=={{header|Io}}==
static function main() {
<lang io>List do (
var integerArray = [1, 10, 2, 5, -1, 5, -19, 4, 23, 0];
selectionSortInPlace := method(
var floatArray = [1.0, -3.2, 5.2, 10.8, -5.7, 7.3,
size repeat(idx,
swapIndices(idx 3.5, indexOf(slice(idx0.0, size)-4.1, min))-9.5];
var stringArray = ['We', 'hold', 'these', 'truths', 'to',
)
'be', 'self-evident', 'that', 'all',
)
'men', 'are', 'created', 'equal'];
)
Sys.println('Unsorted Integers:' + integerArray);
SelectionSort.sort(integerArray);
Sys.println('Sorted Integers: ' + integerArray);
Sys.println('Unsorted Floats: ' + floatArray);
SelectionSort.sort(floatArray);
Sys.println('Sorted Floats: ' + floatArray);
Sys.println('Unsorted Strings: ' + stringArray);
SelectionSort.sort(stringArray);
Sys.println('Sorted Strings: ' + stringArray);
}
}</syntaxhighlight>
 
{{out}}
l := list(-1, 4, 2, -9)
<pre>
l selectionSortInPlace println # ==> list(-9, -1, 2, 4)</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(selectionsort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty")
end
Line 1,095 ⟶ 2,033:
}
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,106 ⟶ 2,044:
on string : "qwerty"
with op = &null: "eqrtwy" (0 ms)</pre>
 
=={{header|Io}}==
<syntaxhighlight lang="io">List do (
selectionSortInPlace := method(
size repeat(idx,
swapIndices(idx, indexOf(slice(idx, size) min))
)
)
)
 
l := list(-1, 4, 2, -9)
l selectionSortInPlace println # ==> list(-9, -1, 2, 4)</syntaxhighlight>
 
=={{header|J}}==
{{eff note|J|/:~}}
Create the following script and load it to a J session.
<langsyntaxhighlight lang="j">selectionSort=: verb define
data=. y
for_xyz. y do.
Line 1,118 ⟶ 2,068:
end.
data
)</langsyntaxhighlight>
 
In an email discussion, Roger_Hui presented the following tacit code:
<langsyntaxhighlight lang="j">ix=: C.~ <@~.@(0, (i. <./))
ss1=: ({. , $:@}.)@ix^:(*@#)</langsyntaxhighlight>
 
To validate:
<langsyntaxhighlight lang="j"> [data=. 6 15 19 12 14 19 0 17 0 14
6 15 19 12 14 19 0 17 0 14
selectionSort data
0 0 6 12 14 14 15 17 19 19
ss1 data
0 0 6 12 14 14 15 17 19 19</langsyntaxhighlight>
 
=={{header|Java}}==
This algorithm sorts in place. The call <tt>sort(array)</tt> will rearrange the array and not create a new one.
<langsyntaxhighlight lang="java">public static void sort(int[] nums){
for(int currentPlace = 0;currentPlace<nums.length-1;currentPlace++){
int smallest = Integer.MAX_VALUE;
Line 1,148 ⟶ 2,098:
nums[smallestAt] = temp;
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
This algorithm sorts array of numbers.
<langsyntaxhighlight lang="javascript">function selectionSort(nums) {
var len = nums.length;
for(var i = 0; i < len; i++) {
Line 1,168 ⟶ 2,118:
}
return nums;
}</langsyntaxhighlight>
 
=={{header|jq}}==
The following implementation does not impose any restrictions on the types of entities that may appear in the array to be sorted. That is, the array may include any collection of JSON entities.
 
The definition also illustrates the use of an inner function (swap), and the use of jq's reduction operator, <tt>reduce</tt>.<langsyntaxhighlight lang="jq"># Sort any array
def selection_sort:
def swap(i;j): if i == j then . else .[i] as $tmp | .[i] = .[j] | .[j] = $tmp end;
Line 1,190 ⟶ 2,140:
)) as $ans
| swap( $currentPlace; $ans[0] )
) ;</langsyntaxhighlight>Example:<syntaxhighlight lang ="jq">
[1, 3.3, null, 2, null, [1,{"a":1 }] ] | selection_sort
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,209 ⟶ 2,159:
]
</pre>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
Because this sort is liable to be used only when memory writes come at a high cost, I've implemented it as an in-place sort. By convention, Julia functions that alter their inputs have names ending in !, so this function is called <code>selectionsort!</code>.
 
<lang Julia>
<syntaxhighlight lang="julia">function selectionsort!{T<:Real}(aarr::ArrayVector{T,1<:Real})
len = length(aarr)
if len < 2 return arr end
return nothing
end
for i in 1:len-1
(lmin, j) = findmin(aarr[i+1:end])
if lmin < aarr[i]
aarr[i+j] = aarr[i]
aarr[i] = lmin
end
end
return nothingarr
end
 
av = [rand(-10010:10010, 10) for i in 1:20]
println("# unordered: $v\n -> ordered: ", selectionsort!(v))</syntaxhighlight>
println("Before Sort:")
println(a)
selectionsort!(a)
println("\nAfter Sort:")
println(a)
</lang>
 
{{out}}
<pre># unordered: [2, -10, 0, -10, -9, -3, -3, 7, 8, -3]
<pre>
-> ordered: [-10, -10, -9, -3, -3, -3, 0, 2, 7, 8]</pre>
Before Sort:
[-15,-35,51,21,-11,12,-39,21,44,70,-16,85,55,-28,-52,83,-12,-20,37,-57]
 
=={{header|Kotlin}}==
After Sort:
{{trans|C#}}
[-57,-52,-39,-35,-28,-20,-16,-15,-12,-11,12,21,21,37,44,51,55,70,83,85]
<syntaxhighlight lang="scala">fun <T : Comparable<T>> Array<T>.selection_sort() {
</pre>
for (i in 0..size - 2) {
var k = i
for (j in i + 1..size - 1)
if (this[j] < this[k])
k = j
 
if (k != i) {
val tmp = this[i]
this[i] = this[k]
this[k] = tmp
}
}
}
 
fun main(args: Array<String>) {
val i = arrayOf(4, 9, 3, -2, 0, 7, -5, 1, 6, 8)
i.selection_sort()
println(i.joinToString())
 
val s = Array(i.size, { -i[it].toShort() })
s.selection_sort()
println(s.joinToString())
 
val c = arrayOf('z', 'h', 'd', 'c', 'a')
c.selection_sort()
println(c.joinToString())
}</syntaxhighlight>
{{out}}
<pre>-5, -2, 0, 1, 3, 4, 6, 7, 8, 9
-9, -8, -7, -6, -4, -3, -1, 0, 2, 5
a, c, d, h, z</pre>
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="lb"> itemCount = 20
dim A(itemCount)
for i = 1 to itemCount
Line 1,276 ⟶ 2,250:
print
return
</syntaxhighlight>
</lang>
 
=={{header|LSE}}==
<syntaxhighlight lang="lse">
(*
** Tri par Sélection
** (LSE2000)
*)
PROCEDURE &Test(TABLEAU DE ENTIER pDonnees[], ENTIER pTaille) LOCAL pTaille
ENTIER i, j, minimum, tmp
POUR i <- 0 JUSQUA pTaille-1 FAIRE
minimum <- i
POUR j <- i+1 JUSQUA pTaille FAIRE
SI pDonnees[j] < pDonnees[minimum] ALORS
minimum <- j
FIN SI
BOUCLER
SI i # min ALORS
tmp <- pDonnees[i]
pDonnees[i] <- pDonnees[minimum]
pDonnees[minimum] <- tmp
FIN SI
BOUCLER
FIN PROCEDURE
</syntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function SelectionSort( f )
for k = 1, #f-1 do
local idx = k
Line 1,298 ⟶ 2,296:
for i in next, f do
print( f[i] )
end</langsyntaxhighlight>
 
=={{header|MathematicaMaple}}==
<syntaxhighlight lang="maple">arr:= Array([17,3,72,0,36,2,3,8,40,0]):
len := numelems(arr):
for i to len-1 do
j_min := i:
for j from i+1 to len do
if arr[j] < arr[j_min] then
j_min := j:
end if:
end do:
if (not j_min = i) then
temp := arr[i]:
arr[i] := arr[j_min]:
arr[j_min] := temp:
end if:
end do:
arr;</syntaxhighlight>
{{Out|Output}}
<pre>[0,0,2,3,3,8,17,36,40,72]</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Procedural solution with custom min function:
 
<langsyntaxhighlight Mathematicalang="mathematica">SelectSort[x_List] := Module[{n = 1, temp, xi = x, j},
While[n <= Length@x,
temp = xi[[n]];
Line 1,314 ⟶ 2,332:
];
xi
]</langsyntaxhighlight>
 
Recursive solution using a pre-existing Min[] function:
 
<langsyntaxhighlight Mathematicalang="mathematica">SelectSort2[x_List]:= Flatten[{Min@x, If[Length@x > 1, SelectSort2@Drop[x, First@Position[x, Min@x]], {}] }];</langsyntaxhighlight>
 
Validate by testing the ordering of a random number of randomly-sized random lists:
 
<langsyntaxhighlight Mathematicalang="mathematica">{And @@ Table[l = RandomInteger[150, RandomInteger[1000]];
Through[And[Length@# == Length@SelectSort@# &, OrderedQ@SelectSort@# &]@l],
{RandomInteger[150]}],
Line 1,329 ⟶ 2,347:
Through[And[Length@# == Length@SelectSort2@# &, OrderedQ@SelectSort2@# &]@l],
{RandomInteger[150]}]
]}</langsyntaxhighlight>
 
Validation Result:
Line 1,336 ⟶ 2,354:
=={{header|MATLAB}} / {{header|Octave}}==
 
<langsyntaxhighlight MATLABlang="matlab">function list = selectionSort(list)
 
listSize = numel(list);
Line 1,359 ⟶ 2,377:
end %for
end %selectionSort</langsyntaxhighlight>
 
Sample Usage:
<langsyntaxhighlight MATLABlang="matlab">>> selectionSort([4 3 1 5 6 2])
 
ans =
 
1 2 3 4 5 6</langsyntaxhighlight>
 
=={{header|Maxima}}==
<langsyntaxhighlight lang="maxima">selection_sort(v) := block([k, m, n],
n: length(v),
for i: 1 thru n do (
Line 1,382 ⟶ 2,400:
v: makelist(random(199) - 99, i, 1, 10); /* [52, -85, 41, -70, -59, 88, 19, 80, 90, 44] */
selection_sort(v)$
v; /* [-85, -70, -59, 19, 41, 44, 52, 80, 88, 90] */</langsyntaxhighlight>
 
=={{header|MAXScript}}==
<langsyntaxhighlight lang="maxscript">fn selectionSort arr =
(
local min = undefined
Line 1,404 ⟶ 2,422:
 
data = selectionSort #(4, 9, 3, -2, 0, 7, -5, 1, 6, 8)
print data</langsyntaxhighlight>
 
=={{header|N/t/roff}}==
<syntaxhighlight lang="n/t/roff">.de end
..
.de array
. nr \\$1.c 0 1
. de \\$1.push end
. nr \\$1..\\\\n+[\\$1.c] \\\\$1
. end
. de \\$1.pushln end
. if \\\\n(.$>0 .\\$1.push \\\\$1
. if \\\\n(.$>1 \{ \
. shift
. \\$1.pushln \\\\$@
. \}
. end
. de \\$1.dump end
. nr i 0 1
. while \\\\n+i<=\\\\n[\\$1.c] .tm \\\\n[\\$1..\\\\ni]
. rr i
. end
. de \\$1.swap end
. if (\\\\$1<=\\\\n[\\$1.c])&(\\\\$2<=\\\\n[\\$1.c]) \{ \
. nr b \\\\n[\\$1..\\\\$1]
. nr \\$1..\\\\$1 \\\\n[\\$1..\\\\$2]
. nr \\$1..\\\\$2 \\\\nb
. rr b
. \}
. end
..
.array myArray
.myArray.pushln 14 62 483 21 12 11 0 589 212 10 5 4 95 4 2 2 12 0 0
.de sort
. nr i 0 1
. while \\n+i<=\\n[\\$1.c] \{ \
. nr j \\ni 1
. nr st \\nj
. while \\n+j<=\\n[\\$1.c] \{ \
. if \\n[\\$1..\\nj]<\\n[\\$1..\\n(st] .nr st \\nj
. \}
. if !\\n(st=\\ni .\\$1.swap \\ni \\n(st
. \}
..
.sort myArray
.myArray.dump</syntaxhighlight>
 
===Output===
<syntaxhighlight lang="text">0
0
0
2
2
4
4
5
10
11
12
12
14
21
62
95
212
483
589</syntaxhighlight>
 
=={{header|Nanoquery}}==
{{trans|Java}}
<syntaxhighlight lang="nanoquery">import math
 
def sort(nums)
global math
for currentPlace in range(0, len(nums) - 2)
smallest = math.maxint
smallestAt = currentPlace + 1
for check in range(currentPlace, len(nums) - 1)
if nums[check] < smallest
smallestAt = check
smallest = nums[check]
end
end
temp = nums[currentPlace]
nums[currentPlace] = nums[smallestAt]
nums[smallestAt] = temp
end
return nums
end</syntaxhighlight>
 
=={{header|Nemerle}}==
{{trans|C#}}
<langsyntaxhighlight Nemerlelang="nemerle">using System;
using System.Console;
 
Line 1,434 ⟶ 2,540:
foreach (i in arr) Write($"$i ");
}
}</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols binary
 
Line 1,493 ⟶ 2,599:
 
return ra
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,516 ⟶ 2,622:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">proc selectionSort[T](a: var openarray[T]) =
let n = a.len
for i in 0 .. < n:
var m = i
for j in i .. < n:
if a[j] < a[m]:
m = j
Line 1,527 ⟶ 2,633:
var a = @[4, 65, 2, -31, 0, 99, 2, 83, 782]
selectionSort a
echo a</langsyntaxhighlight>
{{out}}
<pre>@[-31, 0, 2, 2, 4, 65, 83, 99, 782]</pre>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let rec selection_sort = function
[] -> []
| first::lst ->
Line 1,540 ⟶ 2,646:
| x::xs -> select_r small (x::output) xs
in
select_r first [] lst</langsyntaxhighlight>
 
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">func: selectSort(l)
{
| b j i k s |
l size ->s
l asListBuffer ->b
ListBuffer newSize(s) dup addAll(l) ->b
 
s loop: i [
i dup ->k b at
i 1 + s for: j [ b at(j) dup22dup <= ifTrue: [ drop ] else: [ nip j ->k ] ]
k i b at k b put i swap b put
]
b dup freeze ;</syntaxhighlight>
}</lang>
 
=={{header|ooRexx}}==
 
<langsyntaxhighlight lang="oorexx">/*REXX ****************************************************************
* program sorts an array using the selection-sort method.
* derived from REXX solution
Line 1,612 ⟶ 2,716:
x.9='Aventine'
x.0=9
return</langsyntaxhighlight>
 
=={{header|Oz}}==
Although lists are much more used in Oz than arrays, this algorithm seems more natural for arrays.
<langsyntaxhighlight lang="oz">declare
proc {SelectionSort Arr}
proc {Swap K L}
Line 1,645 ⟶ 2,749:
in
{SelectionSort A}
{Show {Array.toRecord unit A}}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">selectionSort(v)={
for(i=1,#v-1,
my(mn=i,t);
Line 1,659 ⟶ 2,763:
);
v
};</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 1,666 ⟶ 2,770:
=={{header|Perl}}==
{{trans|Tcl}}
<langsyntaxhighlight lang="perl">sub selection_sort
{my @a = @_;
foreach my $i (0 .. $#a - 1)
Line 1,672 ⟶ 2,776:
$a[$_] < $a[$min] and $min = $_ foreach $min .. $#a;
$a[$i] > $a[$min] and @a[$i, $min] = @a[$min, $i];}
return @a;}</langsyntaxhighlight>
 
=={{header|Perl 6}}==
<lang perl6>sub selection_sort ( @a is copy ) {
for 0 ..^ @a.end -> $i {
my $min = [ $i+1 .. @a.end ].min: { @a[$_] };
@a[$i, $min] = @a[$min, $i] if @a[$i] > @a[$min];
}
return @a;
}
 
my @data = 22, 7, 2, -5, 8, 4;
say 'input = ' ~ @data;
say 'output = ' ~ @data.&selection_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;">selection_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: #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: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">m</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">i</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;">sm</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">m</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">for</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;">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: #008080;">do</span>
<span style="color: #004080;">object</span> <span style="color: #000000;">sj</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;">if</span> <span style="color: #000000;">sj</span><span style="color: #0000FF;"><</span><span style="color: #000000;">sm</span> <span style="color: #008080;">then</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">sm</span><span style="color: #0000FF;">,</span><span style="color: #000000;">m</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">sj</span><span style="color: #0000FF;">,</span><span style="color: #000000;">j</span><span style="color: #0000FF;">}</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">sm</span><span style="color: #0000FF;"><</span><span style="color: #000000;">si</span> <span style="color: #008080;">then</span> <span style="color: #000080;font-style:italic;">-- (or equivalently m!=i)</span>
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">sm</span>
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">m</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;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</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;">selection_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>
<pre>input = 22 7 2 -5 8 4
{1,2,3,4,5,6,7,8,9,10}
output = -5 2 4 7 8 22
</pre>
 
=={{header|Phix}}==
Copy of [[Sorting_algorithms/Selection_sort#Euphoria|Euphoria]]
<lang Phix>function selection_sort(sequence s)
integer m
for i=1 to length(s) do
m = i
for j=i+1 to length(s) do
if s[j]<s[m] then
m = j
end if
end for
{s[i],s[m]} = {s[m],s[i]}
end for
return s
end function</lang>
 
=={{header|PHP}}==
Iterative:
<langsyntaxhighlight lang="php">function selection_sort(&$arr) {
$n = count($arr);
for($i = 0; $i < count($arr); $i++) {
Line 1,722 ⟶ 2,821:
list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$i]);
}
}</langsyntaxhighlight>
Recursive:
<langsyntaxhighlight lang="php">function selectionsort($arr,$result=array()){
if(count($arr) == 0){
return $result;
Line 1,732 ⟶ 2,831:
unset($arr[array_search(min($arr),$arr)]);
return selectionsort($arr,$nresult);
}</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de selectionSort (Lst)
(map
'((L) (and (cdr L) (xchg L (member (apply min @) L))))
Lst )
Lst )</langsyntaxhighlight>
 
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
Selection: procedure options (main); /* 2 November 2013 */
 
Line 1,771 ⟶ 2,870:
 
end Selection;
</syntaxhighlight>
</lang>
Results:
<pre>
Line 1,779 ⟶ 2,878:
 
=={{header|PowerShell}}==
<langsyntaxhighlight PowerShelllang="powershell">Function SelectionSort( [Array] $data )
{
$datal=$data.length-1
Line 1,798 ⟶ 2,897:
}
 
$l = 100; SelectionSort( ( 1..$l | ForEach-Object { $Rand = New-Object Random }{ $Rand.Next( 0, $l - 1 ) } ) )</langsyntaxhighlight>
 
=={{header|Prolog}}==
Works with '''SWI-Prolog 6.3.11''' (needs nth0/4).
<syntaxhighlight lang="prolog">
<lang Prolog>
selection_sort([], []).
selection_sort([H | L], [H1 | L2]) :-
Line 1,820 ⟶ 2,919:
nth0(Ind, L, H1, L2),
nth0(Ind, L1, H, L2)).
</syntaxhighlight>
</lang>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure selectionSort(Array a(1))
Protected i, j, lastIndex, minIndex
Line 1,835 ⟶ 2,935:
Swap a(minIndex), a(i)
Next
EndProcedure</langsyntaxhighlight>
 
=={{header|Python}}==
 
<langsyntaxhighlight lang="python">def selection_sort(lst):
for i, e in enumerate(lst):
mn = min(range(i,len(lst)), key=lst.__getitem__)
lst[i], lst[mn] = lst[mn], e
return lst</langsyntaxhighlight>
 
=={{header|Qi}}==
{{trans|sml}}
<syntaxhighlight lang="qi">(define select-r
Small [] Output -> [Small | (selection-sort Output)]
Small [X|Xs] Output -> (select-r X Xs [Small|Output]) where (< X Small)
Small [X|Xs] Output -> (select-r Small Xs [X|Output]))
 
(define selection-sort
[] -> []
[First|Lst] -> (select-r First Lst []))
 
(selection-sort [8 7 4 3 2 0 9 1 5 6])
</syntaxhighlight>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> [ 0 swap
behead swap
witheach
[ 2dup > iff
[ nip nip
i^ 1+ swap ]
else drop ]
drop ] is least ( [ --> n )
 
[ [] swap
dup size times
[ dup least pluck
swap dip join ]
drop ] is ssort ( [ --> [ )
 
[] 20 times [ 10 random join ]
dup echo cr
ssort echo cr</syntaxhighlight>
 
{{out}}
 
<pre>[ 5 2 5 0 4 5 1 5 1 1 0 3 7 2 0 9 6 1 8 7 ]
[ 0 0 0 1 1 1 1 2 2 3 4 5 5 5 5 6 7 7 8 9 ]
</pre>
 
=={{header|R}}==
For loop:
<langsyntaxhighlight lang="r">selectionsort.loop <- function(x)
{
lenx <- length(x)
Line 1,857 ⟶ 2,998:
}
x
}</langsyntaxhighlight>
Recursive:
 
(A prettier solution, but, you may need to increase the value of options("expressions") to test it. Also, you may get a stack overflow if the length of the input vector is more than a few thousand.)
<langsyntaxhighlight lang="r">selectionsort.rec <- function(x)
{
if(length(x) > 1)
Line 1,868 ⟶ 3,009:
c(x[mini], selectionsort(x[-mini]))
} else x
}</langsyntaxhighlight>
 
=={{header|Qi}}==
{{trans|sml}}
<lang qi>(define select-r
Small [] Output -> [Small | (selection-sort Output)]
Small [X|Xs] Output -> (select-r X Xs [Small|Output]) where (< X Small)
Small [X|Xs] Output -> (select-r Small Xs [X|Output]))
 
(define selection-sort
[] -> []
[First|Lst] -> (select-r First Lst []))
 
(selection-sort [8 7 4 3 2 0 9 1 5 6])
</lang>
 
=={{header|Racket}}==
<lang racket>
#lang racket
(define (selection-sort xs)
(cond [(empty? xs) '()]
[else (define x0 (apply min xs))
(cons x0 (selection-sort (remove x0 xs)))]))
</lang>
 
=={{header|Ra}}==
<syntaxhighlight lang="ra">
<lang Ra>
class SelectionSort
**Sort a list with the Selection Sort algorithm**
Line 1,928 ⟶ 3,046:
list[i] := list[minCandidate]
list[minCandidate] := temp
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
(define (selection-sort xs)
(cond [(empty? xs) '()]
[else (define x0 (apply min xs))
(cons x0 (selection-sort (remove x0 xs)))]))
</syntaxhighlight>
 
=={{header|Raku}}==
(formerly Perl 6)
Solution 1:
<syntaxhighlight lang="raku" line>sub selection_sort ( @a is copy ) {
for 0 ..^ @a.end -> $i {
my $min = [ $i+1 .. @a.end ].min: { @a[$_] };
@a[$i, $min] = @a[$min, $i] if @a[$i] > @a[$min];
}
return @a;
}
 
my @data = 22, 7, 2, -5, 8, 4;
say 'input = ' ~ @data;
say 'output = ' ~ @data.&selection_sort;
</syntaxhighlight>
 
{{out}}
<pre>input = 22 7 2 -5 8 4
output = -5 2 4 7 8 22
</pre>
 
Solution 2:
<syntaxhighlight lang="raku" line>sub selectionSort(@tmp) {
for ^@tmp -> $i {
my $min = $i; @tmp[$i, $_] = @tmp[$_, $i] if @tmp[$min] > @tmp[$_] for $i^..^@tmp;
}
return @tmp;
}
</syntaxhighlight>
 
{{out}}
<pre>input = 22 7 2 -5 8 4
output = -5 2 4 7 8 22
</pre>
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX program sorts a stemmed array using the selection-sortselection─sort algorithm. */
@.=;call init @.1 = '---The seven hills of Rome /*assign some values to an array:---' @. */
@.2 = '=============================='
@.3 = 'Caelian'
@.4 = 'Palatine'
@.5 = 'Capitoline'
@.6 = 'Virminal'
@.7 = 'Esquiline'
@.8 = 'Quirinal'
@.9 = 'Aventine'
do #=1 until @.#==''; end; #=#-1 /*find the number of items in the array*/
/* [↑] adjust # ('cause of DO index)*/
call show 'before sort' /*show the before array elements. */
say copies('▒', 65) /*show a nice separator line (fence). */
call selectionSort # /*invoke selection sort (and # items). */
call show ' after sort' /*show the after array elements. */
exit 0 /*stick a fork in it, we're a;;all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
init: @.=; @.1 = '---The seven hills of Rome:---'
@.2 = '=============================='; @.6 = 'Virminal'
@.3 = 'Caelian' ; @.7 = 'Esquiline'
@.4 = 'Palatine' ; @.8 = 'Quirinal'
@.5 = 'Capitoline' ; @.9 = 'Aventine'
do #=1 until @.#==''; end /*find the number of items in the array*/
#= #-1; return /*adjust # (because of DO index). */
/*──────────────────────────────────────────────────────────────────────────────────────*/
selectionSort: procedure expose @.; parse arg n
do j=1 for n-1; _= @.j; p= j
_=@.j; p do k=j;+1 to n; if do @.k>=j+1_ tothen niterate
_= @.k; p= k /*this item is out─of─order, swap if @.k<_ then do; _=@.k; p=k; endlater*/
end /*k*/
if p==j then iterate /*if the same, the order of items OK.is OK*/
_= @.j; @.j= @.p; @.p=_ _ /*swap 2 items that're out-of-sequenceout─of─sequence.*/
end /*j*/
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
show: do i=1 for #; say ' element' right(i,length(#)) arg(1)":" @.i; end; return</langsyntaxhighlight>
'''{{out|output'''|:}}
<pre>
element 1 before sort: ---The seven hills of Rome:---
Line 1,984 ⟶ 3,144:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
aList = [7,6,5,9,8,4,3,1,2,0]
see sortList(aList)
Line 2,004 ⟶ 3,164:
next
return list
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">
{{trans|Tcl}}
# a relatively readable version - creates a distinct array
<lang ruby>class Array
 
def selectionsort!
def sequential_sort(array)
for i in 0..length-2
min_idxsorted = i[]
 
for j in (i+1)...length
while array.any?
min_idx = j if self[j] < self[min_idx]
index_of_smallest_element = find_smallest_index(array) # defined below
sorted << array.delete_at(index_of_smallest_element)
end
 
sorted
end
 
def find_smallest_index(array)
smallest_element = array[0]
smallest_index = 0
 
array.each_with_index do |ele, idx|
if ele < smallest_element
smallest_element = ele
smallest_index = idx
end
end
 
smallest_index
end
 
puts "sequential_sort([9, 6, 8, 7, 5]): #{sequential_sort([9, 6, 8, 7, 5])}"
# prints: sequential_sort([9, 6, 8, 7, 5]): [5, 6, 7, 8, 9]
 
 
 
# more efficient version - swaps the array's elements in place
 
def sequential_sort_with_swapping(array)
array.each_with_index do |element, index|
smallest_unsorted_element_so_far = element
smallest_unsorted_index_so_far = index
 
(index+1...array.length).each do |index_value|
if array[index_value] < smallest_unsorted_element_so_far
smallest_unsorted_element_so_far = array[index_value]
smallest_unsorted_index_so_far = index_value
end
self[i], self[min_idx] = self[min_idx], self[i]
end
 
self
# swap index_value-th smallest element for index_value-th element
array[index], array[smallest_unsorted_index_so_far] = array[smallest_unsorted_index_so_far], array[index]
end
 
array
end
 
ary = [7,6,5,9,8,4,3,1,2,0]
puts "sequential_sort_with_swapping([7,6,5,9,8,4,3,1,2,0]): #{sequential_sort_with_swapping([7,6,5,9,8,4,3,1,2,0])}"
p ary.selectionsort!
# =>prints: sequential_sort_with_swapping([7,6,5,9,8,4,3,1,2,0]): [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]</lang>
</syntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">siz = 10
dim srdData(siz)
for i = 1 to siz
Line 2,045 ⟶ 3,246:
for i = 1 to siz
print i;chr$(9);srtData(i)
next i</langsyntaxhighlight>
<pre>1 20.5576419
2 32.4299311
Line 2,056 ⟶ 3,257:
9 95.4280853
10 98.8323211</pre>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">
fn selection_sort(array: &mut [i32]) {
 
let mut min;
 
for i in 0..array.len() {
 
min = i;
 
for j in (i+1)..array.len() {
 
if array[j] < array[min] {
min = j;
}
}
 
let tmp = array[i];
array[i] = array[min];
array[min] = tmp;
}
}
 
fn main() {
 
let mut array = [ 9, 4, 8, 3, -5, 2, 1, 6 ];
println!("The initial array is {:?}", array);
 
selection_sort(&mut array);
println!(" The sorted array is {:?}", array);
}
</syntaxhighlight>Another way:<syntaxhighlight lang="rust">
fn selection_sort<T: std::cmp::PartialOrd>(arr: &mut [T]) {
for i in 0 .. arr.len() {
let unsorted = &mut arr[i..];
let mut unsorted_min: usize = 0;
for (j, entry) in unsorted.iter().enumerate() {
if *entry < unsorted[unsorted_min] {
unsorted_min = j;
}
}
unsorted.swap(0, unsorted_min);
}
}
</syntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">def swap(a: Array[Int], i1: Int, i2: Int) = { val tmp = a(i1); a(i1) = a(i2); a(i2) = tmp }
 
def selectionSort(a: Array[Int]) =
for (i <- 0 until a.size - 1)
swap(a, i, (i + 1 until a.size).foldLeft(i)((currMin, index) =>
if (a(index) < a(currMin)) index else currMin))</langsyntaxhighlight>
 
This version avoids the extra definition by using a function literal:
 
<langsyntaxhighlight lang="scala">def selectionSort(a: Array[Int]) = for (i <- 0 until a.size - 1) (
{ (i1: Int, i2: Int) => val tmp = a(i1); a(i1) = a(i2); a(i2) = tmp }
) (i, (i + 1 until a.size).foldLeft(i)((currMin, index) => if (a(index) < a(currMin)) index else currMin) )</langsyntaxhighlight>
 
Functional way:
<langsyntaxhighlight lang="scala">def selectionSort[T <% Ordered[T]](list: List[T]): List[T] = {
def remove(e: T, list: List[T]): List[T] =
list match {
Line 2,087 ⟶ 3,334:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">const proc: selectionSort (inout array elemType: arr) is func
local
var integer: i is 0;
Line 2,108 ⟶ 3,355:
arr[i] := help;
end for;
end func;</langsyntaxhighlight>
 
Original source: [http://seed7.sourceforge.net/algorith/sorting.htm#selectionSort]
Line 2,114 ⟶ 3,361:
=={{header|Sidef}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">class Array {
method selectionsort {
range(0,for i in ^(self.len-2end).each { |i|
var min_idx = i;
rangefor j in (i+1, .. self.len-1end).each { |j|
if (self[j] < self[min_idx]) && ({
min_idx = j;
)}
}
self[.swap(i, min_idx] = self[min_idx, i];)
}
return self;
}
}
 
 
var nums = [7,6,5,9,8,4,3,1,2,0];
say nums.selectionsort;
 
 
var strs = ["John", "Kate", "Zerg", "Alice", "Joe", "Jane"];
say strs.selectionsort;</langsyntaxhighlight>
 
=={{header|Standard ML}}==
<langsyntaxhighlight lang="sml">fun selection_sort [] = []
| selection_sort (first::lst) =
let
Line 2,148 ⟶ 3,395:
in
small :: selection_sort output
end</langsyntaxhighlight>
 
=={{header|Stata}}==
<syntaxhighlight lang="stata">mata
function selection_sort(real vector a) {
real scalar i, j, k, n
n = length(a)
for (i = 1; i < n; i++) {
k = i
for (j = i+1; j <= n; j++) {
if (a[j] < a[k]) k = j
}
if (k != i) a[(i, k)] = a[(k, i)]
}
}
end</syntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight Swiftlang="swift">func selectionSort(inout arr:[Int]) {
var min:Int
Line 2,168 ⟶ 3,431:
}
}
}</langsyntaxhighlight>
 
=={{header|Tcl}}==
{{tcllib|struct::list}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
package require struct::list
 
Line 2,191 ⟶ 3,454:
}
 
puts [selectionsort {8 6 4 2 1 3 5 7 9}] ;# => 1 2 3 4 5 6 7 8 9</langsyntaxhighlight>
 
=={{header|TI-83 BASIC}}==
Line 2,222 ⟶ 3,485:
 
=={{header|uBasic/4tH}}==
<syntaxhighlight lang="text">PRINT "Selection sort:"
n = FUNC (_InitArray)
PROC _ShowArray (n)
Line 2,270 ⟶ 3,533:
PRINT
RETURN</langsyntaxhighlight>
 
=={{header|Ursala}}==
The selection_sort function is parameterized by a relational predicate p.
Line 2,276 ⟶ 3,540:
is deleted from the list and inserted into another on each iteration
rather than swapped with a preceding item of the same list.
<langsyntaxhighlight Ursalalang="ursala">#import std
 
selection_sort "p" = @iNX ~&l->rx ^(gldif ==,~&r)^/~&l ^|C/"p"$- ~&</langsyntaxhighlight>
This is already a bad way to code a sorting algorithm in this
language, but with only a bit more work, we can get a bigger and
slower version that more closely simulates the operations of
repeatedly reordering an array.
<langsyntaxhighlight Ursalalang="ursala">selection_sort "p" = ~&itB^?a\~&a ^|JahPfatPRC/~& ~=-~BrhPltPClhPrtPCTlrTQrS^D/"p"$- ~&</langsyntaxhighlight>
Here is a test program sorting by the partial order relation on natural
numbers.
<langsyntaxhighlight Ursalalang="ursala">#import nat
#cast %nL
 
example = selection_sort(nleq) <294,263,240,473,596,392,621,348,220,815></langsyntaxhighlight>
{{out}}
<pre><220,240,263,294,348,392,473,596,621,815></pre>
Line 2,296 ⟶ 3,560:
I shameless stole the swap function from the bubblesort VBscript implementation.
 
<syntaxhighlight lang="vba">
<lang VBA>
sub swap( byref a, byref b)
dim tmp
Line 2,315 ⟶ 3,579:
selectionSort = a
end function
</syntaxhighlight>
</lang>
 
=={{header|VBScript}}==
<langsyntaxhighlight lang="vb">Function Selection_Sort(s)
arr = Split(s,",")
For i = 0 To UBound(arr)
Line 2,335 ⟶ 3,600:
WScript.StdOut.Write "3,2,5,4,1" & vbTab & Selection_Sort("3,2,5,4,1")
WScript.StdOut.WriteLine
WScript.StdOut.Write "c,e,b,a,d" & vbTab & Selection_Sort("c,e,b,a,d")</langsyntaxhighlight>
{{out}}
<pre>
Line 2,341 ⟶ 3,606:
3,2,5,4,1 1,2,3,4,5
c,e,b,a,d a,b,c,d,e
</pre>
 
=={{header|Wren}}==
{{trans|Go}}
<syntaxhighlight lang="wren">var selectionSort = Fn.new { |a|
var last = a.count - 1
for (i in 0...last) {
var aMin = a[i]
var iMin = i
for (j in i+1..last) {
if (a[j] < aMin) {
aMin = a[j]
iMin = j
}
}
var t = a[i]
a[i] = aMin
a[iMin] = 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)")
selectionSort.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.selection(a)
System.print("After : %(a)")
System.print()
}</syntaxhighlight>
 
{{out}}
<pre>
As above.
</pre>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
string 0; \use zero-terminated strings
 
Line 2,369 ⟶ 3,687:
SelSort(Str, StrLen(Str));
Text(0, Str); CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
Line 2,375 ⟶ 3,693:
.Pabcdeefghiiijklmnoooqrstuuvwxyz
</pre>
 
=={{header|zkl}}==
<syntaxhighlight lang="zkl">fcn selectionSort(list){ // sort a list of ints
copy,r:=list.copy(),List();
while(copy){
min,idx:=(0).min(copy), copy.find(min);
r.append(min);
copy.del(idx);
}
r
}</syntaxhighlight>
<syntaxhighlight lang="zkl">selectionSort(List(28, 44, 46, 24, 19, -5, 2, 17, 11, 25, 4)).println();</syntaxhighlight>
{{out}}
<pre>
L(-5,2,4,11,17,19,24,25,28,44,46)
</pre>
 
 
{{omit from|GUISS}}
9,492

edits