forked from apple/swift-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathisSorted.swift
51 lines (43 loc) · 1.72 KB
/
isSorted.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Algorithms open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// isSorted()
//===----------------------------------------------------------------------===//
extension Sequence where Element: Comparable {
public func isSorted() -> Bool {
/// Returns Bool, indicating whether a sequence is sorted
/// into non-descending order.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
isSorted(by: <)
}
public func isSorted(by areInIncreasingOrder: (Element, Element) -> Bool) -> Bool {
/// Returns Bool, indicating whether a sequence is sorted using
/// the given predicate as the comparison between elements.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
var prev: Element?
for element in self {
if let p = prev, !areInIncreasingOrder(p, element) {
return false
}
prev = element
}
return true
}
public func allEqual() -> Bool {
/// Returns Bool, indicating whether all the
/// elements in sequence are equal to each other.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
isSorted(by: ==)
}
}