Sorting algorithms/Selection sort: Difference between revisions
Sorting algorithms/Selection sort (view source)
Revision as of 12:20, 8 February 2024
, 3 months ago→{{header|Wren}}: Minor tidy
(→{{header|Haxe}}: Made function generic.) |
m (→{{header|Wren}}: Minor tidy) |
||
(46 intermediate revisions by 25 users not shown) | |||
Line 1:
{{task|Sorting Algorithms
{{Sorting Algorithm}}
[[Category:Sorting]]
;Task:
Line 17 ⟶ 19:
;References:
* Rosetta Code: [[O]] (complexity).
* Wikipedia: [[wp:Selection_sort|Selection sort]].
* Wikipedia: [[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.
<
SELECSRT CSECT
USING SELECSRT,R13 base register
Line 84 ⟶ 105:
RK EQU 8 k
RT EQU 9 temp
END SELECSRT</
{{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 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}}==
<
//find the i'th element
for (var i:uint = 0; i < input.length; i++) {
Line 108 ⟶ 379:
}
return input;
}</
=={{header|Ada}}==
<
procedure Test_Selection_Sort is
Line 141 ⟶ 412:
Put (Integer'Image (A (I)) & " ");
end loop;
end Test_Selection_Sort;</
{{out}}
<pre>
Line 153 ⟶ 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}}
<
PROC in place selection sort = (REF[]DATA a)VOID:
Line 178 ⟶ 449:
in place selection sort(ref data);
FOR i TO UPB ref data DO print(ref data[i]) OD; print(new line);
print((data))</
{{out}}
<pre>
Line 184 ⟶ 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 */
Line 415 ⟶ 730:
</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]
<
MsgBox % SelecSort("xxx")
MsgBox % SelecSort("3,2,1")
Line 439 ⟶ 773:
sorted .= "," . a%A_Index%
Return SubStr(sorted,2) ; drop leading comma
}</syntaxhighlight>
=={{header|AWK}}==
<
{
min = gl[gi]
Line 469 ⟶ 803:
print line[i]
}
}</
=={{header|BBC BASIC}}==
<
FOR I% = 1 TO Size%-1
lowest% = I%
Line 480 ⟶ 814:
IF I%<>lowest% SWAP data%(I%),data%(lowest%)
NEXT I%
ENDPROC</
=={{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}}==
<
void selection_sort (int *a, int n) {
Line 511 ⟶ 955:
return 0;
}
</syntaxhighlight>
{{out}}
<pre>
4 65 2 -31 0 99 2 83 782 1
-31 0 1 2 2 4 65 83 99 782
</pre>
Line 546 ⟶ 965:
This is a generic implementation that works with any type that implements the IComparable interface
<
public T[] Sort(T[] list) {
int k;
Line 565 ⟶ 984:
return list;
}
}</
Example of usage:
<
SelectionSort<String> mySort = new SelectionSort<string>();
Line 576 ⟶ 995:
for (int i = 0; i < result.Length; i++) {
Console.WriteLine(result[i]);
}</
{{out}}
Line 587 ⟶ 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.
<
(defn arr-swap! [#^ArrayList arr i j]
Line 612 ⟶ 1,056:
(doseq [start-i (range (dec n))]
(move-min! start-i))
arr))))</
=={{header|COBOL}}==
<
UNTIL WB-IX-1 = WC-SIZE.
Line 642 ⟶ 1,086:
F-999.
EXIT.</
=={{header|Common Lisp}}==
<
(do ((length (length array))
(i 0 (1+ i)))
Line 682 ⟶ 1,126:
(etypecase sequence
(list (selection-sort-list sequence predicate))
(vector (selection-sort-vector sequence predicate))))</
Example use:
Line 691 ⟶ 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.
<
(0...array.size-1).each do |i|
nextMinIndex = i
Line 707 ⟶ 1,150:
end
end
end</
=={{header|D}}==
The actual function is very short.
<
enum AreSortableArrayItems(T) = isMutable!T &&
Line 771 ⟶ 1,214:
a.selectionSort;
a.writeln;
}</
{{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 781 ⟶ 1,255:
Static array is an arbitrary-based array of fixed length
<
{$APPTYPE CONSOLE}
Line 829 ⟶ 1,303:
Writeln;
Readln;
end.</
{{out}}
<pre>
Line 838 ⟶ 1,312:
===String sort===
// string is 1-based variable-length array of Char
<
var
Lowest: Char;
Line 853 ⟶ 1,327:
S[I]:= Lowest;
end;
end;</
<pre>
// in : S = 'the quick brown fox jumps over the lazy dog'
Line 861 ⟶ 1,335:
=={{header|E}}==
<
def cswap(c, a, b) {
def t := c[a]
Line 888 ⟶ 1,362:
}
}
}</
=={{header|EasyLang}}==
<syntaxhighlight lang="text">
proc sort . d[] .
for
for j = i + 1 to len
if
.
.
.
data[] = [ 29 4 72 44 55 26 27 77 92 5 ]
print data[]
</syntaxhighlight>
=={{header|EchoLisp}}==
===List sort===
<
;; recursive version (adapted from Racket)
(lib 'list) ;; list-delete
Line 928 ⟶ 1,403:
→ (0 1 2 3 4 5 6 7 8 9 10 11 12)
</syntaxhighlight>
===Array sort===
<
;; sort an array in place
(define (sel-sort a (amin) (imin))
Line 944 ⟶ 1,419:
(sel-sort a)
→ #( 2 3 4 5 6 8 9)
</syntaxhighlight>
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
class
SELECTION_SORT [G -> COMPARABLE]
Line 1,033 ⟶ 1,507:
end
</syntaxhighlight>
Test:
<
class
APPLICATION
Line 1,068 ⟶ 1,542:
end
</syntaxhighlight>
{{out}}
<pre>
Line 1,074 ⟶ 1,548:
Sorted: -7 1 1 3 5 7 27 32 99
</pre>
=={{header|Elena}}==
ELENA
<
import system'routines;
Line 1,085 ⟶ 1,560:
var copy := self.clone();
for(int i := 0
{
int k := i;
for(int j := i + 1
{
if (copy[j] < copy[k])
Line 1,104 ⟶ 1,579:
public program()
{
var list := new string[]
console.printLine("before:",list.asEnumerable());
console.printLine("after:",list.selectionSort().asEnumerable())
}</
{{out}}
<pre>
Line 1,116 ⟶ 1,591:
=={{header|Elixir}}==
<
def selection_sort(list) when is_list(list), do: selection_sort(list, [])
Line 1,124 ⟶ 1,599:
selection_sort(List.delete(list, max), [max | sorted])
end
end</
Example:
Line 1,131 ⟶ 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]).
Line 1,149 ⟶ 1,625:
Ans=selection_sort([1,5,7,8,4,10],[]),
print_array(Ans).
</syntaxhighlight>
=={{header|Euphoria}}==
<
object tmp
integer m
Line 1,176 ⟶ 1,651:
pretty_print(1,s,{2})
puts(1,"\nAfter: ")
pretty_print(1,selection_sort(s),{2})</
{{out}}
Line 1,213 ⟶ 1,688:
=={{header|F Sharp|F#}}==
<
let rec ssort = function
[] -> []
Line 1,219 ⟶ 1,694:
let min, rest =
List.fold (fun (min,acc) x ->
if
else (min,
(x, []) xs
in min::ssort rest
</syntaxhighlight>
=={{header|Factor}}==
<
: select ( m n seq -- )
Line 1,233 ⟶ 1,708:
: selection-sort! ( seq -- seq' )
[ ] [ length dup ] [ ] tri [ select ] 2curry each-integer ;</
Example use
<
--- Data stack:
{ -6 -6 -5 -2 -1 3 4 5 5 9 }</
=={{header|Forth}}==
<
: least ( start end -- least )
Line 1,257 ⟶ 1,732:
array 10 selection
array 10 cells dump</
=={{header|Fortran}}==
{{works with|Fortran|95 and later}}
<
IMPLICIT NONE
Line 1,287 ⟶ 1,762:
END SUBROUTINE Selection_sort
END PROGRAM SELECTION</
{{out}}
<pre>
Line 1,293 ⟶ 1,768:
Sorted array : -5 -2 0 1 3 4 6 7 8 9
</pre>
=={{header|FreeBASIC}}==
<
' compile with: fbc -s console
' for boundry checks on array's compile with: fbc -s console -exx
Line 1,340 ⟶ 1,816:
Print : Print "hit any key to end program"
Sleep
End</
{{out}}
<pre>unsort 1 -7 -5 -4 6 5 -3 4 2 0 3 -6 -2 7 -1
Line 1,346 ⟶ 1,822:
=={{header|Gambas}}==
<
siLow As Short = -99 'Set the lowest value number to create
siHigh As Short = 99 'Set the highest value number to create
Line 1,395 ⟶ 1,871:
Return siList
End</
Output:
Line 1,402 ⟶ 1,878:
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}}==
<
local i, j, k, n, m;
n := Size(v);
Line 1,422 ⟶ 1,899:
v := List([1 .. 100], n -> Random([1 .. 100]));
SelectionSort(v);
v;</
=={{header|Go}}==
<
import "fmt"
Line 1,450 ⟶ 1,927:
a[i], a[iMin] = aMin, a[i]
}
}</
More generic version that sorts anything that implements <code>sort.Interface</code>:
<
import (
Line 1,479 ⟶ 1,956:
a.Swap(i, iMin)
}
}</
=={{header|Haskell}}==
<
selSort :: (Ord a) => [a] -> [a]
selSort [] = []
selSort xs = selSort (delete x xs) ++ [x]
where x = maximum xs</
=={{header|Haxe}}==
<
@:generic
public static function sort<T>(arr:Array<T>) {
var len = arr.length;
for (index in 0...len) {
Line 1,526 ⟶ 2,004:
Sys.println('Sorted Strings: ' + stringArray);
}
}</
{{out}}
Line 1,537 ⟶ 2,015:
Sorted Strings: [We,all,are,be,created,equal,hold,men,self-evident,that,these,to,truths]
</pre>
=={{header|Icon}} and {{header|Unicon}}==
<
demosort(selectionsort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty")
end
Line 1,567 ⟶ 2,033:
}
return X
end</
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,579 ⟶ 2,045:
with op = &null: "eqrtwy" (0 ms)</pre>
=={{header|
<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.
<
data=. y
for_xyz. y do.
Line 1,619 ⟶ 2,068:
end.
data
)</
In an email discussion, Roger_Hui presented the following tacit code:
<
ss1=: ({. , $:@}.)@ix^:(*@#)</
To validate:
<
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</
=={{header|Java}}==
This algorithm sorts in place. The call <tt>sort(array)</tt> will rearrange the array and not create a new one.
<
for(int currentPlace = 0;currentPlace<nums.length-1;currentPlace++){
int smallest = Integer.MAX_VALUE;
Line 1,649 ⟶ 2,098:
nums[smallestAt] = temp;
}
}</
=={{header|JavaScript}}==
This algorithm sorts array of numbers.
<
var len = nums.length;
for(var i = 0; i < len; i++) {
Line 1,669 ⟶ 2,118:
}
return nums;
}</
=={{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>.<
def selection_sort:
def swap(i;j): if i == j then . else .[i] as $tmp | .[i] = .[j] | .[j] = $tmp end;
Line 1,691 ⟶ 2,140:
)) as $ans
| swap( $currentPlace; $ans[0] )
) ;</
[1, 3.3, null, 2, null, [1,{"a":1 }] ] | selection_sort
</syntaxhighlight>
{{Out}}
<pre>
Line 1,710 ⟶ 2,159:
]
</pre>
=={{header|Julia}}==
{{works with|Julia|0.6}}
<
len = length(arr)
if len < 2 return arr end
Line 1,727 ⟶ 2,177:
v = rand(-10:10, 10)
println("# unordered: $v\n -> ordered: ", selectionsort!(v))</
{{out}}
Line 1,735 ⟶ 2,185:
=={{header|Kotlin}}==
{{trans|C#}}
<
for (i in 0..size - 2) {
var k = i
Line 1,762 ⟶ 2,212:
c.selection_sort()
println(c.joinToString())
}</
{{out}}
<pre>-5, -2, 0, 1, 3, 4, 6, 7, 8, 9
Line 1,769 ⟶ 2,219:
=={{header|Liberty BASIC}}==
<
dim A(itemCount)
for i = 1 to itemCount
Line 1,800 ⟶ 2,250:
print
return
</syntaxhighlight>
=={{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}}==
<
for k = 1, #f-1 do
local idx = k
Line 1,822 ⟶ 2,296:
for i in next, f do
print( f[i] )
end</
=={{header|Maple}}==
<
len := numelems(arr):
for i to len-1 do
Line 1,840 ⟶ 2,314:
end if:
end do:
arr;</
{{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:
<
While[n <= Length@x,
temp = xi[[n]];
Line 1,858 ⟶ 2,332:
];
xi
]</
Recursive solution using a pre-existing Min[] function:
<
Validate by testing the ordering of a random number of randomly-sized random lists:
<
Through[And[Length@# == Length@SelectSort@# &, OrderedQ@SelectSort@# &]@l],
{RandomInteger[150]}],
Line 1,873 ⟶ 2,347:
Through[And[Length@# == Length@SelectSort2@# &, OrderedQ@SelectSort2@# &]@l],
{RandomInteger[150]}]
]}</
Validation Result:
Line 1,880 ⟶ 2,354:
=={{header|MATLAB}} / {{header|Octave}}==
<
listSize = numel(list);
Line 1,903 ⟶ 2,377:
end %for
end %selectionSort</
Sample Usage:
<
ans =
1 2 3 4 5 6</
=={{header|Maxima}}==
<
n: length(v),
for i: 1 thru n do (
Line 1,926 ⟶ 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] */</
=={{header|MAXScript}}==
<
(
local min = undefined
Line 1,948 ⟶ 2,422:
data = selectionSort #(4, 9, 3, -2, 0, 7, -5, 1, 6, 8)
print data</
=={{header|N/t/roff}}==
<
..
.de array
Line 2,015 ⟶ 2,467:
..
.sort myArray
.myArray.dump</
===Output===
<syntaxhighlight lang="text">0
0
0
Line 2,036 ⟶ 2,488:
212
483
589</
=={{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#}}
<
using System.Console;
Line 2,066 ⟶ 2,540:
foreach (i in arr) Write($"$i ");
}
}</
=={{header|NetRexx}}==
<
options replace format comments java crossref savelog symbols binary
Line 2,125 ⟶ 2,599:
return ra
</syntaxhighlight>
{{out}}
<pre>
Line 2,148 ⟶ 2,622:
=={{header|Nim}}==
<
let n = a.len
for i in 0 ..
var m = i
for j in i ..
if a[j] < a[m]:
m = j
Line 2,159 ⟶ 2,633:
var a = @[4, 65, 2, -31, 0, 99, 2, 83, 782]
selectionSort a
echo a</
{{out}}
<pre>@[-31, 0, 2, 2, 4, 65, 83, 99, 782]</pre>
=={{header|OCaml}}==
<
[] -> []
| first::lst ->
Line 2,172 ⟶ 2,646:
| x::xs -> select_r small (x::output) xs
in
select_r first [] lst</
=={{header|Oforth}}==
<
| b j i k s |
l size ->s
Line 2,186 ⟶ 2,660:
k i b at b put i swap b put
]
b dup freeze ;</
=={{header|ooRexx}}==
<
* program sorts an array using the selection-sort method.
* derived from REXX solution
Line 2,242 ⟶ 2,716:
x.9='Aventine'
x.0=9
return</
=={{header|Oz}}==
Although lists are much more used in Oz than arrays, this algorithm seems more natural for arrays.
<
proc {SelectionSort Arr}
proc {Swap K L}
Line 2,275 ⟶ 2,749:
in
{SelectionSort A}
{Show {Array.toRecord unit A}}</
=={{header|PARI/GP}}==
<
for(i=1,#v-1,
my(mn=i,t);
Line 2,289 ⟶ 2,763:
);
v
};</
=={{header|Pascal}}==
Line 2,296 ⟶ 2,770:
=={{header|Perl}}==
{{trans|Tcl}}
<
{my @a = @_;
foreach my $i (0 .. $#a - 1)
Line 2,302 ⟶ 2,776:
$a[$_] < $a[$min] and $min = $_ foreach $min .. $#a;
$a[$i] > $a[$min] and @a[$i, $min] = @a[$min, $i];}
return @a;}</
=={{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>
{1,2,3,4,5,6,7,8,9,10}
</pre>
=={{header|PHP}}==
Iterative:
<
$n = count($arr);
for($i = 0; $i < count($arr); $i++) {
Line 2,367 ⟶ 2,821:
list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$i]);
}
}</
Recursive:
<
if(count($arr) == 0){
return $result;
Line 2,377 ⟶ 2,831:
unset($arr[array_search(min($arr),$arr)]);
return selectionsort($arr,$nresult);
}</
=={{header|PicoLisp}}==
<
(map
'((L) (and (cdr L) (xchg L (member (apply min @) L))))
Lst )
Lst )</
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
Selection: procedure options (main); /* 2 November 2013 */
Line 2,416 ⟶ 2,870:
end Selection;
</syntaxhighlight>
Results:
<pre>
Line 2,424 ⟶ 2,878:
=={{header|PowerShell}}==
<
{
$datal=$data.length-1
Line 2,443 ⟶ 2,897:
}
$l = 100; SelectionSort( ( 1..$l | ForEach-Object { $Rand = New-Object Random }{ $Rand.Next( 0, $l - 1 ) } ) )</
=={{header|Prolog}}==
Works with '''SWI-Prolog 6.3.11''' (needs nth0/4).
<syntaxhighlight lang="prolog">
selection_sort([], []).
selection_sort([H | L], [H1 | L2]) :-
Line 2,465 ⟶ 2,919:
nth0(Ind, L, H1, L2),
nth0(Ind, L1, H, L2)).
</syntaxhighlight>
=={{header|PureBasic}}==
<
Protected i, j, lastIndex, minIndex
Line 2,480 ⟶ 2,935:
Swap a(minIndex), a(i)
Next
EndProcedure</
=={{header|Python}}==
<
for i, e in enumerate(lst):
mn = min(range(i,len(lst)), key=lst.__getitem__)
lst[i], lst[mn] = lst[mn], e
return lst</
=={{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:
<
{
lenx <- length(x)
Line 2,502 ⟶ 2,998:
}
x
}</
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.)
<
{
if(length(x) > 1)
Line 2,513 ⟶ 3,009:
c(x[mini], selectionsort(x[-mini]))
} else x
}</
=={{header|Ra}}==
<syntaxhighlight lang="ra">
class SelectionSort
**Sort a list with the Selection Sort algorithm**
Line 2,573 ⟶ 3,046:
list[i] := list[minCandidate]
list[minCandidate] := temp
</syntaxhighlight>
=={{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}}==
<
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
/*──────────────────────────────────────────────────────────────────────────────────────*/
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
do k=j+1 to n; if @.k>=_ then iterate
_= @.k; p= k
end /*k*/
if p==j then iterate
_= @.j; @.j= @.p; @.p= _
end /*j*/
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
show: do i=1 for #; say ' element' right(i,length(#)) arg(1)":" @.i; end; return</
{{out|output|:}}
<pre>
Line 2,625 ⟶ 3,144:
=={{header|Ring}}==
<
aList = [7,6,5,9,8,4,3,1,2,0]
see sortList(aList)
Line 2,645 ⟶ 3,164:
next
return list
</syntaxhighlight>
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">
# a relatively readable version - creates a distinct array
def sequential_sort(array)
while array.any?
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
end
# 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
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])}"
#
</syntaxhighlight>
=={{header|Run BASIC}}==
<
dim srdData(siz)
for i = 1 to siz
Line 2,686 ⟶ 3,246:
for i = 1 to siz
print i;chr$(9);srtData(i)
next i</
<pre>1 20.5576419
2 32.4299311
Line 2,699 ⟶ 3,259:
=={{header|Rust}}==
<
fn selection_sort(array: &mut [i32]) {
Line 2,729 ⟶ 3,289:
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}}==
<
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))</
This version avoids the extra definition by using a function literal:
<
{ (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) )</
Functional way:
<
def remove(e: T, list: List[T]): List[T] =
list match {
Line 2,761 ⟶ 3,334:
}
}
</syntaxhighlight>
=={{header|Seed7}}==
<
local
var integer: i is 0;
Line 2,782 ⟶ 3,355:
arr[i] := help;
end for;
end func;</
Original source: [http://seed7.sourceforge.net/algorith/sorting.htm#selectionSort]
Line 2,788 ⟶ 3,361:
=={{header|Sidef}}==
{{trans|Ruby}}
<
method selectionsort {
for i in ^(self.end) {
Line 2,807 ⟶ 3,380:
var strs = ["John", "Kate", "Zerg", "Alice", "Joe", "Jane"];
say strs.selectionsort;</
=={{header|Standard ML}}==
<
| selection_sort (first::lst) =
let
Line 2,822 ⟶ 3,395:
in
small :: selection_sort output
end</
=={{header|Stata}}==
<
function selection_sort(real vector a) {
real scalar i, j, k, n
Line 2,836 ⟶ 3,410:
}
}
end</
=={{header|Swift}}==
<
var min:Int
Line 2,856 ⟶ 3,431:
}
}
}</
=={{header|Tcl}}==
{{tcllib|struct::list}}
<
package require struct::list
Line 2,879 ⟶ 3,454:
}
puts [selectionsort {8 6 4 2 1 3 5 7 9}] ;# => 1 2 3 4 5 6 7 8 9</
=={{header|TI-83 BASIC}}==
Line 2,910 ⟶ 3,485:
=={{header|uBasic/4tH}}==
<syntaxhighlight lang="text">PRINT "Selection sort:"
n = FUNC (_InitArray)
PROC _ShowArray (n)
Line 2,958 ⟶ 3,533:
PRINT
RETURN</
=={{header|Ursala}}==
The selection_sort function is parameterized by a relational predicate p.
Line 2,964 ⟶ 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.
<
selection_sort "p" = @iNX ~&l->rx ^(gldif ==,~&r)^/~&l ^|C/"p"$- ~&</
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.
<
Here is a test program sorting by the partial order relation on natural
numbers.
<
#cast %nL
example = selection_sort(nleq) <294,263,240,473,596,392,621,348,220,815></
{{out}}
<pre><220,240,263,294,348,392,473,596,621,815></pre>
Line 2,984 ⟶ 3,560:
I shameless stole the swap function from the bubblesort VBscript implementation.
<syntaxhighlight lang="vba">
sub swap( byref a, byref b)
dim tmp
Line 3,003 ⟶ 3,579:
selectionSort = a
end function
</syntaxhighlight>
=={{header|VBScript}}==
<
arr = Split(s,",")
For i = 0 To UBound(arr)
Line 3,023 ⟶ 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")</
{{out}}
<pre>
Line 3,029 ⟶ 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}}==
<
string 0; \use zero-terminated strings
Line 3,057 ⟶ 3,687:
SelSort(Str, StrLen(Str));
Text(0, Str); CrLf(0);
]</
{{out}}
Line 3,065 ⟶ 3,695:
=={{header|zkl}}==
<
copy,r:=list.copy(),List();
while(copy){
Line 3,073 ⟶ 3,703:
}
r
}</
<
{{out}}
<pre>
|