二分搜索

alt text

From Wikipedia: Binary search, also known as half-interval search or logarithmic search, is a search algorithm that finds the position of a target value within a sorted array. It compares the target value to the middle element of the array; if they are unequal, the half in which the target cannot lie is eliminated and the search continues on the remaining half until it is successful.

Properties

  • Worst case performance O(log n)
  • Best case performance O(1)
  • Average case performance O(log n)
  • Worst case space complexity O(1)
  1. use std::cmp::Ordering;
  2. pub fn binary_search<T: Ord>(item: &T, arr: &[T]) -> Option<usize> {
  3. let mut left = 0;
  4. let mut right = arr.len();
  5. while left < right {
  6. let mid = left + (right - left) / 2;
  7. match item.cmp(&arr[mid]) {
  8. Ordering::Less => right = mid,
  9. Ordering::Equal => return Some(mid),
  10. Ordering::Greater => left = mid + 1,
  11. }
  12. }
  13. None
  14. }
  15. #[cfg(test)]
  16. mod tests {
  17. use super::*;
  18. #[test]
  19. fn empty() {
  20. let index = binary_search(&"a", &vec![]);
  21. assert_eq!(index, None);
  22. }
  23. #[test]
  24. fn one_item() {
  25. let index = binary_search(&"a", &vec!["a"]);
  26. assert_eq!(index, Some(0));
  27. }
  28. #[test]
  29. fn search_strings() {
  30. let index = binary_search(&"a", &vec!["a", "b", "c", "d", "google", "zoo"]);
  31. assert_eq!(index, Some(0));
  32. }
  33. #[test]
  34. fn search_ints() {
  35. let index = binary_search(&4, &vec![1, 2, 3, 4]);
  36. assert_eq!(index, Some(3));
  37. let index = binary_search(&3, &vec![1, 2, 3, 4]);
  38. assert_eq!(index, Some(2));
  39. let index = binary_search(&2, &vec![1, 2, 3, 4]);
  40. assert_eq!(index, Some(1));
  41. let index = binary_search(&1, &vec![1, 2, 3, 4]);
  42. assert_eq!(index, Some(0));
  43. }
  44. #[test]
  45. fn not_found() {
  46. let index = binary_search(&5, &vec![1, 2, 3, 4]);
  47. assert_eq!(index, None);
  48. }
  49. }