bubbleSort.definition

bubbleSort.descriptionPart1

bubbleSort.descriptionPart2

bubbleSort.keyPointsTitle

  • bubbleSort.keyPoint1
  • bubbleSort.keyPoint2
  • bubbleSort.keyPoint3
  • bubbleSort.keyPoint4

bubbleSort.exampleTitle

Start:
51428
Pass 1:
14258
Sorted:
12458

bubbleSort.syntaxTitle

// Java
public static void bubbleSort(int[] arr) {
    int n = arr.length;
    for (int i = 0; i < n - 1; i++) {
        boolean swapped = false;
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                // Swap
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
                swapped = true;
            }
        }
        if (!swapped) break; // Optimized
    }
}
# Python
def bubble_sort(arr):
    n = len(arr)
    for i in range(n - 1):
        swapped = False
        for j in range(n - i - 1):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
                swapped = True
        if not swapped:
            break  # Optimized
// C++
void bubbleSort(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        bool swapped = false;
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                swap(arr[j], arr[j + 1]);
                swapped = true;
            }
        }
        if (!swapped) break; // Optimized
    }
}
// JavaScript
function bubbleSort(arr) {
  const n = arr.length;
  for (let i = 0; i < n - 1; i++) {
    let swapped = false;
    for (let j = 0; j < n - i - 1; j++) {
      if (arr[j] > arr[j + 1]) {
        [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
        swapped = true;
      }
    }
    if (!swapped) break; // Optimized
  }
  return arr;
}

Interactive Bubble Sort Visualization

📊

Enter numbers above and click "Create Array" to begin.

Pass: 0Comparisons: 0Elements: 0
Idle
Comparing
Swapping
Sorted

Note: Bubble Sort compares adjacent elements and swaps them if they are in the wrong order. The algorithm uses an optimized early-exit when no swaps occur in a pass.

Time & Space Complexity

CaseComplexityDescription
Best CaseO(n)Array is already sorted (with early-exit optimization)
Average CaseO(n²)Random order requires multiple passes and comparisons
Worst CaseO(n²)Array is sorted in reverse order
SpaceO(1)In-place sorting, only uses a few variables

Comparisons: In the worst case, Bubble Sort makes n(n-1)/2 comparisons.

Swaps: In the worst case, it performs n(n-1)/2 swaps.

Stability: Bubble Sort is a stable sorting algorithm (equal elements maintain their relative order).

enhanced.relatedTopics.prerequisites

enhanced.relatedTopics.related

enhanced.relatedTopics.advanced

bubbleSort.continueLearning

enhanced.author.title

enhanced.author.writtenBy:enhanced.author.teamName
enhanced.author.reviewedBy:enhanced.author.reviewerName
enhanced.author.lastUpdated:January 28, 2026