Sorting algorithms/Selection sort: Difference between revisions

m
(Add BCPL)
m (→‎{{header|Wren}}: Minor tidy)
 
(13 intermediate revisions by 10 users not shown)
Line 28:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F selection_sort(&lst)
L(e) lst
V mn = min(L.index .< lst.len, key' x -> @lst[x])
Line 35:
V arr = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]
selection_sort(&arr)
print(arr)</langsyntaxhighlight>
 
{{out}}
Line 45:
{{trans|PL/I}}
The program uses ASM structured macros and two ASSIST macros to keep the code as short as possible.
<langsyntaxhighlight lang="360asm">* Selection sort 26/06/2016
SELECSRT CSECT
USING SELECSRT,R13 base register
Line 105:
RK EQU 8 k
RT EQU 9 temp
END SELECSRT</langsyntaxhighlight>
{{out}}
<pre>
Line 113:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program selectionSort64.s */
Line 278:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
=={{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 297 ⟶ 379:
}
return input;
}</langsyntaxhighlight>
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
 
procedure Test_Selection_Sort is
Line 330 ⟶ 412:
Put (Integer'Image (A (I)) & " ");
end loop;
end Test_Selection_Sort;</langsyntaxhighlight>
{{out}}
<pre>
Line 342 ⟶ 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 367 ⟶ 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 373 ⟶ 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">
<lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* program selectionSort.s */
Line 605 ⟶ 730:
 
 
</syntaxhighlight>
</lang>
 
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">selectionSort: function [items][
sorted: new []
tmp: new items
Line 620 ⟶ 745:
]
 
print selectionSort [3 1 2 8 5 7 9 4 6]</langsyntaxhighlight>
 
{{out}}
Line 628 ⟶ 753:
=={{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 648 ⟶ 773:
sorted .= "," . a%A_Index%
Return SubStr(sorted,2) ; drop leading comma
}</langsyntaxhighlight>
 
=={{header|AWK}}==
<langsyntaxhighlight lang="awk">function getminindex(gl, gi, gs)
{
min = gl[gi]
Line 678 ⟶ 803:
print line[i]
}
}</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight BBCBASIClang="bbcbasic">DEF PROC_SelectionSort(Size%)
FOR I% = 1 TO Size%-1
lowest% = I%
Line 689 ⟶ 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">
<lang GWBASIC>
10 'SAVE"SELSORT",A
20 ' Selection Sort Algorithm
Line 741 ⟶ 866:
450 PRINT "End of program"
460 END
</syntaxhighlight>
</lang>
 
==={{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}}==
<langsyntaxhighlight BCPLlang="bcpl">get "libhdr"
 
let selectionsort(A, len) be if len > 1
Line 767 ⟶ 921:
selectionsort(array, length)
writes("Output: ") ; writearray(array, length) ; wrch('*N')
$)</langsyntaxhighlight>
{{out}}
<pre>Input: 52 -5 -20 199 65 -3 190 25 9999 -5342
Line 774 ⟶ 928:
=={{header|C}}==
 
<langsyntaxhighlight lang="c">#include <stdio.h>
 
void selection_sort (int *a, int n) {
Line 801 ⟶ 955:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 811 ⟶ 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 830 ⟶ 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 841 ⟶ 995:
for (int i = 0; i < result.Length; i++) {
Console.WriteLine(result[i]);
}</langsyntaxhighlight>
 
{{out}}
Line 856 ⟶ 1,010:
Uses C++11. Compile with
g++ -std=c++11 selection.cpp
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <iterator>
#include <iostream>
Line 872 ⟶ 1,026:
copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
}</langsyntaxhighlight>
{{out}}
<pre>
Line 881 ⟶ 1,035:
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 902 ⟶ 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 932 ⟶ 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 972 ⟶ 1,126:
(etypecase sequence
(list (selection-sort-list sequence predicate))
(vector (selection-sort-vector sequence predicate))))</langsyntaxhighlight>
 
Example use:
Line 984 ⟶ 1,138:
=={{header|Crystal}}==
This sorts the array in-place.
<langsyntaxhighlight lang="crystal">def selectionSort(array : Array)
(0...array.size-1).each do |i|
nextMinIndex = i
Line 996 ⟶ 1,150:
end
end
end</langsyntaxhighlight>
 
