In this tutorial, we will implement bubble sort in python.
Bubble sort is a simple sorting algorithm. In bubble sort, we compare two adjacent elements and check if they are in correct order.If they are not in correct order, we swap them.
Here is a simple illustration of bubble sort.
Above GIF is generated from algorithms app.
Here is simple code for bubble sort in python.
1 2 3 4 5 6 7 8 9 10 11 12 |
arr = [10,80,30,19,8,12,17] print("Original array:",arr) for i in range(len(arr)-1): for j in range(len(arr)-1-j): if arr[j] > arr[j+1]: temp = arr[j] arr[j] = arr[j+1] arr[j+1] = temp print("Sorted array:",arr) |
Output:
Original array: [10, 80, 30, 19, 8, 12, 17]
Sorted array: [8, 10, 12, 17, 19, 30, 80]
Both worst case and average case complexity is O (n^2) for bubble sort.
That’s all about bubble sort in python.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.