Get the App
SLTechnology News&Howtos  ›  Development  › 

How to insert sorting directly into golang

Shulou Source: shulou.com Published: 2022-06-02 06:40:39 10月18日 Update

This article mainly introduces how to insert golang directly into the sort, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

Principle

Direct insertion sorting is also a very simple sorting algorithm.

The first round starts with the second element, compares it with the first one, swaps positions if it is smaller, and the current round ends. The second round starts with the third element, first compares with the second, if smaller, exchanges with the second, and then compares with the first. This loop until the last element completes the comparison logic.

Complexity

In the best case, the direct insertion sort only needs to be compared once and exchanged 0 times. The average time complexity is O (n ^ 2).

Because each element is compared to an ordered queue one by one, elements with the same value do not swap positions after sorting is complete. Therefore, direct insertion sorting 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) }} 运行结果

Thank you for reading this article carefully. I hope the article "how to insert golang directly into sorting" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Tags: Sort element article complexity location complexity algorithm order same three code value interest principle just at the same time case value time more Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB Shulou Information NVidia Shulou Technology Docker