加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Golang - SelectionSort

发布时间:2020-12-16 18:43:53 所属栏目:大数据 来源:网络整理
导读://We start selection sort by scanning the entire list to //find its smallest element and exchange it with the first //element,putting the smallest element in its final position in //the sorted list. Then we scan the list,starting with the
 //We start selection sort by scanning the entire list to //find its smallest element and exchange it with the first //element,putting the smallest element in its final position in //the sorted list. Then we scan the list,starting with the second //element,to find the smallest among the last n-1 elements //and exchange it with the second element,putting the second //smallest element in its final position. //Generally,on the ith pass through the list,which we number from 0 to //n-2,the algorithm searches for the smallest item among the n-i elements //and swap it with A. //After n-1 passes,the list is sorted.

package main

import (
    "fmt"
)
 //Sorts a given slice by selection sort //Input: A slice A[0..n-1] of orderable elements //Output: The original slice after sorted in nondecreasing order
func SelectionSort(A []int) []int {

    length := len(A)

    for i := 0; i < length-1; i++ {

        min := i

        for j := i + 1; j < length; j++ {

            if A[min] > A[j] {
                min = j
            }
        }

        A[i],A[min] = A[min],A[i]
    }

    return A
}

func main() {

    A := []int{1,10,9,8,7,44,2,3,33}

    fmt.Println("The slice before sorted : ",A)
    fmt.Println("The slice after sorted : ",SelectionSort(A))
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读