#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Sorting Algorithms

Bubble Sort Algorithm

Bubble Sort repeatedly steps through the array, compares adjacent elements, and swaps them if they are in the wrong order. Larger elements 'bubble' to the end of the array with each pass.

Algorithm Steps

  • Compare each pair of adjacent elements from the start of the array.
  • Swap them if the left element is greater than the right one.
  • Repeat for the entire array; after each pass, the largest unsorted element settles at the end.
  • Stop early if a pass completes with no swaps (array is already sorted).
def bubble_sort(arr):
    n = len(arr)
    for i in range(n - 1):
        swapped = False
        for j in range(n - 1 - i):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
                swapped = True
        if not swapped:
            break
    return arr

print(bubble_sort([5, 1, 4, 2, 8]))

Complexity

CaseTimeSpace
Best (already sorted, with flag)O(n)O(1)
AverageO(n²)O(1)
WorstO(n²)O(1)

Key Characteristics

  • Stable sort — equal elements retain their relative order.
  • Simple to implement, but inefficient for large datasets compared to Merge Sort or Quick Sort.
  • Mainly used for teaching sorting concepts and for very small or nearly-sorted datasets.

Pass-by-Pass Trace of [5, 1, 4, 2, 8]

Following the sample input through each pass shows the early-exit flag earning its keep.

PassComparisonsSwapsArray after the pass
143 (5↔1, 5↔4, 5↔2)[1, 4, 2, 5, 8]
231 (4↔2)[1, 2, 4, 5, 8]
320[1, 2, 4, 5, 8], loop stops

The array was sorted after pass 2, but the algorithm only knows that once a pass finishes with no swaps, so pass 3 confirms it. Without the flag, a fourth pass would run for nothing. In total, nine comparisons were made instead of the ten a plain version would perform.

Counting the Work

In the worst case, the first pass compares n − 1 pairs, the next n − 2, and so on down to 1. The total is n(n − 1)/2 comparisons, which is where the quadratic time comes from. A reversed array also needs one swap for every comparison, so a list of 1,000 reversed items needs roughly half a million swaps. That is the clearest reason the algorithm is avoided for large data.

Shrinking the range with the last swap

A smarter variant remembers where the last swap happened. Everything after that point is already in its final place, so the next pass can stop there instead of reducing the range by just one.

def bubble_sort_last_swap(arr):
    n = len(arr)
    while n > 1:
        last_swap = 0
        for j in range(1, n):
            if arr[j - 1] > arr[j]:
                arr[j - 1], arr[j] = arr[j], arr[j - 1]
                last_swap = j
        n = last_swap          # 0 means no swaps, loop ends
    return arr

print(bubble_sort_last_swap([3, 2, 1, 4, 5, 6, 7]))

For the input above, the first pass ends with its last swap near the front, so the second pass covers only two elements instead of six.

Cocktail shaker sort

Another variant alternates direction: left to right, then right to left. It fixes the "turtle" problem, where a small value near the end moves only one step left per pass in normal bubble sort.

Bubble, Selection and Insertion Sort Compared

PropertyBubbleSelectionInsertion
Best caseO(n) with flagO(n²)O(n)
Worst caseO(n²)O(n²)O(n²)
StableYesNo in the usual array versionYes
SwapsManyAt most n − 1Shifts instead of swaps

In practice insertion sort usually beats bubble sort on the same data, and selection sort is preferred only when writes are very costly.

Errors Beginners Make

  • Looping the inner index to n - i instead of n - 1 - i, which reads past the end with arr[j + 1].
  • Resetting the swapped flag outside the outer loop, so the early exit never triggers.
  • Using >= in the comparison, which swaps equal items and makes the sort unstable.
  • Forgetting that the list is sorted in place, then being surprised that the original order is gone.

Takeaway: learn bubble sort for the idea of adjacent swaps and stability, then use your language's built-in sort for real work.