=={{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 1,060 ⟶ 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 1,070 ⟶ 1,255:
 
Static array is an arbitrary-based array of fixed length
<langsyntaxhighlight Delphilang="delphi">program TestSelectionSort;
 
{$APPTYPE CONSOLE}
Line 1,118 ⟶ 1,303:
Writeln;
Readln;
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 1,127 ⟶ 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 1,142 ⟶ 1,327:
S[I]:= Lowest;
end;
end;</langsyntaxhighlight>
<pre>
// in : S = 'the quick brown fox jumps over the lazy dog'
Line 1,150 ⟶ 1,335:
=={{header|E}}==
 
<langsyntaxhighlight lang="e">def selectionSort := {
def cswap(c, a, b) {
def t := c[a]
Line 1,177 ⟶ 1,362:
}
}
}</langsyntaxhighlight>
 
=={{header|EasyLang}}==
 
<syntaxhighlight lang="text">
<lang>subr sort
proc sort . d[] .
for i = 0 to len data[] - 2
for min_posi = i1 to len d[] - 1
for j = i + 1 to len datad[] - 1
if datad[j] < datad[min_posi]
min_pos = swap d[j] d[i]
.
.
.
swap data[i] data[min_pos]
.
.
data[] = [ 29 4 72 44 55 26 27 77 92 5 ]
call sort data[]
print data[]</lang>
</syntaxhighlight>
 
=={{header|EchoLisp}}==
===List sort===
<langsyntaxhighlight lang="scheme">
;; recursive version (adapted from Racket)
(lib 'list) ;; list-delete
Line 1,218 ⟶ 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 1,234 ⟶ 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 1,322 ⟶ 1,507:
 
end
</syntaxhighlight>
</lang>
Test:
<langsyntaxhighlight lang="eiffel">
class
APPLICATION
Line 1,357 ⟶ 1,542:
 
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,365 ⟶ 1,550:
 
=={{header|Elena}}==
ELENA 56.0x :
<langsyntaxhighlight lang="elena">import extensions;
import system'routines;
Line 1,375 ⟶ 1,560:
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])
Line 1,398 ⟶ 1,583:
console.printLine("before:",list.asEnumerable());
console.printLine("after:",list.selectionSort().asEnumerable())
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,406 ⟶ 1,591:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Sort do
def selection_sort(list) when is_list(list), do: selection_sort(list, [])
Line 1,414 ⟶ 1,599:
selection_sort(List.delete(list, max), [max | sorted])
end
end</langsyntaxhighlight>
 
Example:
Line 1,423 ⟶ 1,608:
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
-module(solution).
-import(lists,[delete/2,max/1]).
Line 1,440 ⟶ 1,625:
Ans=selection_sort([1,5,7,8,4,10],[]),
print_array(Ans).
</syntaxhighlight>
</lang>
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">function selection_sort(sequence s)
object tmp
integer m
Line 1,466 ⟶ 1,651:
pretty_print(1,s,{2})
puts(1,"\nAfter: ")
pretty_print(1,selection_sort(s),{2})</langsyntaxhighlight>
 
{{out}}
Line 1,503 ⟶ 1,688:
 
=={{header|F Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
let rec ssort = function
[] -> []
Line 1,509 ⟶ 1,694:
let min, rest =
List.fold (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}}==
<langsyntaxhighlight lang="factor">USING: kernel math sequences sequences.extras ;
 
: select ( m n seq -- )
Line 1,523 ⟶ 1,708:
 
: selection-sort! ( seq -- seq' )
[ ] [ length dup ] [ ] tri [ select ] 2curry each-integer ;</langsyntaxhighlight>
Example use
<langsyntaxhighlight 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 }</langsyntaxhighlight>
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">defer less? ' < is less?
 
: least ( start end -- least )
Line 1,547 ⟶ 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 1,577 ⟶ 1,762:
END SUBROUTINE Selection_sort
 
END PROGRAM SELECTION</langsyntaxhighlight>
{{out}}
<pre>
Line 1,585 ⟶ 1,770:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' version 03-12-2016
' compile with: fbc -s console
' for boundry checks on array's compile with: fbc -s console -exx
Line 1,631 ⟶ 1,816:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>unsort 1 -7 -5 -4 6 5 -3 4 2 0 3 -6 -2 7 -1
Line 1,637 ⟶ 1,822:
 
=={{header|Gambas}}==
<langsyntaxhighlight lang="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,686 ⟶ 1,871:
Return siList
 
End</langsyntaxhighlight>
 
Output:
Line 1,695 ⟶ 1,880:
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap">SelectionSort := function(v)
local i, j, k, n, m;
n := Size(v);
Line 1,714 ⟶ 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,742 ⟶ 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,771 ⟶ 1,956:
a.Swap(i, iMin)
}
}</langsyntaxhighlight>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.List (delete)
 
