w3resource
Java Programming Exercies

Java Array Exercises: Check whether there is a pair with a specified sum of a given sorted and rotated array

Java Array: Exercise-46 with Solution

Write a Java program to check whether there is a pair with a specified sum of a given sorted and rotated array.

Sample Solution:

Java Code:

public class Main
{
     static boolean sum_pair(int arr_int[], 
                                    int n, int x)
    {
        int k;
        for (k = 0; k < n - 1; k++)
            if (arr_int[k] > arr_int[k+1])
                break;
                 
        int l = (k + 1) % n;                           
                       
        int r = k;                          
      
       while (l != r)
        {
             if (arr_int[l] + arr_int[r] == x)
                  return true;
             if (arr_int[l] + arr_int[r] < x)
                  l = (l + 1) % n;
                   
             else
                  r = (n + r - 1) % n;
        }
        return false;
    }
 
 public static void main (String[] args)
    {
        int arr_int[] = {22, 25, 17, 18, 19, 20};
        int sum = 42;
        int n = arr_int.length;
      
        if (sum_pair(arr_int, n, sum))
            System.out.print("Array has a pair of elements with sum 42.");
        else
            System.out.print("Array has no pair with sum 42.");
    }
}

Sample Output:

                                                                              
Array has a pair of elements with sum 42.

Flowchart:

Flowchart: Check whether there is a pair with a specified sum of a given  sorted and rotated array

Visualize Java code execution (Python Tutor):


Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to cyclically rotate a given array clockwise by one.
Next: Write a Java program to find the rotation count in a given rotated sorted array of integers.

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming