|
| 1 | +"""Bubble Sort Algo: |
| 2 | +1. iterate through the list/array |
| 3 | +2. iterate again to compare the elements with each other |
| 4 | +3. if arr[j] > arr[j+1]: |
| 5 | +4. swap the numbers in comparison |
| 6 | +5. these swaps are the passes here that bubbles up the largest element to the |
| 7 | +top. |
| 8 | +6. perform these steps n times, n=len(list) |
| 9 | +
|
| 10 | +Conceptually, |
| 11 | +
|
| 12 | +Assume a list l = [2, 5, 3, 0], |
| 13 | +Iter1: take the first element and compare it with |
| 14 | +the one after it and if arr[0] is greater than arr[1], swap elements else no |
| 15 | +operation is performed. |
| 16 | +
|
| 17 | +Iter2: arr[1] > arr[2], swap so now arr[1]=3 and arr[2]=5. |
| 18 | +Iter3: arr[2] > arr[3], swap so now arr[2]=0 and arr[3]=5. |
| 19 | +In Iter3, we see the largest element of the list bubbles up to the end, already |
| 20 | +sorted position. |
| 21 | +
|
| 22 | +The list after these three passes become [2, 3, 0, 5] |
| 23 | +
|
| 24 | +Iter4: arr[0]>arr[1], false so no swap occurs. |
| 25 | +Iter5: arr[1]>arr[2], true so now arr[1]=0 and arr[2]=3 after swapping elements |
| 26 | +Iter6: arr[2]>arr[3], false so no swap. |
| 27 | +
|
| 28 | +Already, 5 is at the sorted position so we may skip the Iter6 step as programmed |
| 29 | +below. |
| 30 | +The list now becomes [2, 0, 3, 5] |
| 31 | +
|
| 32 | +Iter7: arr[0]>arr[1], true, swap so now arr[0]=0 and arr[1]=2 |
| 33 | +List becomes, [0, 2, 3, 5] which is sorted. |
| 34 | +
|
| 35 | +""" |
| 36 | + |
| 37 | + |
| 38 | + |
| 39 | +def bubble_sort(arr): |
| 40 | + print(arr) |
| 41 | + for i in range(len(arr)): |
| 42 | + flag = 0 |
| 43 | + for j in range(0, len(arr)-i-1): |
| 44 | + if arr[j] > arr[j+1]: |
| 45 | + arr[j], arr[j+1] = arr[j+1], arr[j] |
| 46 | + flag = 1 |
| 47 | + print(arr) |
| 48 | + # print(arr) |
| 49 | + if flag == 0: |
| 50 | + break |
| 51 | + |
| 52 | +bubble_sort([2, 4, 3, 1, 7, 0, 5]) |
0 commit comments