In this tutorial, we’ll explore how to implement the Bubble Sort algorithm in Golang. Bubble Sort is a straightforward sorting technique that compares adjacent elements in an array and swaps them if they are in the wrong order.
What’s Inside
Understanding Bubble Sort
Bubble Sort follows a simple set of rules:
- Step 1: Start from the left-hand side of the array.
- Step 2: Compare the first two numbers at index 0 and 1.
- Step 3: If
a[0]
is greater thana[1]
, swap their positions. Ifa[0]
is less thana[1]
, no swap is needed, and move on to compare the next two numbers (a[1]
anda[2]
). - Step 4: Repeat Step 3 until there are no more numbers left to compare.
This process continues until the entire array is sorted. At the end of the first pass, the last element will have the maximum value in the list.
Golang Bubble Sort Implementation
Let’s dive into the Golang implementation:
package main import "fmt" func main() { a := []int{31, 8, 6, 54, 95, 84, 71, 67} fmt.Printf("Original Array: %v\n", a) lenArr := len(a) - 1 for i := 0; i < lenArr; i++ { for j := 0; j < lenArr-i; j++ { fmt.Printf("Comparing %v and %v\n", a[j], a[j+1]) if a[j] > a[j+1] { // Swap elements tmp := a[j] a[j] = a[j+1] a[j+1] = tmp } } fmt.Printf("\nIteration %v\n", i+1) fmt.Printf("Sorted Array: %v\n", a) } fmt.Printf("\nFinal Sorted Array: %v\n", a) }
Time Complexity
The time complexity of Bubble Sort is Ω(n) in the best case and O(n^2) in the worst case.
That’s it! You’ve just created a simple Bubble Sort implementation in Golang. Feel free to experiment with different arrays to see the sorting in action.
You May Also Like: