Find 2 Elements in a Sorted Array with a given Sum – Java Source Code

Find if the sum of two elements in a sorted array sum up to b (a number) with complexity of O(n).

  public static void find2ElementsOfSum(int[] a,int S)
  {
    int left = 0;
    int right = a.length-1;
    while(left < right)
    {
      int sum = a[left]+a[right];
      System.out.println("current Sum="+sum);
      if(sum==S){
       System.out.println("FOUND left="+left+" rigt="+right);
       return;
      }
      if(sum < S)
      {
        left++;
      }else
      {
        right--;
      }
    }
    System.out.println("NOT FOUND");
  }

Leave a Reply