File tree 2 files changed +31
-7
lines changed
algorithms_and_data_structures/algorithms/sorting/bubble_sort
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
+
1
12
def bubble_sort (nums : list [float ]) -> list [float ]:
13
+ """Sorts a list of floats, in-place."""
2
14
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 ]
6
18
7
19
return nums
8
20
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
+
1
12
def bubble_sort (nums : list [float ]) -> list [float ]:
13
+ """Sorts a list of floats, in-place."""
2
14
is_sorted = True
3
15
4
16
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 ]:
7
19
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 ]
9
21
10
- if is_sorted :
22
+ if is_sorted : # End early, list is sorted
11
23
break
12
24
13
25
return nums
You can’t perform that action at this time.
0 commit comments