function findClosestToZero(arr: number[]): void {
if (arr.length < 2) {
console.log("arr must have at least two elements.");
return;
}
// Step 1: Sort the arr
const sortedArr: number[] = [...arr].sort((a, b) => a - b);
let left: number = 0;
let right: number = sortedArr.length - 1;
let closestSum: number = Number.MAX_SAFE_INTEGER;
let closestPair: [number, number] = [0, 0];
// Step 2: Use two-indexed technique
while (left < right) {
const sum: number = 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++; // Increase sum by moving left indexed
} else {
right--; // Decrease sum by moving right indexed
}
}
// Output the result
console.log(`The two elements whose sum is closest to zero are:
${closestPair[0]} and ${closestPair[1]} with a sum of ${closestSum}.`);
}
const arr: number[] = [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."
*/