线性搜索

alt text

From Wikipedia: linear search or sequential search is a method for finding a target value within a list. It sequentially checks each element of the list for the target value until a match is found or until all the elements have been searched. Linear search runs in at worst linear time and makes at most n comparisons, where n is the length of the list.

Properties

  • Worst case performance O(n)
  • Best case performance O(1)
  • Average case performance O(n)
  • Worst case space complexity O(1) iterative
  1. use std::cmp::PartialEq;
  2. pub fn linear_search<T: PartialEq>(item: &T, arr: &[T]) -> Option<usize> {
  3. for (i, data) in arr.iter().enumerate() {
  4. if item == data {
  5. return Some(i);
  6. }
  7. }
  8. None
  9. }
  10. #[cfg(test)]
  11. mod tests {
  12. use super::*;
  13. #[test]
  14. fn search_strings() {
  15. let index = linear_search(&"a", &vec!["a", "b", "c", "d", "google", "zoo"]);
  16. assert_eq!(index, Some(0));
  17. }
  18. #[test]
  19. fn search_ints() {
  20. let index = linear_search(&4, &vec![1, 2, 3, 4]);
  21. assert_eq!(index, Some(3));
  22. let index = linear_search(&3, &vec![1, 2, 3, 4]);
  23. assert_eq!(index, Some(2));
  24. let index = linear_search(&2, &vec![1, 2, 3, 4]);
  25. assert_eq!(index, Some(1));
  26. let index = linear_search(&1, &vec![1, 2, 3, 4]);
  27. assert_eq!(index, Some(0));
  28. }
  29. #[test]
  30. fn not_found() {
  31. let index = linear_search(&5, &vec![1, 2, 3, 4]);
  32. assert_eq!(index, None);
  33. }
  34. #[test]
  35. fn empty() {
  36. let index = linear_search(&1, &vec![]);
  37. assert_eq!(index, None);
  38. }
  39. }