selSort :: (Ord a) => [a] -> [a]
selSort [] = []
selSort xs = selSort (delete x xs) ++ [x]
where x = maximum xs</langsyntaxhighlight>
 
=={{header|Haxe}}==
<langsyntaxhighlight lang="haxe">class SelectionSort {
@:generic
public static function sort<T>(arr:Array<T>) {
Line 1,819 ⟶ 2,004:
Sys.println('Sorted Strings: ' + stringArray);
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,832 ⟶ 2,017:
 
=={{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,848 ⟶ 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,861 ⟶ 2,046:
 
=={{header|Io}}==
<langsyntaxhighlight lang="io">List do (
selectionSortInPlace := method(
size repeat(idx,
Line 1,870 ⟶ 2,055:
 
l := list(-1, 4, 2, -9)
l selectionSortInPlace println # ==> list(-9, -1, 2, 4)</langsyntaxhighlight>
 
=={{header|IS-BASIC}}==
<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</lang>
 
=={{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,912 ⟶ 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,942 ⟶ 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,962 ⟶ 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,984 ⟶ 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 2,007 ⟶ 2,163:
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">function selectionsort!(arr::Vector{<:Real})
len = length(arr)
if len < 2 return arr end
Line 2,021 ⟶ 2,177:
 
v = rand(-10:10, 10)
println("# unordered: $v\n -> ordered: ", selectionsort!(v))</langsyntaxhighlight>
 
{{out}}
Line 2,029 ⟶ 2,185:
=={{header|Kotlin}}==
{{trans|C#}}
<langsyntaxhighlight lang="scala">fun <T : Comparable<T>> Array<T>.selection_sort() {
for (i in 0..size - 2) {
var k = i
Line 2,056 ⟶ 2,212:
c.selection_sort()
println(c.joinToString())
}</langsyntaxhighlight>
{{out}}
<pre>-5, -2, 0, 1, 3, 4, 6, 7, 8, 9
Line 2,063 ⟶ 2,219:
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="lb"> itemCount = 20
dim A(itemCount)
for i = 1 to itemCount
Line 2,094 ⟶ 2,250:
print
return
</syntaxhighlight>
</lang>
 
=={{header|LSE}}==
<syntaxhighlight lang="lse">
<lang LSE>
(*
** Tri par Sélection
Line 2,118 ⟶ 2,274:
BOUCLER
FIN PROCEDURE
</syntaxhighlight>
</lang>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function SelectionSort( f )
for k = 1, #f-1 do
local idx = k
Line 2,140 ⟶ 2,296:
for i in next, f do
print( f[i] )
end</langsyntaxhighlight>
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">arr:= Array([17,3,72,0,36,2,3,8,40,0]):
len := numelems(arr):
for i to len-1 do
Line 2,158 ⟶ 2,314:
end if:
end do:
arr;</langsyntaxhighlight>
{{Out|Output}}
<pre>[0,0,2,3,3,8,17,36,40,72]</pre>
Line 2,165 ⟶ 2,321:
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 2,176 ⟶ 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 2,191 ⟶ 2,347:
Through[And[Length@# == Length@SelectSort2@# &, OrderedQ@SelectSort2@# &]@l],
{RandomInteger[150]}]
]}</langsyntaxhighlight>
 
Validation Result:
Line 2,198 ⟶ 2,354:
=={{header|MATLAB}} / {{header|Octave}}==
 
<langsyntaxhighlight MATLABlang="matlab">function list = selectionSort(list)
 
listSize = numel(list);
Line 2,221 ⟶ 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 2,244 ⟶ 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 2,266 ⟶ 2,422:
 
data = selectionSort #(4, 9, 3, -2, 0, 7, -5, 1, 6, 8)
print data</langsyntaxhighlight>
 
=={{header|N/t/roff}}==
<langsyntaxhighlight Nlang="n/t/roff">.de end
..
.de array
Line 2,311 ⟶ 2,467:
..
.sort myArray
.myArray.dump</langsyntaxhighlight>
 
===Output===
<syntaxhighlight lang="text">0
0
0
Line 2,332 ⟶ 2,488:
212
483
589</langsyntaxhighlight>
 
=={{header|Nanoquery}}==
{{trans|Java}}
<langsyntaxhighlight Nanoquerylang="nanoquery">import math
 
def sort(nums)
Line 2,354 ⟶ 2,510:
end
return nums
end</langsyntaxhighlight>
 
=={{header|Nemerle}}==
{{trans|C#}}
<langsyntaxhighlight Nemerlelang="nemerle">using System;
using System.Console;
 
Line 2,384 ⟶ 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 2,443 ⟶ 2,599:
 
return ra
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,466 ⟶ 2,622:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">proc selectionSort[T](a: var openarray[T]) =
let n = a.len
for i in 0 ..< n:
Line 2,477 ⟶ 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 2,490 ⟶ 2,646:
| x::xs -> select_r small (x::output) xs
in
select_r first [] lst</langsyntaxhighlight>
 
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">: selectSort(l)
| b j i k s |
l size ->s
Line 2,504 ⟶ 2,660:
k i b at b put i swap b put
]
b dup freeze ;</langsyntaxhighlight>
 
=={{header|ooRexx}}==
 
<langsyntaxhighlight lang="oorexx">/*REXX ****************************************************************
* program sorts an array using the selection-sort method.
* derived from REXX solution
Line 2,560 ⟶ 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 2,593 ⟶ 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 2,607 ⟶ 2,763:
);
v
};</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 2,614 ⟶ 2,770:
=={{header|Perl}}==
{{trans|Tcl}}
<langsyntaxhighlight lang="perl">sub selection_sort
{my @a = @_;
foreach my $i (0 .. $#a - 1)
Line 2,620 ⟶ 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|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
Line 2,646 ⟶ 2,802:
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,654 ⟶ 2,810:
=={{header|PHP}}==
Iterative:
<langsyntaxhighlight lang="php">function selection_sort(&$arr) {
$n = count($arr);
for($i = 0; $i < count($arr); $i++) {
Line 2,665 ⟶ 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 2,675 ⟶ 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 2,714 ⟶ 2,870:
 
end Selection;
</syntaxhighlight>
</lang>
Results:
<pre>
Line 2,722 ⟶ 2,878:
 
=={{header|PowerShell}}==
<langsyntaxhighlight PowerShelllang="powershell">Function SelectionSort( [Array] $data )
{
$datal=$data.length-1
Line 2,741 ⟶ 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 2,763 ⟶ 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 2,779 ⟶ 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}}
<langsyntaxhighlight lang="qi">(define select-r
Small [] Output -> [Small | (selection-sort Output)]
Small [X|Xs] Output -> (select-r X Xs [Small|Output]) where (< X Small)
Line 2,801 ⟶ 2,957:
 
(selection-sort [8 7 4 3 2 0 9 1 5 6])
</syntaxhighlight>
</lang>
 
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery"> [ 0 swap
behead swap
witheach
Line 2,822 ⟶ 2,978:
[] 20 times [ 10 random join ]
dup echo cr
ssort echo cr</langsyntaxhighlight>
 
{{out}}
Line 2,832 ⟶ 2,988:
=={{header|R}}==
For loop:
<langsyntaxhighlight lang="r">selectionsort.loop <- function(x)
{
lenx <- length(x)
Line 2,842 ⟶ 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 2,853 ⟶ 3,009:
c(x[mini], selectionsort(x[-mini]))
} else x
}</langsyntaxhighlight>
 
=={{header|Ra}}==
<syntaxhighlight lang="ra">
<lang Ra>
class SelectionSort
**Sort a list with the Selection Sort algorithm**
Line 2,890 ⟶ 3,046:
list[i] := list[minCandidate]
list[minCandidate] := temp
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(define (selection-sort xs)
Line 2,899 ⟶ 3,055:
[else (define x0 (apply min xs))
(cons x0 (selection-sort (remove x0 xs)))]))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
Solution 1:
<syntaxhighlight lang="raku" perl6line>sub selection_sort ( @a is copy ) {
for 0 ..^ @a.end -> $i {
my $min = [ $i+1 .. @a.end ].min: { @a[$_] };
Line 2,915 ⟶ 3,071:
say 'input = ' ~ @data;
say 'output = ' ~ @data.&selection_sort;
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,923 ⟶ 3,079:
 
Solution 2:
<syntaxhighlight lang="raku" perl6line>sub selectionSort(@tmp) {
for ^@tmp -> $i {
my $min = $i; @tmp[$i, $_] = @tmp[$_, $i] if @tmp[$min] > @tmp[$_] for $i^..^@tmp;
Line 2,929 ⟶ 3,085:
return @tmp;
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,937 ⟶ 3,093:
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX program sorts a stemmed array using the selection─sort algorithm. */
call init /*assign some values to an array: @. */
call show 'before sort' /*show the before array elements. */
Line 2,963 ⟶ 3,119:
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
show: do i=1 for #; say ' element' right(i,length(#)) arg(1)":" @.i; end; return</langsyntaxhighlight>
{{out|output|:}}
<pre>
Line 2,988 ⟶ 3,144:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
aList = [7,6,5,9,8,4,3,1,2,0]
see sortList(aList)
Line 3,008 ⟶ 3,164:
next
return list
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">
# a relatively readable version - creates a distinct array
 
Line 3,067 ⟶ 3,223:
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])}"
# 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]
</syntaxhighlight>
</lang>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">siz = 10
dim srdData(siz)
for i = 1 to siz
Line 3,090 ⟶ 3,246:
for i = 1 to siz
print i;chr$(9);srtData(i)
next i</langsyntaxhighlight>
<pre>1 20.5576419
2 32.4299311
Line 3,103 ⟶ 3,259:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">
fn selection_sort(array: &mut [i32]) {
 
Line 3,133 ⟶ 3,289:
println!(" The sorted array is {:?}", array);
}
</syntaxhighlight>Another way:<syntaxhighlight lang="rust">
</lang>
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 3,165 ⟶ 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 3,186 ⟶ 3,355:
arr[i] := help;
end for;
end func;</langsyntaxhighlight>
 
Original source: [http://seed7.sourceforge.net/algorith/sorting.htm#selectionSort]
Line 3,192 ⟶ 3,361:
=={{header|Sidef}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">class Array {
method selectionsort {
for i in ^(self.end) {
Line 3,211 ⟶ 3,380:
 
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 3,226 ⟶ 3,395:
in
small :: selection_sort output
end</langsyntaxhighlight>
 
=={{header|Stata}}==
<langsyntaxhighlight lang="stata">mata
function selection_sort(real vector a) {
real scalar i, j, k, n
Line 3,241 ⟶ 3,410:
}
}
end</langsyntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight Swiftlang="swift">func selectionSort(inout arr:[Int]) {
var min:Int
Line 3,262 ⟶ 3,431:
}
}
}</langsyntaxhighlight>
 
=={{header|Tcl}}==
{{tcllib|struct::list}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
package require struct::list
 
Line 3,285 ⟶ 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 3,316 ⟶ 3,485:
 
=={{header|uBasic/4tH}}==
<syntaxhighlight lang="text">PRINT "Selection sort:"
n = FUNC (_InitArray)
PROC _ShowArray (n)
Line 3,364 ⟶ 3,533:
PRINT
RETURN</langsyntaxhighlight>
 
=={{header|Ursala}}==
Line 3,371 ⟶ 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 3,391 ⟶ 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 3,410 ⟶ 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 3,431 ⟶ 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 3,441 ⟶ 3,610:
=={{header|Wren}}==
{{trans|Go}}
<langsyntaxhighlight ecmascriptlang="wren">var selectionSort = Fn.new { |a|
var last = a.count - 1
for (i in 0...last) {
Line 3,458 ⟶ 3,627:
}
 
var asarray = [ [4, 65, 2, -31, 0, 99, 2, 83, 782, 1], [7, 5, 2, 6, 1, 4, 2, 6, 3] ]
for (a in asarray) {
System.print("Before: %(a)")
selectionSort.call(a)
System.print("After : %(a)")
System.print()
}</langsyntaxhighlight>
 
{{out}}
Line 3,477 ⟶ 3,646:
Alternatively we can just call a library method.
{{libheader|Wren-sort}}
<langsyntaxhighlight ecmascriptlang="wren">import "./sort" for Sort
 
var asarray = [ [4, 65, 2, -31, 0, 99, 2, 83, 782, 1], [7, 5, 2, 6, 1, 4, 2, 6, 3] ]
for (a in asarray) {
System.print("Before: %(a)")
Sort.selection(a)
System.print("After : %(a)")
System.print()
}</langsyntaxhighlight>
 
{{out}}
Line 3,493 ⟶ 3,662:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
string 0; \use zero-terminated strings
 
Line 3,518 ⟶ 3,687:
SelSort(Str, StrLen(Str));
Text(0, Str); CrLf(0);
]</langsyntaxhighlight>
 
{{out}}
Line 3,526 ⟶ 3,695:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn selectionSort(list){ // sort a list of ints
copy,r:=list.copy(),List();
while(copy){
Line 3,534 ⟶ 3,703:
}
r
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">selectionSort(List(28, 44, 46, 24, 19, -5, 2, 17, 11, 25, 4)).println();</langsyntaxhighlight>
{{out}}
<pre>
9,476

edits