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
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
use std::{cmp::Ordering, ops::Index};
use Ordering::{Equal, Greater, Less};

pub trait BinarySearch: Index<usize> {
    /// performs binary search between the `start` and `end` indices
    /// `start`: start index
    /// `end`: end index exclusive
    /// `cmp`: a function that returns `Ordering::Less` when the first argument is less than the
    /// second, etc. returns the index of the target element as `Some(usize)` if present, `Err`
    /// otherwise. In the case of returning an `Err`, the associated value is `Some(usize)`
    /// representing the index at which the target value can be inserted while maintaining the
    /// sorted order, or `None` if the provided `[start, end)` range is empty, i.e. when `start
    /// >= end`.
    fn binary_search_with_cmp<E, F>(
        &self,
        start: usize,
        end: usize,
        target: &E,
        cmp: F,
    ) -> Result<usize, Option<usize>>
    where
        F: Fn(&<Self as Index<usize>>::Output, &E) -> Ordering;
}

impl<T> BinarySearch for Vec<T> {
    fn binary_search_with_cmp<E, F>(
        &self,
        start: usize,
        end_exclusive: usize,
        target: &E,
        cmp: F,
    ) -> Result<usize, Option<usize>>
    where
        F: Fn(&<Self as Index<usize>>::Output, &E) -> Ordering, {
        if start >= end_exclusive {
            return Err(None);
        }
        let mut start = start;
        // now end is inclusive
        let mut end = end_exclusive - 1;
        if cmp(&self[start], target) == Ordering::Greater {
            return Err(Some(start));
        }
        if cmp(&self[end], target) == Ordering::Less {
            return Err(Some(end + 1));
        }
        let mut mid = (start + end) / 2;
        while end > start {
            match cmp(&self[mid], target) {
                Less => {
                    start = mid + 1;
                    mid = (start + end) / 2;
                }
                Greater => {
                    end = mid;
                    mid = (start + end) / 2;
                }
                Equal => return Ok(mid),
            };
        }
        match cmp(&self[mid], target) {
            Equal => Ok(mid),
            Less => Err(Some(mid + 1)),
            Greater => Err(Some(mid)),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::BinarySearch;

    #[test]
    fn test_vec_binary_search() {
        let v = vec![1, 2, 3, 6, 29, 43, 69, 100, 340];
        assert_eq!(
            BinarySearch::binary_search_with_cmp(&v, 0, v.len(), &30, |x, y| x.cmp(y)),
            Err(Some(5))
        );
        assert_eq!(
            BinarySearch::binary_search_with_cmp(&v, 0, v.len(), &-10, |x, y| x.cmp(y)),
            Err(Some(0))
        );
        assert_eq!(
            BinarySearch::binary_search_with_cmp(&v, 0, v.len(), &0, |x, y| x.cmp(y)),
            Err(Some(0))
        );
        assert_eq!(
            BinarySearch::binary_search_with_cmp(&v, 0, v.len(), &341, |x, y| x.cmp(y)),
            Err(Some(v.len()))
        );
        assert_eq!(
            BinarySearch::binary_search_with_cmp(&v, 0, v.len(), &1000, |x, y| x.cmp(y)),
            Err(Some(v.len()))
        );
        assert_eq!(
            BinarySearch::binary_search_with_cmp(&v, 0, v.len(), &1, |x, y| x.cmp(y)),
            Ok(0)
        );
        assert_eq!(
            BinarySearch::binary_search_with_cmp(&v, 0, v.len(), &2, |x, y| x.cmp(y)),
            Ok(1)
        );
        assert_eq!(
            BinarySearch::binary_search_with_cmp(&v, 0, v.len(), &3, |x, y| x.cmp(y)),
            Ok(2)
        );
        assert_eq!(
            BinarySearch::binary_search_with_cmp(&v, 0, v.len(), &6, |x, y| x.cmp(y)),
            Ok(3)
        );
        assert_eq!(
            BinarySearch::binary_search_with_cmp(&v, 0, v.len(), &29, |x, y| x.cmp(y)),
            Ok(4)
        );
        assert_eq!(
            BinarySearch::binary_search_with_cmp(&v, 0, v.len(), &43, |x, y| x.cmp(y)),
            Ok(5)
        );
        assert_eq!(
            BinarySearch::binary_search_with_cmp(&v, 0, v.len(), &69, |x, y| x.cmp(y)),
            Ok(6)
        );
        assert_eq!(
            BinarySearch::binary_search_with_cmp(&v, 0, v.len(), &100, |x, y| x.cmp(y)),
            Ok(7)
        );
        assert_eq!(
            BinarySearch::binary_search_with_cmp(&v, 0, v.len(), &340, |x, y| x.cmp(y)),
            Ok(8)
        );
        assert_eq!(
            BinarySearch::binary_search_with_cmp(&v, 3, 6, &6, |x, y| x.cmp(y)),
            Ok(3)
        );
        assert_eq!(
            BinarySearch::binary_search_with_cmp(&v, 3, 6, &29, |x, y| x.cmp(y)),
            Ok(4)
        );
        assert_eq!(
            BinarySearch::binary_search_with_cmp(&v, 3, 6, &43, |x, y| x.cmp(y)),
            Ok(5)
        );
        assert_eq!(
            BinarySearch::binary_search_with_cmp(&v, 3, 6, &340, |x, y| x.cmp(y)),
            Err(Some(6))
        );
        assert_eq!(
            BinarySearch::binary_search_with_cmp(&v, 3, 6, &2, |x, y| x.cmp(y)),
            Err(Some(3))
        );
        assert_eq!(
            BinarySearch::binary_search_with_cmp(&v, 3, 6, &3, |x, y| x.cmp(y)),
            Err(Some(3))
        );
        assert_eq!(
            BinarySearch::binary_search_with_cmp(&v, 3, 6, &69, |x, y| x.cmp(y)),
            Err(Some(6))
        );
        let v = vec![-10];
        assert_eq!(
            BinarySearch::binary_search_with_cmp(&v, 0, v.len(), &9, |x, y| x.cmp(y)),
            Err(Some(1))
        );
        assert_eq!(
            BinarySearch::binary_search_with_cmp(&v, 0, v.len(), &-10, |x, y| x.cmp(y)),
            Ok(0)
        );
        let v = vec![-10, 1];
        assert_eq!(
            BinarySearch::binary_search_with_cmp(&v, 0, v.len(), &1, |x, y| x.cmp(y)),
            Ok(1)
        );
        assert_eq!(
            BinarySearch::binary_search_with_cmp(&v, 0, v.len(), &-10, |x, y| x.cmp(y)),
            Ok(0)
        );
    }
}