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:
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
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework