The implementation of bubble sort in go language learning notes

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Bubble sort (Bubble sort), is a Computer Science The more simple areas of Sorting Algorithms .

Algorithm principle

The bubbling sorting algorithm works as follows:
    1. Compares the adjacent elements. If the first one is bigger than the second one, swap them both.
    2. Do the same for each pair of adjacent elements, starting with the last pair from the first pair to the end. At this point, the last element should be the maximum number.
    3. Repeat the above steps for all elements, except for the last one.
    4. Repeat the above steps each time for less and fewer elements until there are no pairs of numbers to compare

Algorithm stability


Bubble sort is an in-place sort, and it is stable.

Algorithm description

Go Language

Package bubblesort//Bubble sort func bubblesort (values []int) {flag: = truefor I: = 0; i < len (values)-1; i++ {flag = truefor J : = 0; J < Len (values)-i-1; J + + {if values[j] > values[j+1] {values[j], values[j+1] = values[j+1], Values[j]flag = false}}if Flag = = true {Break}}}
Test Case:

Package Bubblesortimport "Testing"//bubble Sort test func TestBubbleSort1 (t *testing. T) {values: = []int{5, 4, 3, 2, 1}bubblesort (values) if VALUES[0]!! = 1 | | values[1]! = 2 | | values[2]! = 3 | | values[3]! = 4 | | VALUES[4]! = 5 {t.error ("Bubblesort () failed Got", values, "expected 1 2 3 4 5")}}func TestBubbleSort2 (t *testing. T) {values: = []int{5, 5, 3, 2, 1}bubblesort (values) if VALUES[0]!! = 1 | | values[1]! = 2 | | values[2]! = 3 | | values[3]! = 5 | | VALUES[4]! = 5 {t.error ("Bubblesort () failed. Got ", Values," expected 1 2 3 5 5 ")}}func TestBubbleSort3 (t *testing. T) {values: = []int{5}bubblesort (values) if values[0]! = 5 {t.error ("Bubblesort () failed. Got ", Values," expected 5 ")}}


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.