Golang Insertion Sorting algorithm

Source: Internet
Author: User

Insertion Sorting algorithm principle:
The sequence takes a number from the sequence and compares it to the element on the left, and if the left element is larger than the number taken, move to the right until the number is inserted at a position not less than the left element. Sort of points similar to poker.

package mainimport "fmt"func main() {    numbers := []int{6, 2, 7, 3, 8, 5}    InsertSort(numbers)    fmt.Println(numbers)}func InsertSort(values []int) {    length := len(values)    if length <= 1 {        return    }    for i := 1; i < length; i++ {        tmp := values[i] // 从第二个数开始,从左向右依次取数        key := i - 1     // 下标从0开始,依次从左向右        // 每次取到的数都跟左侧的数做比较,如果左侧的数比取的数大,就将左侧的数右移一位,直至左侧没有数字比取的数大为止        for key >= 0 && tmp < values[key] {            values[key+1] = values[key]            key--            //fmt.Println(values)        }        // 将取到的数插入到不小于左侧数的位置        if key+1 != i {            values[key+1] = tmp        }        //fmt.Println(values)    }}

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.