Table of content

Bubble Sort in Python

Bubble Sort is a sorting mechanism that utilizes repeated swapping of adjacent values in an array to achieve a sorted order of elements.

The Bubble Sort Algorithm keeps swapping elements till the largest element in the array reaches the last position in the array and then goes on to the next element in the array. This element in turn again swapped and placed according to its value in reference to the last set of elements already sorted.

The following steps show how Bubble Sort is done.

Step 1

bubble-sort-step-1

Step 2

bubble-sort-step-2

Step 3

bubble-sort-step-3

Step 4

bubble-sort-step-4

Step 5

bubble-sort-step-5

Step 6

bubble-sort-step-6

Step 7

bubble-sort-step-7

Step 8

bubble-sort-step-8

Step 9

bubble-sort-step-9

Step 10

bubble-sort-step-10

Step 11

bubble-sort-step-11

The worst and average-case time complexities of Bubble Sort are both O(n2). The best-case however, where all the elements are already sorted, is O(n). Bubble Sort is an in-place sorting algorithm and no extra memory space is required.

Bubble Sort Algorithm

Assumptions: 'array' is an array with 10 numerical elements in random order

BubbleSort( arguments: array )

  1. Start
  2. n <- length of array - 1
  3. While n >= 1 do
    1. i <- 0
    2. While i < n do
      1. If array[i] > array[i+1] then
        1. temp <- array[i]
        2. array[i] <- array[i+1]
        3. array[i+1] <- temp
      2. EndIf
      3. i <- i + 1
    3. EndWhile
    4. n <- n - 1
  4. EndWhile
  5. Stop

Bubble Sort Code using Python

The Python 3 code for the Bubble Sort function is as follows

def BubbleSort(array):
    n = len(array) - 1
    while n >= 1:
        i = 0
        while i < n:
            if array[i] > array[i + 1]:
                array[i], array[i + 1] = array[i + 1], array[i]
            i = i + 1
        n = n - 1

The complete program, after implementation and compilation is

def BubbleSort(array):
    n = len(array) - 1
    while n >= 1:
        i = 0
        while i < n:
            if array[i] > array[i + 1]:
                array[i], array[i + 1] = array[i + 1], array[i]
            i = i + 1
        n = n - 1


array1 = [9, 8, 6, 7, 5, 4, 1, 3, 2]
BubbleSort(array1)
print(array1)

the output of which is

[1, 2, 3, 4, 5, 6, 7, 8, 9]
Advantages
  • Short code and easy to implement
  • Little memory overhead
  • Easy to understand
  • Fast application on short arrays
Disadvantages
  • Slow in case of long arrays
  • Uses n-squared time which requires n-squared time to sort every element in the array
  • Suitable for academics but not in real-life applications

Applications of Bubble Sort

  • Used to sort elements in ascending order
  • Used in computer graphics as it can detect small errors in almost sorted arrays
  • Used to process small arrays
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions