Commit 61aee4b
authored
⚡️ Speed up function
Certainly! Your code is a classic **bubble sort** implementation with two major performance issues.
- It never checks if the array is already sorted in a pass, so it does the maximum number of iterations.
- It redundantly computes `len(arr)` every inner-loop.
- Bubble sort is inherently slow — but you require an in-place sort and the result must be the same, so we can improve with some key optimizations.
### Optimized Bubble Sort
Improvements.
1. **Early exit:** Stop if no swaps occurred (array is sorted).
2. **Reduce inner loop range each time:** The last elements are already sorted after each pass.
3. **Direct tuple-swap:** Use Python's multiple assignment swap for speed.
4. **Pre-compute `len(arr)`:** Only compute once.
Here is the **optimized version** preserving all your prints and output.
### Explanation of changes
- **`swapped` check:** If no swaps in an outer pass, break for a big speed boost on nearly-sorted data.
- **`range(n - i - 1)`:** Each pass pushes the next-largest value into place, so inner loop shortens.
- **Tuple swap:** Faster than three assignments.
- **No unnecessary calls to `len()` in loop.**
This is the fastest bubble-sort possible without changing the algorithm (still in-place, correct result).
**If you want even faster code, and are allowed to use Python's built-in sort**, you could simply use `arr.sort()`, but as per your request, this implements only the algorithmic optimization of what you already have.sorter by 87%1 parent e17d0f7 commit 61aee4b
1 file changed
+8
-5
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | 2 | | |
3 | | - | |
4 | | - | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
5 | 7 | | |
6 | | - | |
7 | | - | |
8 | | - | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
9 | 12 | | |
10 | 13 | | |
0 commit comments