Bubble sort

Bubble Sort

Generate Random Numbers

How to use ?

Enter an array separated by commas as : 16,15,15,10,1 or just press the hand icon to generate a random array then press enter or Sort button. Sorting will start and you can watch each pass as it gets sorted. When it shows green it means the two of them are being compared when red shows, it means the left number is greater than right number so it needs swapping The blue color means the number is at its correct position and thus sorted it will continue to check other numbers until it reaches end.

Bubble Sort Overview

History

Bubble sort is one of the simplest sorting algorithms, often introduced in computer science education. It was first documented in the 1950s and has been widely used in programming for educational purposes due to its straightforward concept.

Current Uses

  • Educational Purposes: Commonly used to teach the basics of sorting algorithms.
  • Small Data Sets: Occasionally used for small datasets where efficiency is not a concern.
  • Data Analysis: Sometimes utilized in data analysis tasks when simplicity is preferred.

Time and Space Complexity

Time Complexity

  • Best Case: O(n) – When the array is already sorted.
  • Average Case: O(n2) – Quadratic complexity for average cases.
  • Worst Case: O(n2) – When the array is sorted in reverse order.

Space Complexity

Space Complexity: O(1) – It is an in-place sorting algorithm requiring a constant amount of additional space.

Pseudo Code

function bubbleSort(arr):
    n = length(arr)
    for i from 0 to n-1:
        for j from 0 to n-i-1:
            if arr[j] > arr[j + 1]:
                // swap arr[j] and arr[j + 1]
                temp = arr[j]
                arr[j] = arr[j + 1]
                arr[j + 1] = temp
    return arr

Key Characteristics

  • Stability: Bubble sort is a stable sorting algorithm.
  • Adaptability: Performs better on nearly sorted datasets.

Summary

Bubble sort is an easy-to-understand sorting algorithm that works by repeatedly swapping adjacent elements. While it is inefficient for large datasets with its O(n2) worst-case complexity, its simplicity makes it suitable for educational purposes.

Bubble Sort Code Implementation