排序算法——选择排序【代码实现】

ActionScript

function selectionSort(input: Array):Array {
	//find the i'th element
	for (var i:uint = 0; i < input.length; i++) {
		//set minIndex to an arbitrary value
		var minIndex:uint=i;
		//find the smallest number
		for (var j:uint = i; j < input.length; j++) {
			if (input[j]<input[minIndex]) {
				minIndex=j;
			}
		}
		//swap the smallest number into place
		var tmp:Number=input[i];
		input[i]=input[minIndex];
		input[minIndex]=tmp;
	}
	return input;
}

C

#include <stdio.h>
 
void selection_sort (int *a, int n) {
    int i, j, m, t;
    for (i = 0; i < n; i++) {
        for (j = i, m = i; j < n; j++) {
            if (a[j] < a[m]) {
                m = j;
            }
        }
        t = a[i];
        a[i] = a[m];
        a[m] = t;
    }
}
 
int main () {
    int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};
    int n = sizeof a / sizeof a[0];
    int i;
    for (i = 0; i < n; i++)
        printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
    selection_sort(a, n);
    for (i = 0; i < n; i++)
        printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
    return 0;
}

C++

#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";
}

C#


class SelectionSort<T> where T : IComparable {
    public T[] Sort(T[] list) {
        int k;
        T temp;
 
        for (int i = 0; i < list.Length; i++) {
            k = i;
            for (int j=i + 1; j < list.Length; j++) {
                if (list[j].CompareTo(list[k]) < 0) {
                    k = j;
                }
            }
            temp = list[i];
            list[i] = list[k];
            list[k] = temp;
        }
 
        return list;
    }
}

Go

package main
 
import "fmt"
 
var a = []int{170, 45, 75, -90, -802, 24, 2, 66}
 
func main() {
    fmt.Println("before:", a)
    selectionSort(a)
    fmt.Println("after: ", a)
}
 
func selectionSort(a []int) {
    last := len(a) - 1
    for i := 0; i < last; i++ {
        aMin := a[i]
        iMin := i
        for j := i + 1; j < len(a); j++ {
            if a[j] < aMin {
                aMin = a[j]
                iMin = j
            }
        }
        a[i], a[iMin] = aMin, a[i]
    }
}

通用版本

package main
 
import (
  "sort"
  "fmt"
)
 
var a = []int{170, 45, 75, -90, -802, 24, 2, 66}
 
func main() {
    fmt.Println("before:", a)
    selectionSort(sort.IntSlice(a))
    fmt.Println("after: ", a)
}
 
func selectionSort(a sort.Interface) {
    last := a.Len() - 1
    for i := 0; i < last; i++ {
        iMin := i
        for j := i + 1; j < a.Len(); j++ {
            if a.Less(j, iMin) {
                iMin = j
            }
        }
        a.Swap(i, iMin)
    }
}

Java

public static void sort(int[] nums){
	for(int currentPlace = 0;currentPlace<nums.length-1;currentPlace++){
		int smallest = Integer.MAX_VALUE;
		int smallestAt = currentPlace+1;
		for(int check = currentPlace; check<nums.length;check++){
			if(nums[check]<smallest){
				smallestAt = check;
				smallest = nums[check];
			}
		}
		int temp = nums[currentPlace];
		nums[currentPlace] = nums[smallestAt];
		nums[smallestAt] = temp;
	}
}

JavaScript

function selectionSort(nums) {
  var len = nums.length;
  for(var i = 0; i < len; i++) {
    var minAt = i;
    for(var j = i + 1; j < len; j++) {
      if(nums[j] < nums[minAt])
        minAt = j;
    }
 
    if(minAt != i) {
      var temp = nums[i];
      nums[i] = nums[minAt];
      nums[minAt] = temp;
    }
  }
  return nums;
}

Julia

function selectionsort!(arr::Vector{<:Real})
    len = length(arr)
    if len < 2 return arr end
    for i in 1:len-1
        lmin, j = findmin(arr[i+1:end])
        if lmin < arr[i]
            arr[i+j] = arr[i]
            arr[i] = lmin
        end
    end
    return arr
end
 
v = rand(-10:10, 10)
println("# unordered: $v\n -> ordered: ", selectionsort!(v))

Kotlin

fun <T : Comparable<T>> Array<T>.selection_sort() {
    for (i in 0..size - 2) {
        var k = i
        for (j in i + 1..size - 1)
            if (this[j] < this[k])
                k = j
 
        if (k != i) {
            val tmp = this[i]
            this[i] = this[k]
            this[k] = tmp
        }
    }
}
 
