#binary-search #find #search-algorithms #max #algorithm #sorting #recursion

thinkrust_algorithms

Basic Algorithms: Binary Search and Find Max from an array

3 releases

new 0.1.2 Jan 29, 2025
0.1.1 Jan 29, 2025
0.1.0 Jan 29, 2025

#856 in Algorithms

MIT license

7KB
77 lines

Binary Search and Max Finder Crate

This crate provides two utility functions:

  1. binary_search: A function that performs a binary search to find the index of an item in a sorted vector.
  2. find_max_recursive: A recursive function to find the maximum value in a vector of integers.

Features

  • Implements a binary search algorithm for sorted collections.
  • Implements a recursive algorithm to find the maximum value in a collection of integers.
  • Provides tests to ensure correctness and handle edge cases.

Usage

To use the binary_search function, you can call it with a sorted vector and the item to search for. It returns the index of the item if found, or None if not.

use your_crate_name::binary_search;

let items = vec![16, 32, 64, 128, 256, 512, 1024];
let result = binary_search(items, 256);

match result {
    Some(index) => println!("Item found at index: {}", index),
    None => println!("Item not found"),
}

Find Maximum Value Recursively

To use the find_max_recursive function, call it with a vector of integers. It returns the maximum value in the vector or 0 if the vector is empty.

use your_crate_name::find_max_recursive;

let items = vec![8, 12, 128, 1, 90, -1, 32];
let max_value = find_max_recursive(&items);

println!("The maximum value is: {}", max_value);

Function Details

pub fn binary_search<T>(list: Vec<T>, item: T) -> Option<usize>
where
    T: std::cmp::Ord,

Parameters:

  • list: A vector of elements that must be sorted in ascending order.
  • item: The element to search for in the vector.

Returns:

  • Some(usize): The index of the item in the list if found.
  • None: If the item is not found in the list.

find_max_recursive

pub fn find_max_recursive(coll: &Vec<i32>) -> i32

Parameters:

  • coll: A reference to a vector of integers (Vec<i32>) to find the maximum value in.

Returns:

  • i32: The maximum value in the vector. Returns 0 if the vector is empty.

Testing

This crate includes the following tests:

  • returns_none_if_items_is_empty: Ensures that an empty list returns None.
  • doesnt_finds_if_collection_is_not_sorted: Tests that unsorted lists do not return a valid result.
  • finds_index_of_element: Verifies that the index of an element is found in a sorted list.

For find_max_recursive:

  • finds_the_greatest_value: Verifies that the maximum value is correctly found in a non-empty vector.
  • returns_zero_if_empty_vec_is_provided: Ensures that an empty vector returns 0.

Running Tests

To run the tests for both functions, use the following command:

cargo test

License

This crate is licensed under the MIT License.

No runtime deps