var arr = new Array(1, 3, 2, 8, 9, 1, 5);function SelectionSort(arr) { if (arr == null || arr.length < 2) { return arr; } for (var i = 0; i < (arr.length - 1); i++) { let minIndex = i; for (let j = i + 1; j < arr.length; j++) { minIndex = arr[j] < arr[minIndex] ? j : minIndex; } let temp = arr[i]; arr[i] = arr[minIndex]; arr[minIndex] = temp; } return arr;}console.log(arr);SelectionSort(arr);console.log(arr);
Golang
func SelectionSort(nums []int32) { length := len(nums) for i := 0; i < length; i++ { min := i for j := i + 1; j < length; j++ { if nums[j] < nums[min] { min = j } } temp := nums[i] nums[i] = nums[min] nums[min] = temp } fmt.Println(nums)}
Python
def selection_sort(list2): for i in range(0, len (list2)-1): min_ = i for j in range(i + 1, len(list2)): if list2[j] < list2[min_]: min_ = j list2[i], list2[min_] = list2[min_], list2[i] # swap
Pascal
var num,temp,k,loop1,loop2:longint;a:array[1..1000] of longint;beginreadln(num);//讀入數據個數for loop1:=1to num doread(a[loop1]);//讀入進行排序的數據for loop1:=1to num-1 dobegink:= loop1;for loop2:=loop1+1to num doifa[k]>a[loop2]thenk:=loop2;//比較得出最小數ifk<>loop1then//最佳化節省時間begintemp:=a[k];a[k]:=a[loop1];a[loop1]:=temp;//進行數據交換end;end;forloop1:=1to num dowrite(a[loop1],'');//輸出排序後的數據readln;readln;end.
def selection_sort(array) result = [] array.size.times { result << array.delete_at(array.index(array.min)) } resultend
vb
vb實現選擇排序:
Private Sub xzPaiXu(a()AsDouble,shengAsBoolean)'a為需要排序的數組,sheng為True則為升序排列,為False,則為降序排列。Dim i AsInteger,j As IntegerDim temp As DoubleDimm As IntegerFor i = LBound(a) To UBound(a)-1'進行數組大小-1輪比較m=i'在第i輪比較時,假定第'i個元素為最值元素For j = i+1 To UBound(a)'在剩下的元素中找出最'值元素的下標並記錄在m中If sheng Then'若為升序,則m記錄最小元素'下標,否則記錄最大元素下標If a(j)<a(m) Thenm=jElse If a(j) > a(m) Thenm=jEnd IfNext j'將最值元素與第i個元素交換temp=a(i)a(i)=a(m)a(m)=tempNext iEnd Sub