Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

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?

Test your Programming skills with w3resource's quiz.



Java: Tips of the Day

How to sort an ArrayList?

Collections.sort(testList);
Collections.reverse(testList);

That will do what you want. Remember to import Collections though!

Ref: https://bit.ly/32urdSe