# Bubble sort optimal python implimentation

04 July, 2021 - 2 min read

Sorting is a process of arranging objects or things in an ascending or descenting order. This has wide applicability in our everyday lifes, and so in software development.

Imagine you're a teacher, and you're asked to arrange your students by their increasing or descreasing height. What'll be your starting point, and how would you go about it.

# What is Bubble Sort

Bubble sort is a method of arranging or sorting things or items in ascending or descending order by comparing two adjacent values, say **x** and **y**. if **x** is higher than **y**, **x** takes the second position and vice-versa. If the items are already in your prefered order, then no swapping can take place.

This process is repeated until you achieve your desired order.

Now, for explanation purpose, consider this array

**array = [6, 9, 8, 0, 7, 6, 1]**

## Bubble Sort Steps

- Find length of array ie
**len(array)** - Find number of outer passes to be made i.e
**len(array)-1** - Operate the inner passes
**n-1**times for outer pass 1. Get first value and compare with th next number. Do the swapping depending on your preferred order. - Repeat the above operation untul you reach the outer pass
**n-1**. Get next item in the list and repeat the above process util all values are in your preferred order. - Return the sorted list.
- Optimise the algorith.

### Python implimentation

```
def bSort(array):
n = len(array)
for i in range(n-1):
flag = 0
for j in range(n-1):
if array[j] > array[j+1]:
tmp = array[j]
array[j] = array[j+1]
array[j+1] = tmp
flag = 1
if flag == 0:
break
return array
el = [21, 6, 9, 33, 3]
result = bSort(el)
print(result)
```