#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 →
×

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.

Ready to master Data Structures & Algorithms?

Learn DSA hands-on with mentor-led sessions, real interview practice, and placement support.

Explore Course