  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 Step 2 Step 3 Step 4 Step 5 Step 6 Step 7 Step 8 Step 9 Step 10 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]``
• Short code and easy to implement
• Easy to understand
• Fast application on short arrays