From 772d736973f2cb2a663856e1729efa8c4ece550c Mon Sep 17 00:00:00 2001 From: Md Riyazul Islam <121575277+Riyazul555@users.noreply.github.com> Date: Fri, 28 Jun 2024 13:37:36 +0530 Subject: [PATCH] Largest 2 elements in Rust added (#5756) Co-authored-by: Riyazul555 --- ...nd_the_largest_two_elements_in_an_array.rs | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 program/program/find-the-largest-two-elements-in-an-array/find_the_largest_two_elements_in_an_array.rs diff --git a/program/program/find-the-largest-two-elements-in-an-array/find_the_largest_two_elements_in_an_array.rs b/program/program/find-the-largest-two-elements-in-an-array/find_the_largest_two_elements_in_an_array.rs new file mode 100644 index 000000000..12581bac7 --- /dev/null +++ b/program/program/find-the-largest-two-elements-in-an-array/find_the_largest_two_elements_in_an_array.rs @@ -0,0 +1,30 @@ +fn find_largest_two_elements(arr: &[i32]) -> (i32, i32) { + if arr.len() < 2 { + panic!("Array must contain at least two elements"); + } + + let mut largest = arr[0]; + let mut second_largest = arr[1]; + + if second_largest > largest { + std::mem::swap(&mut largest, &mut second_largest); + } + + for &num in &arr[2..] { + if num > largest { + second_largest = largest; + largest = num; + } else if num > second_largest { + second_largest = num; + } + } + + (largest, second_largest) +} + +fn main() { + let arr = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]; + let (largest, second_largest) = find_largest_two_elements(&arr); + println!("The largest element is: {}", largest); + println!("The second largest element is: {}", second_largest); +}