Commit f988f2c
authored
Refactor quick_sort to use in-place sorting for improved space complexity
This commit refactors the quick_sort function to use an in-place sorting approach instead of creating new lists during the partitioning process.
**Changes made:**
- Introduced a helper function `_quick_sort(collection, low, high)` that performs the recursive in-place sorting
- Implemented `_partition(collection, low, high)` using the Lomuto partition scheme for in-place partitioning
- The main `quick_sort(collection)` function now sorts the list in-place and returns it
- Removed the list comprehensions that created new `lesser` and `greater` lists
- Replaced `collection.pop()` with in-place swapping
**Benefits:**
- Improved space complexity: O(log n) for the recursion stack instead of O(n) for creating new lists
- More memory-efficient, especially for large collections
- Maintains the same O(n log n) average time complexity
- Still uses random pivot selection for better average-case performance1 parent e2a78d4 commit f988f2c
1 file changed
Lines changed: 47 additions & 18 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
7 | 7 | | |
8 | 8 | | |
9 | 9 | | |
10 | | - | |
11 | 10 | | |
12 | 11 | | |
13 | 12 | | |
14 | 13 | | |
15 | 14 | | |
16 | 15 | | |
17 | | - | |
| 16 | + | |
18 | 17 | | |
19 | 18 | | |
20 | 19 | | |
21 | 20 | | |
22 | 21 | | |
23 | 22 | | |
24 | 23 | | |
| 24 | + | |
25 | 25 | | |
26 | 26 | | |
| 27 | + | |
27 | 28 | | |
28 | 29 | | |
29 | 30 | | |
30 | | - | |
31 | | - | |
32 | | - | |
| 31 | + | |
| 32 | + | |
| 33 | + | |
| 34 | + | |
| 35 | + | |
| 36 | + | |
| 37 | + | |
| 38 | + | |
| 39 | + | |
| 40 | + | |
| 41 | + | |
| 42 | + | |
| 43 | + | |
| 44 | + | |
| 45 | + | |
| 46 | + | |
| 47 | + | |
| 48 | + | |
| 49 | + | |
| 50 | + | |
| 51 | + | |
| 52 | + | |
| 53 | + | |
| 54 | + | |
| 55 | + | |
| 56 | + | |
| 57 | + | |
| 58 | + | |
| 59 | + | |
| 60 | + | |
| 61 | + | |
| 62 | + | |
33 | 63 | | |
34 | | - | |
35 | | - | |
36 | | - | |
| 64 | + | |
| 65 | + | |
37 | 66 | | |
38 | | - | |
39 | | - | |
40 | | - | |
| 67 | + | |
| 68 | + | |
| 69 | + | |
| 70 | + | |
| 71 | + | |
41 | 72 | | |
42 | | - | |
43 | | - | |
| 73 | + | |
| 74 | + | |
| 75 | + | |
44 | 76 | | |
45 | 77 | | |
46 | 78 | | |
47 | | - | |
48 | | - | |
49 | | - | |
| 79 | + | |
50 | 80 | | |
51 | | - | |
52 | | - | |
| 81 | + | |
0 commit comments