How to find the two largest elements in a vector with Rust

1 Answer

0 votes
// A function that finds the two largest elements in any ordered slice.
// It returns an Option containing a tuple of references to (largest, second_largest).
// Using references (&T) avoids cloning elements and works for any type implementing Ord.
fn find_two_largest<T: Ord>(slice: &[T]) -> Option<(&T, &T)> {
    // A slice must have at least 2 elements to find a second largest.
    if slice.len() < 2 {
        return None;
    }

    // Initialize largest and second largest based on the first two elements
    let (mut largest, mut second) = if slice[0] > slice[1] {
        (&slice[0], &slice[1])
    } else {
        (&slice[1], &slice[0])
    };

    // Iterate through the rest of the slice starting from index 2
    for item in &slice[2..] {
        if item > largest {
            // Found a new absolute maximum; the old maximum becomes the second largest
            second = largest;
            largest = item;
        } else if item > second {
            // Item is greater than second, but not largest
            second = item;
        }
    }

    Some((largest, second))
}

fn main() {
    // Define the vector with the provided data
    let data = vec![3, 4, 9, 6, 7, 1, 2, 5];

    // Call our function and handle the Option result idiomatically using match
    match find_two_largest(&data) {
        Some((largest, second_largest)) => {
            println!("Dataset: {:?}", data);
            println!("The largest element is: {}", largest);
            println!("The second largest element is: {}", second_largest);
        }
        None => {
            println!("Error: The collection must contain at least two elements.");
        }
    }
}


/*
run:

Dataset: [3, 4, 9, 6, 7, 1, 2, 5]
The largest element is: 9
The second largest element is: 7

*/

 



answered 15 hours ago by avibootz
...