fun main(args: Array<String>) {
    val i = arrayOf(4, 9, 3, -2, 0, 7, -5, 1, 6, 8)
    i.selection_sort()
    println(i.joinToString())
 
    val s = Array(i.size, { -i[it].toShort() })
    s.selection_sort()
    println(s.joinToString())
 
    val c = arrayOf('z', 'h', 'd', 'c', 'a')
    c.selection_sort()
    println(c.joinToString())
}

MATLAB / Octave

function list = selectionSort(list)
 
    listSize = numel(list);
 
    for i = (1:listSize-1)
 
        minElem = list(i);
        minIndex = i;
 
        %This for loop can be vectorized, but there will be no significant
        %increase in sorting efficiency.
        for j = (i:listSize)    
            if list(j) <= minElem
                minElem = list(j);
                minIndex = j;
            end                              
        end
 
        if i ~= minIndex
            list([minIndex i]) = list([i minIndex]); %Swap
        end
 
    end %for
end %selectionSort

Perl

sub selection_sort
  {my @a = @_;
   foreach my $i (0 .. $#a - 1)
      {my $min = $i + 1;
       $a[$_] < $a[$min] and $min = $_ foreach $min .. $#a;
       $a[$i] > $a[$min] and @a[$i, $min] = @a[$min, $i];}
   return @a;}

Perl 6

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;

PHP

  • 迭代:
function selection_sort(&$arr) {
    $n = count($arr);
    for($i = 0; $i < count($arr); $i++) {
        $min = $i;
        for($j = $i + 1; $j < $n; $j++){
            if($arr[$j] < $arr[$min]){
                $min = $j;
            }
        }
        list($arr[$i],$arr[$min]) = array($arr[$min],$arr[$i]);
    }
}
  • 递归
function selectionsort($arr,$result=array()){
    if(count($arr) == 0){
        return $result;
    }
    $nresult = $result;
    $nresult[] = min($arr);
    unset($arr[array_search(min($arr),$arr)]);
    return selectionsort($arr,$nresult);	
}

PowerShell

Function SelectionSort( [Array] $data )
{
	$datal=$data.length-1
	0..( $datal - 1 ) | ForEach-Object {
		$min = $data[ $_ ]
		$mini = $_
		( $_ + 1 )..$datal | ForEach-Object {
			if( $data[ $_ ] -lt $min ) {
				$min = $data[ $_ ]
				$mini = $_
			}
		}
		$temp = $data[ $_ ]
		$data[ $_ ] = $min
		$data[ $mini ] = $temp
	}
	$data
}
 
$l = 100; SelectionSort( ( 1..$l | ForEach-Object { $Rand = New-Object Random }{ $Rand.Next( 0, $l - 1 ) } ) )

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

R

  • 循环
selectionsort.loop <- function(x)
{
   lenx <- length(x)
   for(i in seq_along(x))
   {
      mini <- (i - 1) + which.min(x[i:lenx])
      start_ <- seq_len(i-1)
      x <- c(x[start_], x[mini], x[-c(start_, mini)])
   }
   x
}
  • 递归
selectionsort.rec <- function(x)
{
   if(length(x) > 1)
   {
      mini <- which.min(x)
      c(x[mini], selectionsort(x[-mini]))
   } else x
}

Ruby

class Array
  def selectionsort!
    for i in 0..length-2
      min_idx = i
      for j in (i+1)...length
        min_idx = j  if self[j] < self[min_idx]
      end
      self[i], self[min_idx] = self[min_idx], self[i]
    end
    self
  end
end
ary = [7,6,5,9,8,4,3,1,2,0]
p ary.selectionsort!
# => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Rust

fn selection_sort(array: &mut [i32]) {
 
    let mut min;
 
    for i in 0..array.len() {
 
        min = i;
 
        for j in (i+1)..array.len() {
 
            if array[j] < array[min] {
                min = j;
            }
        }
 
        let tmp = array[i];
        array[i] = array[min];
        array[min] = tmp;
    }
}
 
fn main() {
 
    let mut array = [ 9, 4, 8, 3, -5, 2, 1, 6 ];
    println!("The initial array is {:?}", array);
 
    selection_sort(&mut array);
    println!(" The sorted array is {:?}", array);
}

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))

Swift

func selectionSort(inout arr:[Int]) {
    var min:Int
 
    for n in 0..<arr.count {
        min = n
 
        for x in n+1..<arr.count {
            if (arr[x] < arr[min]) {
                min = x
            }
        }
 
        if min != n {
            let temp = arr[min]
            arr[min] = arr[n]
            arr[n] = temp
        }
    }
}

更多代码,持续更新!
整理自网络。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

辕门骁骑

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值