You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Returns the first k elements of this collection when it's sorted.
7
7
8
-
If you need to sort a collection but only need access to a prefix of its
9
-
elements, using this method can give you a performance boost over sorting
10
-
the entire collection. The order of equal elements is guaranteed to be
11
-
preserved.
8
+
If you need to sort a collection but only need access to a prefix of its elements, using this method can give you a performance boost over sorting the entire collection. The order of equal elements is guaranteed to be preserved.
12
9
13
10
```swift
14
11
let numbers = [7,1,6,2,8,3,9]
15
-
let smallestThree = numbers.sortedPrefix(<)
12
+
let smallestThree = numbers.sortedPrefix(3, by: <)
16
13
// [1, 2, 3]
17
14
```
18
15
@@ -36,17 +33,16 @@ extension Collection where Element: Comparable {
36
33
37
34
### Complexity
38
35
39
-
The algorithm used is based on [Soroush Khanlou's research on this matter](https://khanlou.com/2018/12/analyzing-complexity/). The total complexity is `O(k log k + nk)`, which will result in a runtime close to `O(n)` if k is a small amount. If k is a large amount (more than 10% of the collection), we fallback to sorting the entire array. Realistically, this means the worst case is actually `O(n log n)`.
36
+
The algorithm used is based on [Soroush Khanlou's research on this matter](https://khanlou.com/2018/12/analyzing-complexity/). The total complexity is `O(k log k + nk)`, which will result in a runtime close to `O(n)` if k is a small amount. If k is a large amount (more than 10% of the collection), we fall back to sorting the entire array. Realistically, this means the worst case is actually `O(n log n)`.
40
37
41
38
Here are some benchmarks we made that demonstrates how this implementation (SmallestM) behaves when k increases (before implementing the fallback):
Copy file name to clipboardExpand all lines: README.md
+1-1Lines changed: 1 addition & 1 deletion
Original file line number
Diff line number
Diff line change
@@ -30,7 +30,7 @@ Read more about the package, and the intent behind it, in the [announcement on s
30
30
31
31
#### Partial sorting
32
32
33
-
-[`sortedPrefix(_:by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/PartialSort.md): Returns the first k elements of a sorted collection.
33
+
-[`sortedPrefix(_:by:)`](https://github.com/apple/swift-algorithms/blob/main/Guides/SortedPrefix.md): Returns the first k elements of a sorted collection.
0 commit comments