object ClosestToZero {
// Function to find the two elements whose sum is closest to zero
def findClosestToZero(arr: Array[Int]): Unit = {
if (arr.length < 2) {
println("arr must have at least two elements.")
return
}
// Step 1: Sort the arr
val sortedArr = arr.sorted
var left = 0
var right = sortedArr.length - 1
var closestSum = Int.MaxValue
var closestPair = (0, 0)
// Step 2: Use two-indexed technique
while (left < right) {
val sum = sortedArr(left) + sortedArr(right)
// Update closest sum and pair if needed
if (math.abs(sum) < math.abs(closestSum)) {
closestSum = sum
closestPair = (sortedArr(left), sortedArr(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(s"The two elements whose sum is closest to zero are: ${closestPair._1} and ${closestPair._2} with a sum of $closestSum.")
}
def main(args: Array[String]): Unit = {
val arr = Array(23, -26, -88, -42, 55, 99, -11, 90, -13, 17, -31)
findClosestToZero(arr)
}
}
/*
run:
The two elements whose sum is closest to zero are: -88 and 90 with a sum of 2.
*/