Cada bucle externo de ordenación de burbujas organiza el valor máximo actual (valor mínimo) en la posición correspondiente.
Por ejemplo, la burbuja ordena los datos de la matriz[10] de pequeño a grande
El primer bucle almacenará el valor máximo en la ubicación de los datos[9]
El segundo bucle almacenará el valor máximo restante en la ubicación de los datos[8]
package main
import (
"fmt"
"math/rand"
"time"
)
//Arrange from small to large
func bubbleSort(data []int) {
size := len(data)
/*
Outer loop, bubbling in inner loop for each position from the far right to the far left in turn
In the first loop, store the maximum value to the rightmost position
In the second loop, the second largest value is stored in the second position on the far right
...
*/
for i := 0; i < size; i++ {
/*
Memory loop, bubbling, from data[0] to data[size-1-i]
Use data[j] and data[j+1] to compare each time
If data[j]> data[j+1], swap the positions
Make sure the largest number bubble up
*/
for j := 0; j < size-1-i; j++ {
if data[j] > data[j+1] {
data[j], data[j+1] = data[j+1], data[j]
}
}
}
}
func main() {
rand.Seed(time.Now().UnixNano() / 1000)
arr := [100]int{}
for i := 0; i < 100; i++ {
arr[i] = rand.Intn(1000)
}
fmt.Println(arr)
bubbleSort(arr[:])
fmt.Println(arr)
}
.