Python Tutorial @ Home

# Python Searching and Sorting|Bubble Sort

Implementation in Python Code

Program

```# Creating a bubble sort function
def bubble_sort(list1):
# Outer loop for traverse the entire list
for i in range(0,len(list1)-1):
for j in range(len(list1)-1):
if(list1[j]>list1[j+1]):
temp = list1[j]
list1[j] = list1[j+1]
list1[j+1] = temp
return list1

list1 = [5, 3, 8, 6, 7, 2]
print("The unsorted list is: ", list1)
# Calling the bubble sort function
print("The sorted list is: ", bubble_sort(list1))  ```

Output:

The unsorted list is: [5, 3, 8, 6, 7, 2]
The sorted list is: [2, 3, 5, 6, 7, 8]

Without using a temp variable

We can also swap the elements without using the temp variable. Python has a very unique syntax. We can use the following lines of code.

Example –

```def bubble_sort(list1):
# Outer loop for traverse the entire list
for i in range(0,len(list1)-1):
for j in range(len(list1)-1):
if(list1[j]>list1[j+1]):
# here we are not using temp variable
list1[j],list1[j+1] = list1[j+1], list1[j]
return list1

list1 = [5, 3, 8, 6, 7, 2]
print("The unsorted list is: ", list1)
# Calling the bubble sort function
print("The sorted list is: ", bubble_sort(list1))  ```

Output:

The unsorted list is: [5, 3, 8, 6, 7, 2]
The sorted list is: [2, 3, 5, 6, 7, 8]

Optimization of Python Code Implementation

We can optimize the above code using the two techniques. The swaps are not done; it means list is sorted. In the previous technique – The previous technique will evaluate the complete list though it doesn’t seem necessary to do.

We can prevent the unnecessary evaluation using the Boolean flag and checks if any swaps were made in the previous section.

Example –

```def bubble_sort(list1):
# We can stop the iteration once the swap has done
has_swapped = True

while(has_swapped):
has_swapped = False
for i in range(len(list1) - 1):
if list1[i] > list1[i+1]:
# Swap
list1[i], list1[i+1] = list1[i+1], list1[i]
has_swapped = True
return list1

list1 = [5, 3, 8, 6, 7, 2]
print("The unsorted list is: ", list1)
# Calling the bubble sort function
print("The sorted list is: ", bubble_sort(list1))  ```

Important Pages Visitor Counter       