forked from kodecocodes/swift-algorithm-club
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCountOccurrences.swift
36 lines (34 loc) · 945 Bytes
/
CountOccurrences.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
/// Counts the number of times a value appears in an array in O(log n) time. The array must be sorted from low to high.
///
/// - Parameter key: the key to be searched for in the array
/// - Parameter array: the array to search
/// - Returns: the count of occurences of the key in the given array
func countOccurrences<T: Comparable>(of key: T, in array: [T]) -> Int {
var leftBoundary: Int {
var low = 0
var high = array.count
while low < high {
let midIndex = low + (high - low)/2
if array[midIndex] < key {
low = midIndex + 1
} else {
high = midIndex
}
}
return low
}
var rightBoundary: Int {
var low = 0
var high = array.count
while low < high {
let midIndex = low + (high - low)/2
if array[midIndex] > key {
high = midIndex
} else {
low = midIndex + 1
}
}
return low
}
return rightBoundary - leftBoundary
}