Friday 21 October 2016

Find two elements in Array whose sum is Zero

SumZeroAmazon.com
import java.util.Arrays;

/**
 * Class to find the pair whose sum equal to zero.
 * @author rajesh.kumar
 */
public class SumZeroAmazon {

     public static void main(String[] args) {
           int[] array = {10,12,14,16,-8,10,18,19,6,-6};

           getPairWithZeroSum(array);

     }

     /**
      * Method to print the pair.
      * @param array
      */
     private static void getPairWithZeroSum(int[] array) {
           Arrays.sort(array);
           int length = array.length;
          
           if(length==0 || length==1) {
                System.out.println("No pair exists !!");
           }
          
           int i = 0;
           int j = length -1;
          
           while (i  <  j) {

                /* If sum of the elements at index i and j equals 0 */
                if (array[i] + array[j] == 0) {
                     System.out.println("Pair is ("+array[i]+","+array[j]+")");
                     return;
                } else if(Math.abs(array[i]) > Math.abs(array[j])) {
                     i++;
                } else {
                     j--;
                }
           }
           System.out.println("No pair exists !!");
     }
}

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...