Bubble Sort in Golang
Hey, fellow coders! Today I want to share with you a simple but useful algorithm: bubble sort in Go (Golang). Bubble sort is a sorting algorithm that works by repeatedly swapping adjacent elements in a slice until they are in the right order. It's not the fastest or the most efficient algorithm, but it's easy to understand and implement.
Here's how bubble sort works in Go:
func bubbleSort(arr []int)
? ? n := len(arr)
? ? for i := 0; i < n-1; i++ {
? ? ? ? for j := 0; j < n-i-1; j++ {
? ? ? ? ? ? if arr[j] > arr[j+1] {
? ? ? ? ? ? ? ? arr[j], arr[j+1] = arr[j+1], arr[j]
? ? ? ? ? ? }
? ? ? ? }
? ? }
}
You can test this function with some sample input:
func main()
? ? arr := []int{64, 25, 12, 22, 11}
? ? bubbleSort(arr)
? ? fmt.Println("Sorted array: ", arr)
}
That's it! Bubble sort is a simple but elegant algorithm that you can use to sort small slices in Go. For more details, you can watch the video I made here:
I hope you enjoyed this post and learned something new. If you have any questions or feedback, feel free to leave a comment below. Happy coding!