# Optimized Bubble Sort in Python

It is the simple sorting algorithm that works on the principle of repeated swapping of consecutive elements if they are placed at wrong place.

You have used the swapping concept in your daily life, same concept is applicable here only with the condition that you can swap only two adjacent element with each other.

Now Its time for implementation of bubble sort in Python.

## Python Code for Bubble Sort

```# Bubble Sort Published on Freshlybuilt.com

def bubble_sort(input_list):
# Swap the elements to arrange in order
for iter_num in range(len(input_list) - 1, 0, -1):
for idx in range(iter_num):
if input_list[idx] > input_list[idx + 1]:
temp = input_list[idx]
input_list[idx] = input_list[idx + 1]
input_list[idx + 1] = temp
print(f"Iteration decreasing number {iter_num}:", input_list)
return input_list

def main():
lst = [8, 17, 3, 9]
print("Initial Unsorted List:", lst)
bubble_sort(lst)
print("After Sorting:", lst)

if __name__ == "__main__":
main()```

### Output

```Initial Unsorted List: [8, 17, 3, 9]
After Sorting: [3, 8, 9, 17]```