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:
- Compares the adjacent elements. If the first one is bigger than the second one, swap them both.
- 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.
- Repeat the above steps for all elements, except for the last one.
- 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 ")}}