ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Rust Binary Search on Sorted Array

Rust

Goal -- WPM

Ready
Exercise Algorithm Area
1use std::cmp::Ordering;
2
3/// Performs a binary search on a sorted slice to find the index of a target value.
4///
5/// This function uses a recursive helper to implement the binary search logic.
6/// It assumes the input slice is sorted in ascending order.
7///
8/// # Arguments
9///
10/// * `arr` - A sorted slice of elements that implement `Ord` and `Copy`.
11/// * `target` - The value to search for.
12///
13/// # Returns
14///
15/// An `Option<usize>` containing the index of the target if found, otherwise `None`.
16pub fn binary_search<T: Ord + Copy>(arr: &[T], target: T) -> Option<usize> {
17// Handle the edge case of an empty array.
18if arr.is_empty() {
19return None;
20}
21
22// Call the recursive helper function with initial bounds.
23binary_search_recursive(arr, target, 0, arr.len() - 1)
24}
25
26/// Recursive helper function for binary search.
27///
28/// # Arguments
29///
30/// * `arr` - The sorted slice.
31/// * `target` - The value to search for.
32/// * `low` - The lower bound of the current search range (inclusive).
33/// * `high` - The upper bound of the current search range (inclusive).
34///
35/// # Returns
36///
37/// An `Option<usize>` containing the index of the target if found, otherwise `None`.
38fn binary_search_recursive<T: Ord + Copy>(arr: &[T], target: T, low: usize, high: usize) -> Option<usize> {
39// Base case: If the search range is invalid (low > high), the target is not found.
40// This also implicitly handles the case where high might underflow if not careful.
41// We check `low <= high` to ensure valid range.
42if low > high {
43return None;
44}
45
46// Calculate the middle index. Use `low + (high - low) / 2` to prevent potential overflow
47// if `low` and `high` are very large.
48let mid = low + (high - low) / 2;
49
50match arr[mid].cmp(&target) {
51Ordering::Equal => {
52// Target found at the middle index.
53Some(mid)
54}
55Ordering::Less => {
56// Target is in the right half. Recursively search from `mid + 1` to `high`.
57// Ensure `mid + 1` does not overflow `usize` if `mid` is `usize::MAX`.
58// However, given typical array sizes, this is unlikely.
59// The `low > high` check at the start of the next call will handle invalid ranges.
60binary_search_recursive(arr, target, mid + 1, high)
61}
62Ordering::Greater => {
63// Target is in the left half. Recursively search from `low` to `mid - 1`.
64// Handle potential underflow if `mid` is 0.
65if mid == 0 {
66None // Target cannot be in the left half if mid is 0 and it's greater.
67} else {
68binary_search_recursive(arr, target, low, mid - 1)
69}
70}
71}
72}
73
74/// Helper function to create a sample sorted array.
75fn create_sorted_array() -> Vec<i32> {
76vec![2, 5, 8, 12, 16, 23, 38, 56, 72, 91]
77}
78
79/// Main function to demonstrate binary search.
80fn main() {
81let arr = create_sorted_array();
82
83println!("Array: {:?}", arr);
84
85// Test cases
86let targets = vec![23, 2, 91, 7, 0, 100];
87
88for target in targets {
89match binary_search(&arr, target) {
90Some(index) => println!("Target {} found at index: {}", target, index),
91None => println!("Target {} not found in the array.", target),
92}
93}
94
95// Test with an empty array.
96let empty_arr: Vec<i32> = vec![];
97println!("\nSearching in empty array for target 5:");
98match binary_search(&empty_arr, 5) {
99Some(index) => println!("Target 5 found at index: {}", index),
100None => println!("Target 5 not found in the array."),
101}
102
103// Test with a single-element array.
104let single_arr = vec![42];
105println!("\nArray: {:?}", single_arr);
106println!("Searching for 42:");
107match binary_search(&single_arr, 42) {
108Some(index) => println!("Target 42 found at index: {}", index),
109None => println!("Target 42 not found in the array."),
110}
111println!("Searching for 10:");
112match binary_search(&single_arr, 10) {
113Some(index) => println!("Target 10 found at index: {}", index),
114None => println!("Target 10 not found in the array."),
115}
116}
Algorithm description viewbox

Rust Binary Search on Sorted Array

Algorithm description:

This Rust code implements a binary search algorithm, a highly efficient method for finding an item in a sorted array. It works by repeatedly dividing the search interval in half. If the value of the search key is less than the item in the middle of the interval, the algorithm narrows the interval to the lower half. Otherwise, it narrows it to the upper half. This process continues until the value is found or the interval is empty.

Algorithm explanation:

The `binary_search` function finds the index of a `target` in a sorted slice `arr`. It first checks if the array is empty, returning `None` if it is. Otherwise, it calls a recursive helper function `binary_search_recursive` with the array, target, and initial search bounds (0 to `arr.len() - 1`). The recursive helper function has a base case: if `low` becomes greater than `high`, the target is not in the array, and `None` is returned. Otherwise, it calculates the middle index `mid` using `low + (high - low) / 2` to prevent potential integer overflow. It then compares `arr[mid]` with the `target`. If they are equal, `Some(mid)` is returned. If `arr[mid]` is less than `target`, the search continues in the right half by calling `binary_search_recursive(arr, target, mid + 1, high)`. If `arr[mid]` is greater than `target`, the search continues in the left half by calling `binary_search_recursive(arr, target, low, mid - 1)`, with a special check to prevent `mid - 1` from underflowing if `mid` is 0. The time complexity is O(log N) because the search space is halved in each step. The space complexity is O(log N) due to the recursion depth on the call stack. Edge cases handled include empty arrays, targets at the boundaries, targets not present, and potential overflow in `mid` calculation.

Pseudocode:

function binary_search(array arr, target):
  if arr is empty:
    return not_found
  return binary_search_recursive(arr, target, 0, length(arr) - 1)

function binary_search_recursive(array arr, target, low, high):
  if low > high:
    return not_found

  mid = low + (high - low) / 2

  if arr[mid] == target:
    return mid
  else if arr[mid] < target:
    return binary_search_recursive(arr, target, mid + 1, high)
  else: // arr[mid] > target
    if mid == 0:
      return not_found
    else:
      return binary_search_recursive(arr, target, low, mid - 1)