Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,845 questions

51,766 answers

573 users

How to find the two elements in a vector whose sum is closest to zero in Rust

1 Answer

0 votes
use std::cmp::Ordering;

// Function to find the two elements whose sum is closest to zero
fn find_closest_to_zero(vector: &[i32]) {
    if vector.len() < 2 {
        println!("vector must have at least two elements.");
        return;
    }

    // Step 1: Sort the vector
    let mut sorted_vector = vector.to_vec();
    sorted_vector.sort();

    let mut left = 0;
    let mut right = sorted_vector.len() - 1;
    let mut closest_sum = i32::MAX;
    let mut closest_pair = (0, 0);

    // Step 2: Use two-indexed technique
    while left < right {
        let sum = sorted_vector[left] + sorted_vector[right];

        // Update closest sum and pair if needed
        if sum.abs().cmp(&closest_sum.abs()) == Ordering::Less {
            closest_sum = sum;
            closest_pair = (sorted_vector[left], sorted_vector[right]);
        }

        // Move indexeds
        if sum < 0 {
            left += 1; // Increase sum by moving left indexed
        } else {
            right -= 1; // Decrease sum by moving right indexed
        }
    }

    // Output the result
    println!(
        "The two elements whose sum is closest to zero are: {} and {} with a sum of {}.",
        closest_pair.0, closest_pair.1, closest_sum
    );
}

fn main() {
    let vector = vec![23, -26, -88, -42, 55, 99, -11, 90, -13, 17, -31];
    
    find_closest_to_zero(&vector);
}



/*
run:

The two elements whose sum is closest to zero are: -88 and 90 with a sum of 2.

*/

 



answered Sep 13, 2025 by avibootz
...