Bubble sort in Go

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.

Understanding the concept

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.

1 of 21

Implementation of bubble sort

The following code shows the implementation of bubble sort in Go.

package main
import "fmt"
func bubbleSort(arr []int) {
n := len(arr)
swapped := true
m := 0
for swapped {
swapped = false
fmt.Println("iteration number: " ,m)
for i := 1; i < n; i++ {
if arr[i-1] > arr[i] {
// Swap elements if they are in the wrong order
arr[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 array
fmt.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)
}

Code explanation

  • 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 O(n2)O(n^2)The space complexity of bubble sort is O(1)O(1). For larger datasets, more efficient sorting algorithms like merge sort or quicksort are preferred.

Copyright ©2024 Educative, Inc. All rights reserved