rustHow to perform a binary search on a Rust slice?
A binary search is an efficient algorithm for finding an item in a sorted list. In Rust, a binary search can be performed on a slice using the binary_search()
method.
let mut v = vec![1, 2, 3, 4, 5, 6];
v.sort();
let result = v.binary_search(&3);
The output of the above code is Ok(2)
, indicating that the value 3
is located at index 2
in the sorted slice v
.
The binary_search()
method takes a reference to the value to be searched for as an argument and returns a Result
type. If the value is found, the Result
is Ok
with the index of the value in the slice. If the value is not found, the Result
is Err
with the index where the value would be inserted to maintain the sorted order of the slice.
Parts of the code:
let mut v = vec![1, 2, 3, 4, 5, 6];
: creates a mutable vectorv
with the values1
to6
v.sort();
: sorts the vector in ascending orderlet result = v.binary_search(&3);
: performs a binary search on the sorted vectorv
for the value3
Helpful links
Related
- How to convert a Rust slice of u8 to u32?
- How to convert a u8 slice to a hex string in Rust?
- How to convert a Rust slice of u8 to a string?
- How to get the last element of a Rust slice?
- How to convert a Rust slice to a fixed array?
- How to convert a slice of bytes to a string in Rust?
- How to convert a slice to a hex string in Rust?
- How to convert a vector to a Rust slice?
- How to calculate the sum of a Rust slice?
- How to create a slice from a string in Rust?
More of Rust
- How to get a capture group using Rust regex?
- How to use regex with bytes in Rust?
- How to parse JSON string in Rust?
- How to convert a Rust HashMap to a BTreeMap?
- How to use regex to match a group in Rust?
- How to replace a capture group using Rust regex?
- How to use regex to match a double quote in Rust?
- How to implement PartialEq for a Rust HashMap?
- How to use a tuple as a key in a Rust HashMap?
- How to convert a Rust HashMap to a JSON string?
See more codes...