CIT PYTHON COHORT THREE
  • CIT Python Cloud Software Engineering
  • week one
    • What is Python
    • Python Syntax
    • variables
    • Numbers / Integers
  • week Two
    • Control Flow Statements
      • If Statements
      • For Loops
      • While Loops
      • Break and Continue Statements
    • Operators
      • Assignment Operators
      • Arithmetic Operators
      • Comparison Operators
      • Logical Operators
      • Relational Operators
      • Bitwise Operators
      • Identity Operators
      • Membership Operators
    • Data Types
      • Strings
      • Numbers
      • Booleans
      • Lists
      • Dictionaries
      • Tuples
      • Sets
  • Week 3
    • Functions
      • Function Arguments
      • Python Recursion
      • Python Anonymous/Lambda Function
    • Object Oriented Programming
      • Classes
      • Inheritance
      • Polymorphism
      • Abstraction
      • Encapsulation
    • Python Modules
      • Python Packages
      • Python Built-in Modules
      • Python Standard Library
      • Python Third Party Modules
    • Python Exceptions
      • Python Try Except
      • Python Raise
      • Python Assert
      • Python User-defined Exceptions
  • Week 4
    • Python File Handling
  • Week6
    • Data Structures and Algorithms
      • DSA Introduction
      • What is an Algorithm?
      • Data Structures and Types
      • Stack
      • Queue
      • Linked List
      • Bubble Sort Algorithm
      • Selection Sort Algorithm
      • Insertion Sort Algorithm
      • Merge Sort Algorithm
      • Quick Sort Algorithm
  • Week8
    • Cryptography
      • Reverse Cipher
      • Caesar Cipher
      • Hash Functions
        • Applications of Hash Functions
        • Examples of Hash Functions
  • Assignments and Solutions
    • Loops
Powered by GitBook
On this page

Was this helpful?

Edit on GitHub
  1. Week6
  2. Data Structures and Algorithms

Bubble Sort Algorithm

In this lesson, we will learn about the bubble sort algorithm. We will also learn how to implement it in Python.

PreviousLinked ListNextSelection Sort Algorithm

Last updated 2 years ago

Was this helpful?

Bubble sort is an algorithm that compares adjacent elements in a list and swaps them if they are out of order. It continues to do this until the list is sorted. The algorithm is named bubble sort because the largest element in the list "bubbles" to the top of the list.

Just like the movement of air bubbles in water that rise to the top, the largest element in the list will bubble to the top. The algorithm will then ignore the largest element and repeat the process until the list is sorted.

Working of the Bubble Sort Algorithm

Suppose we are trying to sort the following list of numbers in ascending order:

[5, 1, 4, 2, 8]
  1. First Iteration (Compare and Swap)

    1. Starting from the first index, compare the first and the second elements.

    2. If the first element is greater than the second element, swap them.

    3. Now, compare the second and the third elements. Swap them if they are not in order.

    4. The above process goes on until the last element

Compare the Adjacent Elements
  1. Remaining Iteration

The same process goes on for the remaining iterations.

After each iteration, the largest element among the unsorted elements is placed at the end.

In each iteration, the comparison takes place up to the last unsorted element.

The array is sorted when all the unsorted elements are placed at their correct positions.

Bubble Sort Algorithm

bubbleSort(array)
  for i <- 1 to indexOfLastUnsortedElement-1
    if leftElement > rightElement
      swap leftElement and rightElement
end bubbleSort

Bubble Sort Code in Python

# Bubble sort in Python

def bubbleSort(array):
    
  # loop to access each array element
  for i in range(len(array)):

    # loop to compare array elements
    for j in range(0, len(array) - i - 1):

      # compare two adjacent elements
      # change > to < to sort in descending order
      if array[j] > array[j + 1]:

        # swapping elements if elements
        # are not in the intended order
        temp = array[j]
        array[j] = array[j+1]
        array[j+1] = temp


data = [-2, 45, 0, 11, -9]

bubbleSort(data)

print('Sorted Array in Ascending Order:')
print(data)

Optimized Bubble Sort Algorithm

In the above algorithm, all the comparisons are made even if the array is already sorted. This increases the execution time.

To solve this, we can introduce an extra variable swapped. The value of swapped is set true if there occurs swapping of elements. Otherwise, it is set false.

After an iteration, if there is no swapping, the value of swapped will be false. This means elements are already sorted and there is no need to perform further iterations.

This will reduce the execution time and helps to optimize the bubble sort.

Algorithm for optimized bubble sort is

bubbleSort(array)
  swapped <- false
  for i <- 1 to indexOfLastUnsortedElement-1
    if leftElement > rightElement
      swap leftElement and rightElement
      swapped <- true
end bubbleSort

Optimized Bubble Sort in Python

# Optimized Bubble sort in Python

def bubbleSort(array):
    
  # loop through each element of array
  for i in range(len(array)):
        
    # keep track of swapping
    swapped = False
    
    # loop to compare array elements
    for j in range(0, len(array) - i - 1):

      # compare two adjacent elements
      # change > to < to sort in descending order
      if array[j] > array[j + 1]:

        # swapping occurs if elements
        # are not in the intended order
        temp = array[j]
        array[j] = array[j+1]
        array[j+1] = temp

        swapped = True
          
    # no swapping means the array is already sorted
    # so no need for further comparison
    if not swapped:
      break

data = [-2, 45, 0, 11, -9]

bubbleSort(data)

print('Sorted Array in Ascending Order:')
print(data)
Put the largest element at the end
Compare the adjacent elements
The array is sorted if all elements are kept in the right order