VOOZH about

URL: https://www.analyticsvidhya.com/blog/2023/12/bubble-sort-in-python/

⇱ Bubble Sort in Python: Program, Complexity, Working


India's Most Futuristic AI Conference Is Back – Bigger, Sharper, Bolder

  • d
  • :
  • h
  • :
  • m
  • :
  • s

Bubble Sort in Python: Program, Complexity, Working

Pankaj Singh Last Updated : 29 May, 2025
5 min read

Introduction

Bubble Sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. While it may not be the most efficient sorting algorithm for large datasets, it is easy to understand and implement, making it a valuable learning tool for beginners. In this comprehensive guide, we’ll explore the principles behind Bubble Sort and provide a step-by-step implementation in Python.

Bubble Sort Algorithm

Bubble Sort is a comparison-based algorithm that repeatedly compares adjacent elements and swaps them if they are in the wrong order. This process is repeated until the entire list is sorted. The algorithm gets its name from how smaller elements β€œbubble” to the top of the list during each iteration.

Bubble Sort Program in Python

To implement Bubble Sort in Python, we follow a step-by-step algorithm. First, we compare adjacent elements and swap them if necessary. We repeat this process for each pair of adjacent elements until the entire list is sorted. We provide a code example below to illustrate the implementation.

Below is a simple implementation of the Bubble Sort algorithm in Python:

def bubble_sort(arr):

    n = len(arr)

    for i in range(n):

        for j in range(0, n-i-1):

            if arr[j] > arr[j+1]:

                arr[j], arr[j+1] = arr[j+1], arr[j]

    return arr

# Example usage

my_list = [64, 34, 25, 12, 22, 11, 90]

sorted_list = bubble_sort(my_list)

print(sorted_list)

Time Complexity Analysis of Bubble Sort

The time complexity of Bubble Sort is O(n^2), where n is the number of elements in the list. This means the algorithm’s performance decreases significantly as the list size increases. However, Bubble Sort can be efficient for small datasets or partially sorted lists.

How Bubble Sort Works in Python

To implement Bubble Sort in Python, we compare and swap the first two elements if necessary. We then move to the next pair of elements and continue this process until the end of the list. This constitutes one pass. We repeat this process for multiple passes until the list is completely sorted.

Here is the illustration of how Bubble Sort works

Step 1: Our input Array is {7,4,1,6}

πŸ‘ Bubble Sort in Python

Step 2:

πŸ‘ Bubble Sort in Python

Step 3:

πŸ‘ Bubble Sort in Python

Optimizing Bubble Sort in Python

While Bubble Sort is not the most efficient sorting algorithm, several optimization techniques can improve its performance. Here, you will learn about the 3 bubble sorting techniques: Flagged Bubble Sort, Recursive Bubble Sort, and Cocktail Shaker Sort.

  1. Flagged Bubble Sort uses a flag to track whether swaps were made during a pass. If no swaps occur, the list is sorted, and we can terminate the algorithm early.
  2. Recursive Bubble Sort is a variation of Bubble Sort that uses recursion to sort the list. It divides the list into two parts: the first element and the remaining unsorted list. It then recursively sorts the remaining list until the entire list is sorted.
  3. Cocktail Shaker Sort, also known as Bidirectional Bubble Sort, is an optimized version of Bubble Sort that sorts the list in both directions. This reduces the required passes and can improve the algorithm’s performance.

Bubble Sort Applications and Use Cases

Bubble Sort can be applied in various scenarios where sorting is required. It is commonly used for sorting lists, arrays, and data structures such as linked lists and binary trees. Additionally, Bubble Sort can handle large datasets, although its performance may be slower than that of more efficient sorting algorithms. Here are the applications of Bubble Sort:

  1. Sorting Lists and Arrays: Bubble Sort can sort lists and arrays of any data type. It is particularly useful when the list is small or partially sorted.
  2. Sorting Data Structures: Bubble Sort can be applied to sort data structures like linked lists and binary trees. However, its performance may not be optimal for large data structures.
  3. Sorting Large Datasets: While Bubble Sort is not the most efficient algorithm for sorting large datasets, it can still be used if performance is not critical. However, it is recommended that more efficient sorting algorithms for large datasets be considered.

Bubble Sort vs Other Sorting Algorithms

Sorting algorithms are essential in computer science, and various algorithms have been developed to organize data efficiently. To understand their differences and performance characteristics, let’s compare Bubble Sort with a few other popular sorting algorithms.

  1. Bubble Sort vs Selection Sort: Both algorithms have a time complexity of O(n^2), but Selection Sort performs fewer swaps, making it more efficient in practice.
  2. Bubble Sort vs Insertion Sort: Insertion Sort is another comparison-based sorting algorithm that builds the final sorted list one element at a time. It performs better than Bubble Sort for small datasets and partially sorted lists.
  3. Bubble Sort vs Merge Sort: Merge Sort is a divide-and-conquer algorithm that divides the list into smaller sublists, sorts them, and then merges them. It has a time complexity of O(n log n) and is more efficient than Bubble Sort for large datasets.
  4. Bubble Sort vs Quick Sort: Quick Sort is another divide-and-conquer algorithm that partitions the list into two sublists, sorts them independently, and then combines them. It has an average time complexity of O(n log n) and is generally faster than Bubble Sort.

