Bubble Sort Implementation in Python

We all know that a Bubble Sort is a sorting algorithm. You can find the implementation code of this algorithm is everywhere. But I want to organize this on my site.

The complexity of this algorithm.

Worst Complexity: O( n^2 )
Average Complexity: O( n^2 )
Best Complexity: O( n )
Space Complexity: O( 1 )

def bubble_sort(lst):
	for i in range(len(lst)-1, 0, -1):
		for j in range(i):
			if lst[j] > lst[j+1]:
				temp = lst[j]
				lst[j] = lst[j+1]
				lst[j+1] = temp
	
	return lst

print(bubble_sort([5, 2, 1, 3, 6, 4, 7])) # Output = [1, 2, 3, 4, 5, 6, 7]
Scroll to Top