devoalda.gitlab.io/content/en/posts/Rust_Binary_Search.md

1.9 KiB

author authorEmoji title date description draft hideToc enableToc enableTocContent tocPosition tocLevels tags series categories image libraries math
Devoalda 🐺 Rust Binary Search 2023-04-10T21:42:22+08:00 Binary Search in Rust false false true true inner
h1
h2
h3
rust
Searching Algorithm
Binary Search
rust
Searching Algorithm
mathjax
true

Abstract

[Binary Search]( {{< ref "posts/BinarySearch.md" >}}) is one of my favourite searchin algorithms, it is quick and efficient most of the times to search, given a sorted array.

This is an implementation of this algorithm in Rust. This post marks the start of my Rust learning journey. Implementing this algorithm is a must and this allows me to learn the Rust syntax given a familiar algorithm.

In this implementation, a vector is used instead of an array, this allows for dynamic memory allocation of a given list of sorted numbers.

Code

fn main() {
    let vec = vec![1,2,3,4,5,6,7,8,9,10];
    let val = 3;
    let pos = binary_search(vec, val);

    if pos != -1 {
        println!("{} is at position {}", val, pos)
    } else {
        println!("{} is not in the vector", val)
    }
}

fn binary_search(vec: Vec<i32>, val:i32) -> i32{
    let mut left:i32 = 0;
    let mut right:i32 = vec.len() as i32;
    let result = -1;

    while left <= right {
        let mid:i32 = (left + right) >> 1;

        if vec[mid as usize] == val {
            return mid;
        }
        else if vec[mid as usize] < val {
            left = mid + 1;
        }
        else{
            right = mid - 1;
        }
    }
    result
}

Output:

3 is at position 2

Similar to the previous implementation of [Binary Search]( {{< ref "posts/BinarySearch.md" >}}), I used the right shift >> 1 to do the division by 2 to get the mid value, followed by the iterative version of the comparison.