[Golang] Data structure-bubble sort

Source: Internet
Author: User

Break it up and read
No more classical sorting algorithms, the most likely first impression of a sort algorithm is it. I remember that the teacher took a class time to explain in detail when I was in college.

Principle
The bubbling algorithm (bubble sort) is a very simple sort of exchange. Each wheel starts with the first element, then swaps the larger value backward one bit until the entire queue is orderly.

Complexity of
As with other inefficient sorting algorithms, the average time complexity is O (n^2). The best case is that the original queue is a well-arranged array, and the time complexity is O (n). Space complexity is O (1) for Exchange.
The algorithm for sorting by comparison is stable, and so is the bubble sort.

Code

package mainimport (    "time"    "fmt"    "math/rand")func main() {    var length = 15    var list []int    // 以时间戳为种子生成随机数,保证每次运行数据不重复    r := rand.New(rand.NewSource(time.Now().UnixNano()))    for i := 0; i < length; i++ {        list = append(list, int(r.Intn(1000)))    }    fmt.Println(list)    // n-1轮,每轮减少一位的比较    for i := 1; i < length; i++ {        // 每轮都从第一个元素开始,将最大的值交换到最后一位        for j := 0; j < length-i; j++ {            if list[j] > list[j+1] {                list[j], list[j+1] = list[j+1], list[j]            }        }        fmt.Println(list)    }}

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.