Close Menu
    Code and Debug
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook X (Twitter) Instagram YouTube WhatsApp
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook Instagram YouTube LinkedIn WhatsApp
    Code and Debug – BlogCode and Debug – Blog
    Code and Debug – BlogCode and Debug – Blog
    Home»Data Structures & Algorithms»Bubble Sort Algorithm in Python | Explained in Depth
    Data Structures & Algorithms

    Bubble Sort Algorithm in Python | Explained in Depth

    Anirudh KhuranaBy Anirudh Khurana29 May 2025No Comments4 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    Bubble Sort Algorithm in Python
    Share
    Facebook Twitter LinkedIn Pinterest Email

    Hi everyone! In this article, we’ll help you solve & understand bubble sort algorithm in Python like nowhere before. With it’s approach, code, explanation, dry run & complexity analysis.

    So let’s begin with the [Problem Link].

    Problem Statement

    Given an array, “arr[]”. Sort the array using bubble sort algorithm.

    Examples

    Example 1:
    
      Input: arr[] = [4, 1, 3, 9, 7]
      Output: [1, 3, 4, 7, 9]
    
    Example 2:
    
      Input: arr[] = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
      Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    
    Example 3:
    
      Input: arr[] = [1, 2, 3, 4, 5]
      Output: [1, 2, 3, 4, 5]
      Explanation: An array that is already sorted should remain unchanged after applying bubble sort.

    Constraints:

    • 1 <= arr.size() <= 103
    • 1 <= arr[i] <= 103

    Approach to Bubble Sort Algorithm in Python

    The bubble sort algorithm works by repeatedly comparing adjacent elements in the array & swapping them if they are in the wrong order.

    This process is repeated for every element. Ensuring that after each pass, the largest unsorted element is “bubbled” to its correct position. The algorithm continues until the array is sorted.

    Key Steps in the Approach:

    1. Start with the first element and compare it with the next
    2. If the current element is greater than the next, swap them
    3. Move to the next pair of elements and repeat the process for the entire array
    4. After each pass, the largest unsorted element is placed at its correct position
    5. Reduce the range of comparison for subsequent passes as the largest elements are already sorted
    6. Repeat this process until no swaps are needed or the array is sorted

    Also read about the Python Program for Selection Sort Algorithm.

    Code

    class Solution:
        # Function to sort the array using bubble sort algorithm.
        def bubbleSort(self, arr):
            n = len(arr)
            for i in range(n - 2, -1, -1):
                for j in range(0, i + 1):
                    if arr[j] > arr[j + 1]:
                        arr[j], arr[j + 1] = arr[j + 1], arr[j]

    Code Explanation

    1. Class & Function Definition:
      1. A class Solution is defined, which contains the method “bubbleSort”
      2. The function takes one parameter, “arr”, which is the array to be sorted
    2. Initialization: n = len(arr): The length of the array is stored in the variable “n”
    3. Outer Loop (for i in range(n – 2, -1, -1)):
      1. This loop controls the number of passes through the array
      2. It runs from n-2 to 0 (inclusive), ensuring that with each iteration, the unsorted portion of the array reduces by one
    4. Inner Loop (for j in range(0, i + 1)):
      1. This loop iterates through the unsorted portion of the array
      2. “j” starts from the beginning of the array and goes up to the last unsorted element (i + 1)
    5. Comparison (if arr[j] > arr[j + 1]): Adjacent elements are compared to check if they are in the wrong order (i.e., the current element is greater than the next)
    6. Swapping (arr[j], arr[j + 1] = arr[j + 1], arr[j]): If the elements are out of order, they are swapped using Python’s tuple unpacking
    7. Termination: After the outer loop completes all passes, the array is sorted

    Dry Run

    Iteration 1:Dry Run of Bubble Sort Algorithm in Python (Iteration 1)

    Iteration 2:

    Dry Run of Bubble Sort Algorithm in Python (Iteration 2)

    Iteration 3:

    Dry Run of Bubble Sort Algorithm in Python (Iteration 3)

    Iteration 4:

    Dry Run of Bubble Sort Algorithm in Python (Iteration 4)

    Iteration 5:

    Dry Run of Bubble Sort Algorithm in Python (Iteration 5)

    Complexity Analysis

    1. Time Complexity:
      • Worst Case: O(n2), when the array is in reverse order and every element needs to be compared and swapped
      • Best Case: O(n2), as the given code does not include an optimization to exit early when the array is already sorted
      • Average Case: O(n2)
    2. Space Complexity:
      • The algorithm operates in-place, meaning no extra memory is used apart from a few variables
      • Space Complexity: O(1)

    For any changes to the document, kindly email at code@codeanddebug.in or contact us at +91-9712928220.

    Array Sorting Algorithm
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticlePython Program to Find Factorial of Number Using Recursion
    Next Article Word Ladder II | Leetcode 126 | Shortest Transformation Sequences with BFS
    Anirudh Khurana
    • Website

    Anirudh Khurana is the founder of Code and Debug, an Indian EdTech platform that helps students and working professionals crack coding interviews and move into data and AI roles. He teaches DSA, Python, SQL, data engineering and machine learning through live bootcamps and his YouTube channel, Code and Debug, which has over 50,000 subscribers. Every guide on this blog is written or reviewed by him and tested with real code.

    Related Posts

    Data Structures & Algorithms

    DSA Interview Cheat Sheet: All Patterns You Need to Know

    4 April 2026
    Data Structures & Algorithms

    Symmetric Tree | Leetcode 101 | Recursive DFS Approach

    2 September 2025
    Data Structures & Algorithms

    Binary Tree Right Side View | Leetcode 199 | BFS and DFS Approaches

    2 September 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Categories
    • AI & Machine Learning (4)
    • Data Structures & Algorithms (241)
      • Beginner (82)
      • Expert (52)
      • Intermediate (106)
    • Pandas (1)
    • Python (1)
    • Resume (1)
    • SQL (1)
    Recent Posts

    Confusion Matrix in Machine Learning: An Interactive Guide

    21 October 2026

    100 SQL Interview Questions with Queries and Answers (Freshers to Experienced)

    17 October 2026

    Logistic Regression in Machine Learning: Explained Visually (with Python)

    17 October 2026

    Linear Regression in Machine Learning: Explained Visually (with Python)

    17 October 2026

    100 Python Interview Questions and Answers for Freshers and Experienced (Free PDF)

    17 October 2026
    Facebook Instagram YouTube LinkedIn WhatsApp
    © 2025 Code and Debug. All rights reserved.

    Type above and press Enter to search. Press Esc to cancel.