|
1 | | -# Python program for implementation of Bubble Sort |
2 | | - |
3 | 1 | def bubbleSort(arr): |
4 | | - n = len(arr) |
5 | | - # optimize code, so if the array is already sorted, it doesn't need |
6 | | - # to go through the entire process |
7 | | - swapped = False |
8 | | - # Traverse through all array elements |
9 | | - for i in range(n-1): |
10 | | - # range(n) also work but outer loop will |
11 | | - # repeat one time more than needed. |
12 | | - # Last i elements are already in place |
13 | | - for j in range(0, n-i-1): |
| 2 | + n = len(arr) |
| 3 | + # optimize code, so if the array is already sorted, it doesn't need |
| 4 | + # to go through the entire process |
| 5 | + swapped = False |
| 6 | + # Traverse through all array elements |
| 7 | + for i in range(n - 1): |
| 8 | + # range(n) also works but the outer loop will |
| 9 | + # repeat one time more than needed. |
| 10 | + # Last i elements are already in place |
| 11 | + for j in range(0, n - i - 1): |
| 12 | + # traverse the array from 0 to n-i-1 |
| 13 | + # Swap if the element found is greater |
| 14 | + # than the next element |
| 15 | + if arr[j] > arr[j + 1]: |
| 16 | + swapped = True |
| 17 | + arr[j], arr[j + 1] = arr[j + 1], arr[j] |
| 18 | + |
| 19 | + if not swapped: |
| 20 | + # if we haven't needed to make a single swap, we |
| 21 | + # can just exit the main loop. |
| 22 | + return |
14 | 23 |
|
15 | | - # traverse the array from 0 to n-i-1 |
16 | | - # Swap if the element found is greater |
17 | | - # than the next element |
18 | | - if arr[j] > arr[j + 1]: |
19 | | - swapped = True |
20 | | - arr[j], arr[j + 1] = arr[j + 1], arr[j] |
21 | | - |
22 | | - if not swapped: |
23 | | - # if we haven't needed to make a single swap, we |
24 | | - # can just exit the main loop. |
25 | | - return |
| 24 | +def main(): |
| 25 | + n = int(input("Enter the number of elements: ")) |
| 26 | + arr = [] |
| 27 | + for i in range(n): |
| 28 | + element = int(input(f"Enter element {i+1}: ")) |
| 29 | + arr.append(element) |
26 | 30 |
|
| 31 | + bubbleSort(arr) |
27 | 32 |
|
28 | | -# Driver code to test above |
29 | | -arr = [64, 34, 25, 12, 22, 11, 90] |
| 33 | + print("Sorted array is:") |
| 34 | + for i in range(len(arr)): |
| 35 | + print("%d" % arr[i], end=" ") |
30 | 36 |
|
31 | | -bubbleSort(arr) |
| 37 | +if __name__ == "__main__": |
| 38 | + main() |
32 | 39 |
|
33 | | -print("Sorted array is:") |
34 | | -for i in range(len(arr)): |
35 | | - print("% d" % arr[i], end=" ") |
|
0 commit comments