Bubble sort in python

Previous
Next

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.
Bubble sort
Above GIF is generated from algorithms app.

Here is simple code for bubble sort in python.

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.

Previous
Next

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog