Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to insert sorting directly into golang

2025-04-05 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

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!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report