|
| 1 | +''' |
| 2 | + Bubble Sort |
| 3 | +Bubble sort is a sorting algorithm that compares two adjacent elements and swaps them until they are not in the intended order. |
| 4 | +''' |
| 5 | + |
| 6 | +def bubbleSort(array): |
| 7 | + |
| 8 | + # loop to access each array element |
| 9 | + for i in range(len(array)): |
| 10 | + |
| 11 | + # loop to compare array elements |
| 12 | + for j in range(0, len(array) - i - 1): |
| 13 | + |
| 14 | + # compare two adjacent elements |
| 15 | + # change > to < to sort in descending order |
| 16 | + if array[j] > array[j + 1]: |
| 17 | + |
| 18 | + # swapping elements if elements |
| 19 | + # are not in the intended order |
| 20 | + temp = array[j] |
| 21 | + array[j] = array[j+1] |
| 22 | + array[j+1] = temp |
| 23 | + |
| 24 | + |
| 25 | +list = [-2, 45, 0, 11, -9] |
| 26 | + |
| 27 | +bubbleSort(list) |
| 28 | +print(list) #[-9, -2, 0, 11, 45] |
| 29 | + |
| 30 | +# Optimized |
| 31 | + |
| 32 | +def bubbleSort(array): |
| 33 | + |
| 34 | + # loop through each element of array |
| 35 | + for i in range(len(array)): |
| 36 | + |
| 37 | + # keep track of swapping |
| 38 | + swapped = False |
| 39 | + |
| 40 | + # loop to compare array elements |
| 41 | + for j in range(0, len(array) - i - 1): |
| 42 | + |
| 43 | + # compare two adjacent elements |
| 44 | + # change > to < to sort in descending order |
| 45 | + if array[j] > array[j + 1]: |
| 46 | + |
| 47 | + # swapping occurs if elements |
| 48 | + # are not in the intended order |
| 49 | + temp = array[j] |
| 50 | + array[j] = array[j+1] |
| 51 | + array[j+1] = temp |
| 52 | + |
| 53 | + swapped = True |
| 54 | + |
| 55 | + # no swapping means the array is already sorted |
| 56 | + # so no need for further comparison |
| 57 | + if not swapped: |
| 58 | + break |
| 59 | + |
| 60 | +list = [-2, 45, 0, 11, -9] |
| 61 | + |
| 62 | +bubbleSort(list) |
| 63 | +print(list) #[-9, -2, 0, 11, 45] |
| 64 | + |
0 commit comments