4 ms·
So let's for completenes circle back to the usecase of a certified sorted array, it would be something like this struct Sorted<'a> { reference: &'a
by im3w1l 2y ago
So let's for completenes circle back to the usecase of a certified sorted array, it would be something like this
struct Sorted<'a> {
reference: &'a [i32]
}
impl<'a> Sorted<'a> {
fn in_place<'b: 'a>(source: &'b mut [i32]) -> Sorted<'a> {
source.sort();
Sorted { reference: source }
}
}
fn use_sorted_array(sorted_arr: &Sorted) {
let arr = sorted_arr.reference;
println!("{} {} {}", arr[0], arr[1], arr[2]);
}
fn main() {
let mut arr = [2, 3, 1];
let sorted_arr = Sorted::in_place(&mut arr);
use_sorted_array(&sorted_arr);
}
You might also want to add methods on Sorted for creating a Option<Sorted> by verifying the sortedness of an immutable reference and a method that copies an array and sorts it (it would need to return a struct of a Box for managing the lifetime and a Sorted pointing into the box, or something I guess, probably need to use Pin?)
---
On a completely separate note, this will actually not work for the binary search in the article in question, as it uses binary search on a predicate. Having a sorted array doesn't guarantee that the predicate will be monotonic.