Bubble sort has a time complexity of , making it inefficient for large datasets but useful for small or nearly sorted lists.
Key takeaways:
Bubble sort follows a comparative approach, iterating over the list and swapping out-of-order elements.
It has a time complexity of
, making it less efficient for large datasets. Go is a great language to implement sorting algorithms due to its simplicity and performance characteristics.
Bubble sort compares adjacent elements and swaps them if they are in the wrong order repeatedly throughout the array. It continues until the entire array is sorted, ensuring that larger elements are at the end of the array.
Bubble sort is a very simple algorithm designed to compare adjacent elements in a list and swap them if they are not in the correct order. Although it’s not the most efficient sorting method, it’s an excellent algorithm for beginners to grasp fundamental sorting concepts.
For a better understanding of the concept of how bubble sort works, an illustration is displayed. In this illustration, the given list, i.e.,
Now that we understand the basic concept, let’s implement 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
To further enhance your knowledge and skills in coding interviews, we recommend a specially designed path, Educative 99. This path offers interactive lessons that give hands-on experience with coding problems and opportunities to test and refine your solutions.
The time complexity of the algorithm is
Its space complexity is
Understanding these algorithms and patterns can be a game changer if you’re prepping for technical interviews. For LeetCode pattern-based problems, check out our course on "Coding Interview Patterns."
Haven’t found what you were looking for? Contact Us
Free Resources