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

76 lines
1.9 KiB
Markdown

---
author: "Devoalda"
authorEmoji: 🐺
title: "Rust Binary Search"
date: 2023-04-10T21:42:22+08:00
description: Binary Search in Rust
draft: false
hideToc: false
enableToc: true
enableTocContent: true
tocPosition: inner
tocLevels: ["h1", "h2", "h3"]
tags:
- rust
- Searching Algorithm
- Binary Search
series:
- rust
categories:
- Searching Algorithm
image:
libraries:
- mathjax
math: 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
```rust
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:
```bash
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.