#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 in Data Structure

Bubble Sort is one of the simplest sorting algorithms taught in data structures. It repeatedly compares adjacent elements in an array and swaps them if they are out of order, causing larger values to 'bubble up' toward the end of the array with each pass.

Dry Run Example

Sorting [5, 3, 8, 1]: Pass 1 compares (5,3)→swap, (5,8)→no swap, (8,1)→swap, giving [3, 5, 1, 8]. Pass 2 compares (3,5)→no swap, (5,1)→swap, giving [3, 1, 5, 8]. Pass 3 compares (3,1)→swap, giving the fully sorted [1, 3, 5, 8].

def bubble_sort(arr):
    n = len(arr)
    for i in range(n - 1):
        for j in range(n - 1 - i):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
    return arr

Complexity

CaseTime
Best (with early-exit flag)O(n)
Average/WorstO(n²)

Where It Fits in DSA

  • Commonly used as the first sorting algorithm taught due to its intuitive logic.
  • Rarely used in production code due to poor performance on large datasets.
  • Useful for teaching concepts like stability and in-place sorting.

Ready to master Data Structures & Algorithms?

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

Explore Course