#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <math.h>
int compareInts(const void *a, const void *b) {
return (*(int *)a - *(int *)b);
}
// Finds the two elements whose sum is closest to zero
void findClosestToZero(int arr[], int size) {
if (size < 2) {
printf("Array must have at least two elements.\n");
return;
}
// Step 1: Sort the array
qsort(arr, size, sizeof(int), compareInts);
int left = 0;
int right = size - 1;
int closestSum = INT_MAX;
int closestPair[2] = {0, 0};
// Step 2: Use two-indexes technique
while (left < right) {
int sum = arr[left] + arr[right];
// Update closest sum and pair if needed
if (abs(sum) < abs(closestSum)) {
closestSum = sum;
closestPair[0] = arr[left];
closestPair[1] = arr[right];
}
// Move indexess
if (sum < 0) {
left++; // Increase sum
} else {
right--; // Decrease sum
}
}
// Output the result
printf("The two elements whose sum is closest to zero are: %d and %d with a sum of %d.\n",
closestPair[0], closestPair[1], closestSum);
}
int main() {
int arr[] = {23, -26, -88, -42, 55, 99, -11, 90, -13, 17, -31};
int size = sizeof(arr) / sizeof(arr[0]);
findClosestToZero(arr, size);
return 0;
}
/*
run:
The two elements whose sum is closest to zero are: -88 and 90 with a sum of 2.
*/