Skip to content

Instantly share code, notes, and snippets.

@caot
Forked from kmdarshan/gist:6719785
Last active August 29, 2015 14:02
Show Gist options
  • Save caot/2ef08a277e489b3967db to your computer and use it in GitHub Desktop.
Save caot/2ef08a277e489b3967db to your computer and use it in GitHub Desktop.
Given a sorted array that has been transposed (that is, a portion has been removed from one end and attached to the other), write a function to determine if a given number is present in the array. Example: (7, 8, 9, 10, 1, 2, 3, 4, 5, 6) => find 9, 5, 11;
class SortedArray {
static boolean ispresent(int[] a, int i) {
return i == find(a, 0, a.length - 1, i);
}
static int find(int[] a, int low, int high, int i) {
int m = low + (high - low) / 2;
if (i == a[m])
return i;
if (((a[low] <= i || i < a[m]) && a[low] > a[m]) ||
(a[low] <= i && i < a[m]) )
return find(a, low, m - 1, i);
if ( ((a[m] < i || i <= a[high]) && a[m] > a[high] ) ||
(a[m] < i && i <= a[high]) )
return find(a, m + 1, high, i);
return i - 1;
}
public static void main(String[] args) {
int[] a = { 7, 8, 9, 10, 1, 2, 3, 4, 5, 6 };
for (int x : a)
System.out.println(x + ": " + find(a, x));
for (int x : new int[]{-1, 0, 11, Integer.MIN_VALUE, Integer.MAX_VALUE})
System.out.println(x + ": " + find(a, x));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment