Skip to content
This repository has been archived by the owner on Jul 10, 2024. It is now read-only.

Commit

Permalink
Largest 2 elements in Rust added (#5756)
Browse files Browse the repository at this point in the history
Co-authored-by: Riyazul555 <riyazulislam2003@gmail.com>
  • Loading branch information
Riyazul555 and MdRiyazulIslam authored Jun 28, 2024
1 parent 7fb33f0 commit 772d736
Showing 1 changed file with 30 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -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);
}

0 comments on commit 772d736

Please sign in to comment.