Bubble sort is a sorting algorithm. It steps through the list iteratively and compares adjacent elements. It swaps the elements in case they are in the wrong order. The list is passed through iteratively until it is sorted and all numbers are at their correct location.
For a better understanding of the concept of how bubble sort works, an illustration is displayed. In this illustration, the given list, i.e., [5, 2, 4, 6, 1, 3], is unordered. The bubble sort algorithm is applied to sort the list.
The following code shows the implementation of bubble sort in Go.
package mainimport "fmt"func bubbleSort(arr []int) {n := len(arr)swapped := truem := 0for swapped {swapped = falsefmt.Println("iteration number: " ,m)for i := 1; i < n; i++ {if arr[i-1] > arr[i] {// Swap elements if they are in the wrong orderarr[i-1], arr[i] = arr[i], arr[i-1]swapped = true}}n-- // The largest element is now in its correct position, so reduce the length of the unsorted part of the arrayfmt.Println("Sorted array:", arr)m++}}func main() {arr := []int{5, 2, 4, 6, 1, 3}fmt.Println("Unsorted array:", arr)bubbleSort(arr)fmt.Println("The sorted array is:", arr)}
Line 5–29: The bubbleSort
function takes an integer slice as input and sorts it in ascending order using the bubble sort algorithm.
Line 10–28: The outer loop (for swapped
) runs until there are no more swaps in one pass, which indicates that the array is sorted.
Line 14–23: The inner loop (for i
) compares adjacent elements and swaps them if necessary.
The array is successfully sorted in ascending order using the bubble sort algorithm. Remember that bubble sort is not the most efficient sorting algorithm and has a time complexity of