A drop in the universe 2022-01-26 15:00:03 阅读数:432
Bubble sort is the simplest exchange sort algorithm .
What exchange is ? Exchange is to compare two by two , If the order is not satisfied, you can exchange positions . such as , We want to sort from small to large , Compare the values in two positions , If it's in reverse order, it's swapped , Make records with large keywords pop up like bubbles and put them at the end .
Repeat bubble sort several times , Finally, we get an ordered sequence .
The name of bubble sort comes from : Elements with smaller values are like ” Bubble “ Gradually float to the top of the sequence .
If the element size relationship is incorrect , Exchange these two numbers ( In this case a> b),
Given an array 29, 10, 14, 37, 14, 48, 17
, The bubble sorted animation is shown below :
package main
import "fmt"
func main() {
// index starts from 0
var nums = [] int{ 29, 10, 14, 37, 14, 48, 17}
var length = len( nums)
fmt . Println( " Original array :", nums)
bubbleSort( nums, length)
fmt . Print( " After array sorting :")
for i : = 0; i < length; i ++ {
fmt . Printf( "%d\t", nums[ i])
}
}
func bubbleSort( nums [] int, length int) {
for i : = 0; i < length - 1; i ++ {
for j : = 0; j < length - i - 1; j ++ {
if nums[ j] > nums[ j + 1] { // If big , In exchange for
var temp = nums[ j] // Temporary variables save the previous value
nums[ j] = nums[ j + 1]
nums[ j + 1] = temp
}
}
}
}
Run the above code , You can see the result of sorting :
[ Running] go run "e:\Coding Workspaces\LearningGoTheEasiestWay\Go data structure \ Bubble sort \main.go"
Original array : [ 29 10 14 37 14 48 17]
After array sorting : 10 14 14 17 29 37 48
A flag can be attached to improve the algorithm , During sorting , If there is no swap operation, it means that the sorting is completed . If the sequence is already ordered , You can end the algorithm by judging the flag .
func bubbleSortImproved( nums [] int, length int) {
swapped : = true
for i : = 0; i < length - 1 && swapped; i ++ {
swapped = false
for j : = 0; j < length - i - 1; j ++ {
if nums[ j] > nums[ j + 1] { // If big , In exchange for
var temp = nums[ j] // Temporary variables save the previous value
nums[ j] = nums[ j + 1]
nums[ j + 1] = temp
swapped = true
}
}
}
}
In the best case , The time complexity of the improved bubbling algorithm is .
The advantage of comparing other sorting algorithms is , It can detect whether the input sequence is already sorted .
The time complexity of bubble sort is ( Even in the best of circumstances ), The space complexity is
.
Bubble sorting is also a stable algorithm .
copyright:author[A drop in the universe],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/01/202201261500001488.html