File tree Expand file tree Collapse file tree 2 files changed +31
-7
lines changed
algorithms_and_data_structures/algorithms/sorting/bubble_sort Expand file tree Collapse file tree 2 files changed +31
-7
lines changed Original file line number Diff line number Diff line change 1+ """
2+ This implementation of Bubble Sort:
3+ * Is a naive version, can be easily optimized.
4+ * Doesn't return early if the list is already sorted or is sorted during the process.
5+ * Iterates through the sorted portion of the list unnecessarily.
6+
7+ Time Complexity: Best O(n^2) | Avg O(n^2) | Worst O(n^2)
8+ Space Complexity: Total O(n) | Aux O(1)
9+ """
10+
11+
112def bubble_sort (nums : list [float ]) -> list [float ]:
13+ """Sorts a list of floats, in-place."""
214 for _ in range (len (nums )):
3- for indx in range (len (nums ) - 1 ):
4- if nums [indx ] > nums [indx + 1 ]:
5- nums [indx ], nums [indx + 1 ] = nums [indx + 1 ], nums [indx ]
15+ for idx in range (len (nums ) - 1 ):
16+ if nums [idx ] > nums [idx + 1 ]:
17+ nums [idx ], nums [idx + 1 ] = nums [idx + 1 ], nums [idx ]
618
719 return nums
820
Original file line number Diff line number Diff line change 1+ """
2+ This implementation of Bubble Sort:
3+ * Is an optimized version of the naive version.
4+ * Returns early if the list is already sorted or is sorted during the process.
5+ * Doesn't iterate through the sorted portion of the list unnecessarily.
6+
7+ Time Complexity: Best O(n) | Avg O(n^2) | Worst O(n^2)
8+ Space Complexity: Total O(n) | Aux O(1)
9+ """
10+
11+
112def bubble_sort (nums : list [float ]) -> list [float ]:
13+ """Sorts a list of floats, in-place."""
214 is_sorted = True
315
416 for loop in range (len (nums ) - 1 ):
5- for indx in range (len (nums ) - loop - 1 ):
6- if nums [indx ] > nums [indx + 1 ]:
17+ for idx in range (len (nums ) - loop - 1 ):
18+ if nums [idx ] > nums [idx + 1 ]:
719 is_sorted = False
8- nums [indx ], nums [indx + 1 ] = nums [indx + 1 ], nums [indx ]
20+ nums [idx ], nums [idx + 1 ] = nums [idx + 1 ], nums [idx ]
921
10- if is_sorted :
22+ if is_sorted : # End early, list is sorted
1123 break
1224
1325 return nums
You can’t perform that action at this time.
0 commit comments