[Golang] Data structure-simple selection sorting

Source: Internet
Author: User

Principle
Simple selection of sorting should be the most intuitive and easy to understand sorting method.
Directly from the beginning of one to go than, find the smallest to put to the far left. Then finish sorting the other bits in turn.

Complexity of Time
The number of comparisons is fixed to O (n^2) and the number of data exchanges is 0~n-1 times
Select sort is not stable because data is exchanged for the same values in different locations

Code implementation

package mainimport (    "fmt")func main() {    var length = 10    var mm = make(map[int]int, length)    var o []int    // 先准备一个顺序随机的数(qie)组(pian)    for i := 0; i < length; i++ {        mm[i] = i    }    for k, _ := range mm {        o = append(o, k)    }    fmt.Println(o)    // 两次循环找到最小的排前面    for i := 0; i < length; i++ {        min := i        for j := length - 1; j >= i; j-- {            if o[j] < o[min] {                min = j            }        }        // 当前就是最小值时就不交换了        if min == i {            continue        }        // 顺序交换        o[i] = o[i] + o[min]        o[min] = o[i] - o[min]        o[i] -= o[min]        fmt.Println(o)    }}

Run results

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.