8
8
// See https://swift.org/LICENSE.txt for license information
9
9
//
10
10
11
- //===----------------------------------------------------------------------===//
12
- // sortedPrefix(_:by:)
13
- //===----------------------------------------------------------------------===//
14
-
15
11
extension Collection {
16
-
12
+ /// Returns the first k elements of this collection when it's sorted using
13
+ /// the given predicate as the comparison between elements.
14
+ ///
15
+ /// This example partially sorts an array of integers to retrieve its three
16
+ /// smallest values:
17
+ ///
18
+ /// let numbers = [7,1,6,2,8,3,9]
19
+ /// let smallestThree = numbers.sortedPrefix(3, <)
20
+ /// // [1, 2, 3]
21
+ ///
22
+ /// If you need to sort a collection but only need access to a prefix of its
23
+ /// elements, using this method can give you a performance boost over sorting
24
+ /// the entire collection. The order of equal elements is guaranteed to be
25
+ /// preserved.
26
+ ///
27
+ /// - Parameter count: The k number of elements to prefix.
28
+ /// - Parameter areInIncreasingOrder: A predicate that returns true if its
29
+ /// first argument should be ordered before its second argument;
30
+ /// otherwise, false.
31
+ ///
32
+ /// - Complexity: O(k log k + nk)
17
33
public func sortedPrefix(
18
34
_ count: Int ,
19
35
by areInIncreasingOrder: ( Element , Element ) throws -> Bool
@@ -35,17 +51,35 @@ extension Collection {
35
51
var result = try self . prefix ( count) . sorted ( by: areInIncreasingOrder)
36
52
for e in self . dropFirst ( count) {
37
53
if let last = result. last, try areInIncreasingOrder ( last, e) { continue }
38
- if let insertionIndex = try result. firstIndex ( where: { try areInIncreasingOrder ( e, $0) } ) {
54
+ if let insertionIndex = try result. firstIndex ( where: { try areInIncreasingOrder ( e, $0) } ) {
39
55
result. insert ( e, at: insertionIndex)
40
56
result. removeLast ( )
41
57
}
42
58
}
59
+
43
60
return result
44
61
}
45
62
}
46
63
47
64
extension Collection where Element: Comparable {
48
-
65
+ /// Returns the first k elements of this collection when it's sorted using
66
+ /// the given predicate as the comparison between elements.
67
+ ///
68
+ /// This example partially sorts an array of integers to retrieve its three
69
+ /// smallest values:
70
+ ///
71
+ /// let numbers = [7,1,6,2,8,3,9]
72
+ /// let smallestThree = numbers.sortedPrefix(3, <)
73
+ /// // [1, 2, 3]
74
+ ///
75
+ /// If you need to sort a collection but only need access to a prefix of its
76
+ /// elements, using this method can give you a performance boost over sorting
77
+ /// the entire collection. The order of equal elements is guaranteed to be
78
+ /// preserved.
79
+ ///
80
+ /// - Parameter count: The k number of elements to prefix.
81
+ ///
82
+ /// - Complexity: O(k log k + nk)
49
83
public func sortedPrefix( _ count: Int ) -> [ Element ] {
50
84
return sortedPrefix ( count, by: < )
51
85
}
0 commit comments