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
(Added solution for Action!) |
m (→{{header|Wren}}: Minor tidy) |
||
(12 intermediate revisions by 9 users not shown) | |||
Line 28:
{{trans|Python}}
<
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)</
{{out}}
Line 45:
{{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 105:
RK EQU 8 k
RT EQU 9 temp
END SELECSRT</
{{out}}
<pre>
Line 113:
=={{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 */
Line 278:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
=={{header|Action!}}==
<
INT i
Line 336:
Test(c,8)
Test(d,12)
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Selection_sort.png Screenshot from Atari 8-bit computer]
Line 362:
=={{header|ActionScript}}==
<
//find the i'th element
for (var i:uint = 0; i < input.length; i++) {
Line 379:
}
return input;
}</
=={{header|Ada}}==
<
procedure Test_Selection_Sort is
Line 412:
Put (Integer'Image (A (I)) & " ");
end loop;
end Test_Selection_Sort;</
{{out}}
<pre>
Line 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 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 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 687 ⟶ 730:
</syntaxhighlight>
=={{header|Arturo}}==
<
sorted: new []
tmp: new items
Line 702 ⟶ 745:
]
print selectionSort [3 1 2 8 5 7 9 4 6]</
{{out}}
Line 710 ⟶ 753:
=={{header|AutoHotkey}}==
ahk forum: [http://www.autohotkey.com/forum/topic44657-105.html discussion]
<
MsgBox % SelecSort("xxx")
MsgBox % SelecSort("3,2,1")
Line 730 ⟶ 773:
sorted .= "," . a%A_Index%
Return SubStr(sorted,2) ; drop leading comma
}</
=={{header|AWK}}==
<
{
min = gl[gi]
Line 760 ⟶ 803:
print line[i]
}
}</
=={{header|BBC BASIC}}==
<
FOR I% = 1 TO Size%-1
lowest% = I%
Line 771 ⟶ 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
Line 823 ⟶ 866:
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}}==
<
let selectionsort(A, len) be if len > 1
Line 849 ⟶ 921:
selectionsort(array, length)
writes("Output: ") ; writearray(array, length) ; wrch('*N')
$)</
{{out}}
<pre>Input: 52 -5 -20 199 65 -3 190 25 9999 -5342
Line 856 ⟶ 928:
=={{header|C}}==
<
void selection_sort (int *a, int n) {
Line 883 ⟶ 955:
return 0;
}
</syntaxhighlight>
{{out}}
<pre>
Line 893 ⟶ 965:
This is a generic implementation that works with any type that implements the IComparable interface
<
public T[] Sort(T[] list) {
int k;
Line 912 ⟶ 984:
return list;
}
}</
Example of usage:
<
SelectionSort<String> mySort = new SelectionSort<string>();
Line 923 ⟶ 995:
for (int i = 0; i < result.Length; i++) {
Console.WriteLine(result[i]);
}</
{{out}}
Line 938 ⟶ 1,010:
Uses C++11. Compile with
g++ -std=c++11 selection.cpp
<
#include <iterator>
#include <iostream>
Line 954 ⟶ 1,026:
copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
}</
{{out}}
<pre>
Line 963 ⟶ 1,035:
This is an implementation that mutates a Java arraylist in place.
<
(defn arr-swap! [#^ArrayList arr i j]
Line 984 ⟶ 1,056:
(doseq [start-i (range (dec n))]
(move-min! start-i))
arr))))</
=={{header|COBOL}}==
<
UNTIL WB-IX-1 = WC-SIZE.
Line 1,014 ⟶ 1,086:
F-999.
EXIT.</
=={{header|Common Lisp}}==
<
(do ((length (length array))
(i 0 (1+ i)))
Line 1,054 ⟶ 1,126:
(etypecase sequence
(list (selection-sort-list sequence predicate))
(vector (selection-sort-vector sequence predicate))))</
Example use:
Line 1,066 ⟶ 1,138:
=={{header|Crystal}}==
This sorts the array in-place.
<
(0...array.size-1).each do |i|
nextMinIndex = i
Line 1,078 ⟶ 1,150:
end
end
end</
=={{header|D}}==
The actual function is very short.
<
enum AreSortableArrayItems(T) = isMutable!T &&
Line 1,142 ⟶ 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 1,152 ⟶ 1,255:
Static array is an arbitrary-based array of fixed length
<
{$APPTYPE CONSOLE}
Line 1,200 ⟶ 1,303:
Writeln;
Readln;
end.</
{{out}}
<pre>
Line 1,209 ⟶ 1,312:
===String sort===
// string is 1-based variable-length array of Char
<
var
Lowest: Char;
Line 1,224 ⟶ 1,327:
S[I]:= Lowest;
end;
end;</
<pre>
// in : S = 'the quick brown fox jumps over the lazy dog'
Line 1,232 ⟶ 1,335:
=={{header|E}}==
<
def cswap(c, a, b) {
def t := c[a]
Line 1,259 ⟶ 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 1,300 ⟶ 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 1,316 ⟶ 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,404 ⟶ 1,507:
end
</syntaxhighlight>
Test:
<
class
APPLICATION
Line 1,439 ⟶ 1,542:
end
</syntaxhighlight>
{{out}}
<pre>
Line 1,447 ⟶ 1,550:
=={{header|Elena}}==
ELENA
<
import system'routines;
Line 1,457 ⟶ 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,480 ⟶ 1,583:
console.printLine("before:",list.asEnumerable());
console.printLine("after:",list.selectionSort().asEnumerable())
}</
{{out}}
<pre>
Line 1,488 ⟶ 1,591:
=={{header|Elixir}}==
<
def selection_sort(list) when is_list(list), do: selection_sort(list, [])
Line 1,496 ⟶ 1,599:
selection_sort(List.delete(list, max), [max | sorted])
end
end</
Example:
Line 1,505 ⟶ 1,608:
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
-module(solution).
-import(lists,[delete/2,max/1]).
Line 1,522 ⟶ 1,625:
Ans=selection_sort([1,5,7,8,4,10],[]),
print_array(Ans).
</syntaxhighlight>
=={{header|Euphoria}}==
<
object tmp
integer m
Line 1,548 ⟶ 1,651:
pretty_print(1,s,{2})
puts(1,"\nAfter: ")
pretty_print(1,selection_sort(s),{2})</
{{out}}
Line 1,585 ⟶ 1,688:
=={{header|F Sharp|F#}}==
<
let rec ssort = function
[] -> []
Line 1,591 ⟶ 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,605 ⟶ 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,629 ⟶ 1,732:
array 10 selection
array 10 cells dump</
=={{header|Fortran}}==
{{works with|Fortran|95 and later}}
<
IMPLICIT NONE
Line 1,659 ⟶ 1,762:
END SUBROUTINE Selection_sort
END PROGRAM SELECTION</
{{out}}
<pre>
Line 1,667 ⟶ 1,770:
=={{header|FreeBASIC}}==
<
' compile with: fbc -s console
' for boundry checks on array's compile with: fbc -s console -exx
Line 1,713 ⟶ 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,719 ⟶ 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,768 ⟶ 1,871:
Return siList
End</
Output:
Line 1,777 ⟶ 1,880:
=={{header|GAP}}==
<
local i, j, k, n, m;
n := Size(v);
Line 1,796 ⟶ 1,899:
v := List([1 .. 100], n -> Random([1 .. 100]));
SelectionSort(v);
v;</
=={{header|Go}}==
<
import "fmt"
Line 1,824 ⟶ 1,927:
a[i], a[iMin] = aMin, a[i]
}
}</
More generic version that sorts anything that implements <code>sort.Interface</code>:
<
import (
Line 1,853 ⟶ 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>) {
Line 1,901 ⟶ 2,004:
Sys.println('Sorted Strings: ' + stringArray);
}
}</
{{out}}
Line 1,914 ⟶ 2,017:
=={{header|Icon}} and {{header|Unicon}}==
<
demosort(selectionsort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty")
end
Line 1,930 ⟶ 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,943 ⟶ 2,046:
=={{header|Io}}==
<
selectionSortInPlace := method(
size repeat(idx,
Line 1,952 ⟶ 2,055:
l := list(-1, 4, 2, -9)
l selectionSortInPlace println # ==> list(-9, -1, 2, 4)</
=={{header|J}}==
{{eff note|J|/:~}}
Create the following script and load it to a J session.
<
data=. y
for_xyz. y do.
Line 1,994 ⟶ 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 2,024 ⟶ 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 2,044 ⟶ 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 2,066 ⟶ 2,140:
)) as $ans
| swap( $currentPlace; $ans[0] )
) ;</
[1, 3.3, null, 2, null, [1,{"a":1 }] ] | selection_sort
</syntaxhighlight>
{{Out}}
<pre>
Line 2,089 ⟶ 2,163:
{{works with|Julia|0.6}}
<
len = length(arr)
if len < 2 return arr end
Line 2,103 ⟶ 2,177:
v = rand(-10:10, 10)
println("# unordered: $v\n -> ordered: ", selectionsort!(v))</
{{out}}
Line 2,111 ⟶ 2,185:
=={{header|Kotlin}}==
{{trans|C#}}
<
for (i in 0..size - 2) {
var k = i
Line 2,138 ⟶ 2,212:
c.selection_sort()
println(c.joinToString())
}</
{{out}}
<pre>-5, -2, 0, 1, 3, 4, 6, 7, 8, 9
Line 2,145 ⟶ 2,219:
=={{header|Liberty BASIC}}==
<
dim A(itemCount)
for i = 1 to itemCount
Line 2,176 ⟶ 2,250:
print
return
</syntaxhighlight>
=={{header|LSE}}==
<syntaxhighlight lang="lse">
(*
** Tri par Sélection
Line 2,200 ⟶ 2,274:
BOUCLER
FIN PROCEDURE
</syntaxhighlight>
=={{header|Lua}}==
<
for k = 1, #f-1 do
local idx = k
Line 2,222 ⟶ 2,296:
for i in next, f do
print( f[i] )
end</
=={{header|Maple}}==
<
len := numelems(arr):
for i to len-1 do
Line 2,240 ⟶ 2,314:
end if:
end do:
arr;</
{{Out|Output}}
<pre>[0,0,2,3,3,8,17,36,40,72]</pre>
Line 2,247 ⟶ 2,321:
Procedural solution with custom min function:
<
While[n <= Length@x,
temp = xi[[n]];
Line 2,258 ⟶ 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 2,273 ⟶ 2,347:
Through[And[Length@# == Length@SelectSort2@# &, OrderedQ@SelectSort2@# &]@l],
{RandomInteger[150]}]
]}</
Validation Result:
Line 2,280 ⟶ 2,354:
=={{header|MATLAB}} / {{header|Octave}}==
<
listSize = numel(list);
Line 2,303 ⟶ 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 2,326 ⟶ 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 2,348 ⟶ 2,422:
data = selectionSort #(4, 9, 3, -2, 0, 7, -5, 1, 6, 8)
print data</
=={{header|N/t/roff}}==
<
..
.de array
Line 2,393 ⟶ 2,467:
..
.sort myArray
.myArray.dump</
===Output===
<syntaxhighlight lang="text">0
0
0
Line 2,414 ⟶ 2,488:
212
483
589</
=={{header|Nanoquery}}==
{{trans|Java}}
<
def sort(nums)
Line 2,436 ⟶ 2,510:
end
return nums
end</
=={{header|Nemerle}}==
{{trans|C#}}
<
using System.Console;
Line 2,466 ⟶ 2,540:
foreach (i in arr) Write($"$i ");
}
}</
=={{header|NetRexx}}==
<
options replace format comments java crossref savelog symbols binary
Line 2,525 ⟶ 2,599:
return ra
</syntaxhighlight>
{{out}}
<pre>
Line 2,548 ⟶ 2,622:
=={{header|Nim}}==
<
let n = a.len
for i in 0 ..< n:
Line 2,559 ⟶ 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,572 ⟶ 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,586 ⟶ 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,642 ⟶ 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,675 ⟶ 2,749:
in
{SelectionSort A}
{Show {Array.toRecord unit A}}</
=={{header|PARI/GP}}==
<
for(i=1,#v-1,
my(mn=i,t);
Line 2,689 ⟶ 2,763:
);
v
};</
=={{header|Pascal}}==
Line 2,696 ⟶ 2,770:
=={{header|Perl}}==
{{trans|Tcl}}
<
{my @a = @_;
foreach my $i (0 .. $#a - 1)
Line 2,702 ⟶ 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}}==
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
Line 2,728 ⟶ 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>
<!--</
{{out}}
<pre>
Line 2,736 ⟶ 2,810:
=={{header|PHP}}==
Iterative:
<
$n = count($arr);
for($i = 0; $i < count($arr); $i++) {
Line 2,747 ⟶ 2,821:
list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$i]);
}
}</
Recursive:
<
if(count($arr) == 0){
return $result;
Line 2,757 ⟶ 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,796 ⟶ 2,870:
end Selection;
</syntaxhighlight>
Results:
<pre>
Line 2,804 ⟶ 2,878:
=={{header|PowerShell}}==
<
{
$datal=$data.length-1
Line 2,823 ⟶ 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,845 ⟶ 2,919:
nth0(Ind, L, H1, L2),
nth0(Ind, L1, H, L2)).
</syntaxhighlight>
=={{header|PureBasic}}==
<
Protected i, j, lastIndex, minIndex
Line 2,861 ⟶ 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}}
<
Small [] Output -> [Small | (selection-sort Output)]
Small [X|Xs] Output -> (select-r X Xs [Small|Output]) where (< X Small)
Line 2,883 ⟶ 2,957:
(selection-sort [8 7 4 3 2 0 9 1 5 6])
</syntaxhighlight>
=={{header|Quackery}}==
<
behead swap
witheach
Line 2,904 ⟶ 2,978:
[] 20 times [ 10 random join ]
dup echo cr
ssort echo cr</
{{out}}
Line 2,914 ⟶ 2,988:
=={{header|R}}==
For loop:
<
{
lenx <- length(x)
Line 2,924 ⟶ 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,935 ⟶ 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,972 ⟶ 3,046:
list[i] := list[minCandidate]
list[minCandidate] := temp
</syntaxhighlight>
=={{header|Racket}}==
<
#lang racket
(define (selection-sort xs)
Line 2,981 ⟶ 3,055:
[else (define x0 (apply min xs))
(cons x0 (selection-sort (remove x0 xs)))]))
</syntaxhighlight>
=={{header|Raku}}==
(formerly Perl 6)
Solution 1:
<syntaxhighlight lang="raku"
for 0 ..^ @a.end -> $i {
my $min = [ $i+1 .. @a.end ].min: { @a[$_] };
Line 2,997 ⟶ 3,071:
say 'input = ' ~ @data;
say 'output = ' ~ @data.&selection_sort;
</syntaxhighlight>
{{out}}
Line 3,005 ⟶ 3,079:
Solution 2:
<syntaxhighlight lang="raku"
for ^@tmp -> $i {
my $min = $i; @tmp[$i, $_] = @tmp[$_, $i] if @tmp[$min] > @tmp[$_] for $i^..^@tmp;
Line 3,011 ⟶ 3,085:
return @tmp;
}
</syntaxhighlight>
{{out}}
Line 3,019 ⟶ 3,093:
=={{header|REXX}}==
<
call init /*assign some values to an array: @. */
call show 'before sort' /*show the before array elements. */
Line 3,045 ⟶ 3,119:
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
show: do i=1 for #; say ' element' right(i,length(#)) arg(1)":" @.i; end; return</
{{out|output|:}}
<pre>
Line 3,070 ⟶ 3,144:
=={{header|Ring}}==
<
aList = [7,6,5,9,8,4,3,1,2,0]
see sortList(aList)
Line 3,090 ⟶ 3,164:
next
return list
</syntaxhighlight>
=={{header|Ruby}}==
<
# a relatively readable version - creates a distinct array
Line 3,149 ⟶ 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>
=={{header|Run BASIC}}==
<
dim srdData(siz)
for i = 1 to siz
Line 3,172 ⟶ 3,246:
for i = 1 to siz
print i;chr$(9);srtData(i)
next i</
<pre>1 20.5576419
2 32.4299311
Line 3,185 ⟶ 3,259:
=={{header|Rust}}==
<
fn selection_sort(array: &mut [i32]) {
Line 3,215 ⟶ 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 3,247 ⟶ 3,334:
}
}
</syntaxhighlight>
=={{header|Seed7}}==
<
local
var integer: i is 0;
Line 3,268 ⟶ 3,355:
arr[i] := help;
end for;
end func;</
Original source: [http://seed7.sourceforge.net/algorith/sorting.htm#selectionSort]
Line 3,274 ⟶ 3,361:
=={{header|Sidef}}==
{{trans|Ruby}}
<
method selectionsort {
for i in ^(self.end) {
Line 3,293 ⟶ 3,380:
var strs = ["John", "Kate", "Zerg", "Alice", "Joe", "Jane"];
say strs.selectionsort;</
=={{header|Standard ML}}==
<
| selection_sort (first::lst) =
let
Line 3,308 ⟶ 3,395:
in
small :: selection_sort output
end</
=={{header|Stata}}==
<
function selection_sort(real vector a) {
real scalar i, j, k, n
Line 3,323 ⟶ 3,410:
}
}
end</
=={{header|Swift}}==
<
var min:Int
Line 3,344 ⟶ 3,431:
}
}
}</
=={{header|Tcl}}==
{{tcllib|struct::list}}
<
package require struct::list
Line 3,367 ⟶ 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 3,398 ⟶ 3,485:
=={{header|uBasic/4tH}}==
<syntaxhighlight lang="text">PRINT "Selection sort:"
n = FUNC (_InitArray)
PROC _ShowArray (n)
Line 3,446 ⟶ 3,533:
PRINT
RETURN</
=={{header|Ursala}}==
Line 3,453 ⟶ 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 3,473 ⟶ 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,492 ⟶ 3,579:
selectionSort = a
end function
</syntaxhighlight>
=={{header|VBScript}}==
<
arr = Split(s,",")
For i = 0 To UBound(arr)
Line 3,513 ⟶ 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,523 ⟶ 3,610:
=={{header|Wren}}==
{{trans|Go}}
<
var last = a.count - 1
for (i in 0...last) {
Line 3,540 ⟶ 3,627:
}
var
for (a in
System.print("Before: %(a)")
selectionSort.call(a)
System.print("After : %(a)")
System.print()
}</
{{out}}
Line 3,559 ⟶ 3,646:
Alternatively we can just call a library method.
{{libheader|Wren-sort}}
<
var
for (a in
System.print("Before: %(a)")
Sort.selection(a)
System.print("After : %(a)")
System.print()
}</
{{out}}
Line 3,575 ⟶ 3,662:
=={{header|XPL0}}==
<
string 0; \use zero-terminated strings
Line 3,600 ⟶ 3,687:
SelSort(Str, StrLen(Str));
Text(0, Str); CrLf(0);
]</
{{out}}
Line 3,608 ⟶ 3,695:
=={{header|zkl}}==
<
copy,r:=list.copy(),List();
while(copy){
Line 3,616 ⟶ 3,703:
}
r
}</
<
{{out}}
<pre>
|