Skip to content

Instantly share code, notes, and snippets.

@anil477
Last active November 15, 2017 06:50
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/4495add336bed546d93e7364213e832b to your computer and use it in GitHub Desktop.
Save anil477/4495add336bed546d93e7364213e832b to your computer and use it in GitHub Desktop.
Find pivot in a sorted rotated array
// Find pivot in a sorted rotated array - http://www.ideserve.co.in/learn/find-pivot-in-a-sorted-rotated-array
// Find the minimum element in a sorted and rotated array - http://www.geeksforgeeks.org/find-minimum-element-in-a-sorted-and-rotated-array/
import java.io.*;
import java.util.*;
class Pivot
{
public int recursive(int a[], int low, int high)
{
// already in sorted part sorted
if (a[high] > a[low])
return -1;
while(low <= high)
{
int mid = (high + low)/2;
System.out.println("Low:" + low + " Mid:" + mid + " High: " + high);
if ( (mid == 0 || a[mid-1] > a[mid]) && ((mid == (a.length - 1)) || a[mid] < a[mid+1]))
return mid;
if (a[mid] < a[low])
high = mid-1;
else
low = mid+1;
};
return -1;
}
public static void main(String[] args)
{
Pivot obj = new Pivot();
int a[] = {4, 5, 6, 7, 1};
// int a[] = {15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14};
int n = a.length;
int pivot = obj.recursive(a, 0, n-1);
if (pivot != -1) {
System.out.println( "Pivot Index(0 based) " + pivot);
System.out.println( "Pivot Value/Smallest Value " + a[pivot]);
System.out.println( "Rotated " + pivot + " many times ");
}
else {
System.out.println( "Not Rotated");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment