Bubble Sort

 Bubble Sort

  • What is Bubble Sort?
    Bubble Sort is a way to arrange a list of numbers (or items) in order, either from smallest to largest (ascending) or largest to smallest (descending).

  • How does it work?
    Imagine bubbles in water. The bigger bubbles float up, and smaller bubbles sink down. In Bubble Sort, we compare two numbers at a time and swap them if they’re in the wrong order.

  • Step-by-step process:

    • Start with the first two numbers in the list.
    • Compare them:
      • If the first number is bigger than the second, swap them.
      • If the first number is smaller, leave them as is.
    • Move to the next two numbers and repeat.
    • Do this for the whole list.

    After one pass through the list, the biggest number will have "bubbled up" to its correct spot at the end.

    Repeat the process for the remaining part of the list (ignoring the last sorted numbers each time) until everything is sorted.

  • Example:
    List: [5, 3, 8, 4]

    • Compare 5 and 3 → Swap → [3, 5, 8, 4]
    • Compare 5 and 8 → No Swap → [3, 5, 8, 4]
    • Compare 8 and 4 → Swap → [3, 5, 4, 8]
      First pass done. Biggest number (8) is now in its place.

    Second pass: [3, 5, 4, 8]

    • Compare 3 and 5 → No Swap
    • Compare 5 and 4 → Swap → [3, 4, 5, 8]
      Second pass done. Now, the second biggest number (5) is in place.

    Keep repeating until sorted: [3, 4, 5, 8].

  • Key idea:
    Compare, swap if needed, and keep going until the list is fully sorted!

  • Comments

    Popular posts from this blog

    Programming Notes by Atul Kalukhe