|
| 1 | +# Python program for implementation of Bubble Sort |
| 2 | + |
| 3 | +def bubbleSort(arr): |
| 4 | + n = len(arr) |
| 5 | + |
| 6 | + # Traverse through all array elements |
| 7 | + for i in range(n): |
| 8 | + |
| 9 | + # Last i elements are already in place, so the inner loops will run until it reaches the last i elements |
| 10 | + for j in range(0, n-i-1): |
| 11 | + |
| 12 | + # traverse the array from 0 to n-i-1 |
| 13 | + # Swap if the element found is greater than the next element |
| 14 | + if arr[j] > arr[j+1] : |
| 15 | + arr[j], arr[j+1] = arr[j+1], arr[j] |
| 16 | + |
| 17 | + |
| 18 | +def modifiedBubbleSort(arr): |
| 19 | + n = len(arr) |
| 20 | + |
| 21 | + # Traverse through all array elements |
| 22 | + for i in range(n): |
| 23 | + # Taking a flag variable |
| 24 | + flag = 0 |
| 25 | + # Last i elements are already in place |
| 26 | + for j in range(0, n-i-1): |
| 27 | + |
| 28 | + # traverse the array from 0 to n-i-1 |
| 29 | + # Swap if the element found is greater |
| 30 | + # than the next element |
| 31 | + if arr[j] > arr[j+1] : |
| 32 | + arr[j], arr[j+1] = arr[j+1], arr[j] |
| 33 | + # Setting the flag, if swapping occurs |
| 34 | + flag = 1 |
| 35 | + |
| 36 | + # If not swapped, that means the list has already sorted |
| 37 | + if flag == 0: |
| 38 | + break |
| 39 | + |
| 40 | +# Main code |
| 41 | +arr = [64, 34, 25, 12, 22, 11, 90] |
| 42 | + |
| 43 | +bubbleSort(arr) |
| 44 | +# modifiedBubbleSort(arr) |
| 45 | + |
| 46 | +print ("Sorted array is:") |
| 47 | +for i in range(len(arr)): |
| 48 | + print ("%d" %arr[i]), |
0 commit comments