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 an array whose sum is closest to zero in Pascal

1 Answer

0 votes
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.

*)




 



answered Sep 12, 2025 by avibootz
edited Sep 12, 2025 by avibootz
...