Last active
April 15, 2025 20:20
-
-
Save om-mapari/239e340dbec8981823f595d16bf90695 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Optimized Bubble sort in Python | |
| def bubbleSort(array): | |
| # loop through each element of array | |
| for i in range(len(array)): | |
| # keep track of swapping | |
| swapped = False | |
| # loop to compare array elements | |
| for j in range(0, len(array) - i - 1): | |
| # compare two adjacent elements | |
| # change > to < to sort in descending order | |
| if array[j] > array[j + 1]: | |
| # swapping occurs if elements | |
| # are not in the intended order | |
| temp = array[j] | |
| array[j] = array[j+1] | |
| array[j+1] = temp | |
| swapped = True | |
| # no swapping means the array is already sorted | |
| # so no need for further comparison | |
| if not swapped: | |
| break | |
| data = [-2, 45, 0, 11, -9] | |
| bubbleSort(data) | |
| print('Sorted Array in Ascending Order:') | |
| print(data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment