Bubble Sorting

Priya LallPriya Lall
1 min read

Bubble Sort is a simple sorting algorithm that works by repeatedly swapping adjacent elements if they are in the wrong order.

Think of it like bubbling up the largest element to the end in each round — just like bubbles rising to the top of water.

How It Works

  1. Outer Loop: Runs n−1n-1n−1 times, ensuring all elements are sorted.

  2. Inner Loop: Compares adjacent elements and swaps them if necessary.

  3. Optimization: If no swaps occur in a full pass, the array is already sorted, and we exit early.

C# Bubble Sort with Two for Loops

Step-by-Step Explanation

Let's take an example array:
[5, 3, 8, 4, 2]

Step 1: Outer Loop (Passes)

The outer for loop runs multiple passes to ensure the array is sorted.

  • Pass 1: Moves the largest number to the correct position.

  • Pass 2: Moves the second-largest number to its correct position.

  • Pass 3: Continues moving elements into place.

  • Pass 4: Finishes sorting.

Step 2: Inner Loop (Comparisons & Swaps)

The inner loop:

  1. Compares adjacent elements.

  2. Swaps them if they are in the wrong order.

  3. Repeats until the largest element reaches the correct place.

Visual Representation

Pass1

Pass 2

Pass 3

0
Subscribe to my newsletter

Read articles from Priya Lall directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Priya Lall
Priya Lall