@@ -6,17 +6,17 @@ The `sorted()` function returns a new sorted list from the items in an iterable.
66
77| Case | Time | Space | Notes |
88| ------| ------| -------| -------|
9- | Basic sorting | O(n log n) | O(n) | Timsort algorithm |
9+ | Basic sorting | O(n log n) | O(n) | Timsort/Powersort |
1010| With key function | O(n log n + n* k) | O(n) | k = key function time; key computed once per element |
1111| Reverse sorting | O(n log n) | O(n) | No extra overhead |
12- | Already sorted | O(n) | O(n) | Best case for Timsort |
12+ | Already sorted | O(n) | O(n) | Best case |
1313
1414## Basic Usage
1515
1616### Simple Sorting
1717
1818``` python
19- # O(n log n) - uses Timsort algorithm
19+ # O(n log n) - Timsort (≤3.10) or Powersort (3.11+)
2020numbers = [3 , 1 , 4 , 1 , 5 , 9 , 2 , 6 ]
2121result = sorted (numbers)
2222# [1, 1, 2, 3, 4, 5, 6, 9]
@@ -102,16 +102,19 @@ result = sorted(coords, key=lambda c: c[1])
102102# [(3, 2), (1, 5), (2, 8)]
103103```
104104
105- ## Timsort Algorithm
105+ ## Sorting Algorithm
106106
107107### How It Works
108108
109109```
110- Timsort is a hybrid algorithm combining merge sort and insertion sort:
110+ Python uses Timsort (Python 2.3-3.10) or Powersort (Python 3.11+).
111+ Both are hybrid algorithms combining merge sort and insertion sort:
1111121. Divide array into small chunks (runs) - ~32-64 elements
1121132. Sort each run with insertion sort - O(k²) per run
1131143. Merge runs together - O(n log n) overall
1141154. Already sorted data: O(n) - detects and uses it
116+
117+ Powersort uses an improved merge policy but has the same complexity.
115118```
116119
117120### Performance Characteristics
@@ -147,7 +150,7 @@ original = [3, 1, 4, 1, 5]
147150original.sort() # [1, 1, 3, 4, 5]
148151# original modified
149152
150- # Both use Timsort , same complexity but sorted() makes copy
153+ # Both use same algorithm , same complexity but sorted() makes copy
151154```
152155
153156### Expensive Key Functions
@@ -325,6 +328,5 @@ result = sorted(numbers) # Nearly O(n)
325328
326329## Version Notes
327330
328- - ** Python 2.x** : Uses Timsort since 2.3
329- - ** Python 3.x** : Same Timsort implementation
330- - ** Python 3.8+** : No changes to complexity, consistent performance
331+ - ** Python 2.3-3.10** : Uses Timsort algorithm
332+ - ** Python 3.11+** : Uses Powersort (improved merge policy, same complexity)
0 commit comments