Conclusion

In this comprehensive guide, we explored the Bubble Sort algorithm in Python. Its working principle analyzed its time complexity and explored various optimization techniques. We also compared Bubble Sort with other sorting algorithms and provided a step-by-step implementation in Python. We also discussed the applications and use cases of Bubble Sort, as well as best practices and tips for efficient usage. Following the guidelines and techniques outlined in this guide, you can effectively apply Bubble Sort to your projects and achieve the desired sorting results. If you want a complete AI & ML program, register yourself on the Certified AI & ML BlackBelt Plus Program today.

Hi, I am Pankaj Singh Negi - Senior Content Editor | Passionate about storytelling and crafting compelling narratives that transform ideas into impactful content. I love reading about technology revolutionizing our lifestyle.

Login to continue reading and enjoy expert-curated content.

Free Courses

Generative AI - A Way of Life

Explore Generative AI for beginners: create text and images, use top AI tools, learn practical skills, and ethics.

Getting Started with Large Language Models

Master Large Language Models (LLMs) with this course, offering clear guidance in NLP and model training made simple.

Building LLM Applications using Prompt Engineering

This free course guides you on building LLM apps, mastering prompt engineering, and developing chatbots with enterprise data.

Improving Real World RAG Systems: Key Challenges & Practical Solutions

Explore practical solutions, advanced retrieval strategies, and agentic RAG systems to improve context, relevance, and accuracy in AI-driven applications.

Microsoft Excel: Formulas & Functions

Master MS Excel for data analysis with key formulas, functions, and LookUp tools in this comprehensive course.

Responses From Readers

Flagship Programs

GenAI Pinnacle Program| GenAI Pinnacle Plus Program| AI/ML BlackBelt Program| Agentic AI Pioneer Program

Free Courses

Generative AI| DeepSeek| OpenAI Agent SDK| LLM Applications using Prompt Engineering| DeepSeek from Scratch| Stability.AI| SSM & MAMBA| RAG Systems using LlamaIndex| Building LLMs for Code| Python| Microsoft Excel| Machine Learning| Deep Learning| Mastering Multimodal RAG| Introduction to Transformer Model| Bagging & Boosting| Loan Prediction| Time Series Forecasting| Tableau| Business Analytics| Vibe Coding in Windsurf| Model Deployment using FastAPI| Building Data Analyst AI Agent| Getting started with OpenAI o3-mini| Introduction to Transformers and Attention Mechanisms

Popular Categories

AI Agents| Generative AI| Prompt Engineering| Generative AI Application| News| Technical Guides| AI Tools| Interview Preparation| Research Papers| Success Stories| Quiz| Use Cases| Listicles

Generative AI Tools and Techniques

GANs| VAEs| Transformers| StyleGAN| Pix2Pix| Autoencoders| GPT| BERT| Word2Vec| LSTM| Attention Mechanisms| Diffusion Models| LLMs| SLMs| Encoder Decoder Models| Prompt Engineering| LangChain| LlamaIndex| RAG| Fine-tuning| LangChain AI Agent| Multimodal Models| RNNs| DCGAN| ProGAN| Text-to-Image Models| DDPM| Document Question Answering| Imagen| T5 (Text-to-Text Transfer Transformer)| Seq2seq Models| WaveNet| Attention Is All You Need (Transformer Architecture) | WindSurf| Cursor

Popular GenAI Models

Llama 4| Llama 3.1| GPT 4.5| GPT 4.1| GPT 4o| o3-mini| Sora| DeepSeek R1| DeepSeek V3| Janus Pro| Veo 2| Gemini 2.5 Pro| Gemini 2.0| Gemma 3| Claude Sonnet 3.7| Claude 3.5 Sonnet| Phi 4| Phi 3.5| Mistral Small 3.1| Mistral NeMo| Mistral-7b| Bedrock| Vertex AI| Qwen QwQ 32B| Qwen 2| Qwen 2.5 VL| Qwen Chat| Grok 3

AI Development Frameworks

n8n| LangChain| Agent SDK| A2A by Google| SmolAgents| LangGraph| CrewAI| Agno| LangFlow| AutoGen| LlamaIndex| Swarm| AutoGPT

Data Science Tools and Techniques

Python| R| SQL| Jupyter Notebooks| TensorFlow| Scikit-learn| PyTorch| Tableau| Apache Spark| Matplotlib| Seaborn| Pandas| Hadoop| Docker| Git| Keras| Apache Kafka| AWS| NLP| Random Forest| Computer Vision| Data Visualization| Data Exploration| Big Data| Common Machine Learning Algorithms| Machine Learning| Google Data Science Agent
πŸ‘ Av Logo White

Continue your learning for FREE

Forgot your password?
πŸ‘ Av Logo White

Enter OTP sent to

Edit

Wrong OTP.

Enter the OTP

Resend OTP

Resend OTP in 45s

πŸ‘ Popup Banner
πŸ‘ AI Popup Banner