|
1 | 1 | # A simple implementation of bubble sort
|
2 | 2 |
|
3 | 3 | def bubbleSort(arr):
|
| 4 | + # travese the whole array |
4 | 5 | for i in range(len(arr)):
|
5 |
| - for j in range(i+1, len(arr)): |
| 6 | + |
| 7 | + # last i elements are already in place |
| 8 | + for j in range(0, len(arr)-i-1): |
| 9 | + |
| 10 | + if arr[j] > arr[j+1]: |
| 11 | + arr[j], arr[j+1] = arr[j+1], arr[j] |
| 12 | + |
| 13 | + return arr |
| 14 | + |
| 15 | +# Approach 2: This algorithm will run for O(n^2) even if the array is |
| 16 | +# already sorted. For avoiding this, we can check if elements are swapped |
| 17 | +# in each pass. We will break the loop in case they are not |
| 18 | + |
| 19 | +# Time Complexity: O(n^2) - Average or Worst Case; O(n) - Best case [Array is already sorted] |
| 20 | + |
| 21 | +def bubbleSortOptimized(arr): |
| 22 | + for i in range(len(arr)): |
| 23 | + swapped = False |
| 24 | + |
| 25 | + for j in range(0, len(arr)-i-1): |
| 26 | + |
6 | 27 | if arr[i] > arr[j]:
|
7 | 28 | arr[i], arr[j] = arr[j], arr[i]
|
| 29 | + swapped = True |
| 30 | + |
| 31 | + # if no elements are swapped, break the loop |
| 32 | + if swapped == False: |
| 33 | + break |
8 | 34 |
|
9 | 35 | return arr
|
10 | 36 |
|
11 |
| -arr = [2, 6, 1, 5, 3, 4] |
12 |
| -res = bubbleSort(arr) |
13 |
| -print(res) |
| 37 | +if __name__ = "__main__": |
| 38 | + arr = [2, 6, 1, 5, 3, 4] |
| 39 | + res = bubbleSort(arr) |
| 40 | + print(res) |
0 commit comments