| 1 | //! The run finder algorithm. Takes an unsorted slice, and returns the number |
| 2 | //! of sequential elements in a row. |
| 3 | |
| 4 | #[cfg(test)] |
| 5 | mod tests; |
| 6 | |
| 7 | use crate::Comparator; |
| 8 | |
| 9 | /// Find a run, reversing if necessary. |
| 10 | pub(crate) fn get_run<T, C: Comparator<T>>(list: &mut [T], cmp: &C) -> Result<usize, C::Error> { |
| 11 | let (ord, len) = find_run(list, cmp)?; |
| 12 | if ord { |
| 13 | list[..len].reverse(); |
| 14 | } |
| 15 | Ok(len) |
| 16 | } |
| 17 | |
| 18 | /// Find a run. Returns true if it needs reversed, and false otherwise. |
| 19 | pub(crate) fn find_run<T, C: Comparator<T>>( |
| 20 | list: &[T], |
| 21 | cmp: &C, |
| 22 | ) -> Result<(bool, usize), C::Error> { |
| 23 | let (first, second) = match list { |
| 24 | [a, b, ..] => (a, b), |
| 25 | _ => return Ok((false, list.len())), |
| 26 | }; |
| 27 | let mut pos = 1; |
| 28 | let gt = if cmp.is_gt(first, second)? { |
| 29 | for pair in list[1..].windows(2) { |
| 30 | if !cmp.is_gt(&pair[0], &pair[1])? { |
| 31 | break; |
| 32 | } |
| 33 | pos += 1; |
| 34 | } |
| 35 | true |
| 36 | } else { |
| 37 | for pair in list[1..].windows(2) { |
| 38 | if cmp.is_gt(&pair[0], &pair[1])? { |
| 39 | break; |
| 40 | } |
| 41 | pos += 1; |
| 42 | } |
| 43 | false |
| 44 | }; |
| 45 | Ok((gt, pos + 1)) |
| 46 | } |