DEV Community

Ajith R
Ajith R

Posted on

Bubble Sort

Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted. It is named for the way smaller elements "bubble" to the top of the list with each iteration.

Algorithm:

  1. Start from the beginning of the list.
  2. Compare each pair of adjacent elements.
  3. If the elements are in the wrong order, swap them.
  4. Repeat this process for each pair of adjacent elements until no swaps are needed, indicating that the list is sorted.

JavaScript Implementation:

function bubbleSort(arr) {
    let n = arr.length;
    let swapped;
    do {
        swapped = false;
        for (let i = 0; i < n - 1; i++) {
            if (arr[i] > arr[i + 1]) {
                let temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;
                swapped = true;
            }
        }
    } while (swapped);
    return arr;
}
Enter fullscreen mode Exit fullscreen mode

Advantages of Bubble Sort:

  1. Simplicity: Bubble sort is straightforward to understand and implement. It involves simple logic and requires minimal auxiliary data structures.

  2. Ease of Implementation: It is easy to implement in various programming languages due to its simplicity and intuitive nature.

  3. Space Efficiency: Bubble sort operates in-place, meaning it does not require additional memory beyond the input array. This makes it memory efficient for sorting small datasets or when memory usage is a concern.

Disadvantages of Bubble Sort:

  1. Inefficiency: Bubble sort has poor time complexity, especially for large datasets. Its average and worst-case time complexity is O(n^2), making it inefficient for sorting large arrays.

  2. Performance: Due to its quadratic time complexity, bubble sort is not suitable for sorting large or nearly sorted arrays. It performs poorly compared to more efficient sorting algorithms such as quicksort or mergesort.

  3. Stability: While bubble sort is stable (i.e., it preserves the relative order of equal elements), its performance limitations often outweigh this advantage in practical applications.

Conclusion:

https://github.com/ajithr116/Data-Structures/tree/main/06-sorting/bubblesort is a simple and intuitive sorting algorithm with advantages in simplicity and ease of implementation. However, its inefficiency and poor performance for large datasets limit its practical use in most scenarios. While bubble sort may be suitable for educational purposes or small datasets, more efficient sorting algorithms are preferred for real-world applications.


Top comments (0)