program ClosestToZero;
const
MAX_INT = 32767;
type
IntArray = array[1..100] of integer;
var
arr: IntArray;
n: integer;
// Procedure to sort the array using simple Bubble Sort
procedure SortArray(var a: IntArray; size: integer);
var
i, j, temp: integer;
begin
for i := 1 to size - 1 do
for j := i + 1 to size do
if a[i] > a[j] then
begin
temp := a[i];
a[i] := a[j];
a[j] := temp;
end;
end;
// Procedure to find the pair with sum closest to zero
procedure FindClosestToZero(a: IntArray; size: integer);
var
left, right: integer;
closestSum: integer;
closestPair1, closestPair2: integer;
sum: integer;
begin
if size < 2 then
begin
writeln('Array must have at least two elements.');
exit;
end;
// Step 1: Sort the array
SortArray(a, size);
left := 1;
right := size;
closestSum := MAX_INT;
// Step 2: Two-indexed technique
while left < right do
begin
sum := a[left] + a[right];
// Update closest sum and pair if needed
if abs(sum) < abs(closestSum) then
begin
closestSum := sum;
closestPair1 := a[left];
closestPair2 := a[right];
end;
// Move indexeds
if sum < 0 then
inc(left) // Increase sum by moving left indexed
else
dec(right); // Decrease sum by moving right indexed
end;
// Output the result
writeln('The two elements whose sum is closest to zero are: ',
closestPair1, ' and ', closestPair2,
' with a sum of ', closestSum, '.');
end;
begin
// Initialize array
n := 11;
arr[1] := 23;
arr[2] := -26;
arr[3] := -88;
arr[4] := -42;
arr[5] := 55;
arr[6] := 99;
arr[7] := -11;
arr[8] := 90;
arr[9] := -13;
arr[10] := 17;
arr[11] := -31;
FindClosestToZero(arr, n);
end.
(*
run:
The two elements whose sum is closest to zero are: -88 and 90 with a sum of 2.
*)