[Golang] Data structure-Direct insert sort

Source: Internet
Author: User

Principle
Direct insertion of sorting is also a very simple sorting algorithm.
The first round starts with the second element, and the first compares, if smaller, the swap position, the end of this round. The second round starts with the third element, compared with the second one, if smaller is the second interchange, and then the first comparison. This loops until the last element completes the comparison logic.

Complexity of
In the best case, the direct insertion of the sort requires only a n-1 comparison, 0 times of exchange. The average time complexity is O (n^2).
Because each element is compared to an ordered queue, elements that do not appear to have the same numeric value swap positions after sorting is complete. So the direct insert sort is a stable sorting algorithm.

Code

package mainimport (    "fmt"    "math/rand")func main() {    var length = 10    var tree []int    for i := 0; i < length; i++ {        tree = append(tree, int(rand.Intn(1000)))    }    fmt.Println(tree)    for i := 1; i < length; i++ {        for j := i; j > 0 && tree[j] < tree[j-1]; j-- {            tree[j], tree[j-1] = tree[j-1], tree[j]        }        fmt.Println(tree)    }}

Run results

Related Article

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.