Skip to content

Instantly share code, notes, and snippets.

@anil477
Created June 14, 2017 15:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anil477/9301120f83321ae3aa239de197a9e7d5 to your computer and use it in GitHub Desktop.
Save anil477/9301120f83321ae3aa239de197a9e7d5 to your computer and use it in GitHub Desktop.
Sum Pair in Sorted Rotated Array
import java.io.*;
import java.util.*;
class Pivot
{
public void recursive(int a[], int low, int high, int sum)
{
// already in sorted part sorted
if (a[high] > a[low]){
System.out.println("Not rotated");
return;
}
int length = a.length;
int mid = -1;
while(low <= high)
{
mid = (high + low)/2;
// System.out.println(" Mid: " + mid);
if (mid < a.length-1 && a[mid] > a[mid+1])
break;
//return (mid+1);
if (a[low] <= a[mid])
low = mid + 1;
else
high = mid - 1;
};
int max = mid;
int min = (mid +1)%length;
while(mid==max) {
if((a[min] + a[max]) == sum) {
System.out.println( " Sum Pair found :" + a[min] + " " + a[max]);
return;
}
if((a[min] + a[max]) > sum)
{
max = (max - 1 + length)%length;
}else{
min = (min + 1)%length;
}
};
System.out.println( " No Result ");
return;
}
public static void main(String[] args)
{
Pivot obj = new Pivot();
int a[] = {6, 7, 16, 1, 2, 3, 4, 5};
//int a[] = {15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14};
int n = a.length;
int sum = 22;
obj.recursive(a, 0, n-1, sum);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment