Skip to content

Commit 6820ca2

Browse files
committed
refa: add docstrings
1 parent d95a294 commit 6820ca2

File tree

2 files changed

+31
-7
lines changed

2 files changed

+31
-7
lines changed

algorithms_and_data_structures/algorithms/sorting/bubble_sort/bubble_sort_naive.py

+15-3
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,20 @@
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+
112
def 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

algorithms_and_data_structures/algorithms/sorting/bubble_sort/bubble_sort_optimized.py

+16-4
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,25 @@
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+
112
def 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

0 commit comments

Comments
 (0)