Created
September 26, 2013 20:04
-
-
Save kmdarshan/6719785 to your computer and use it in GitHub Desktop.
//Given a sorted list 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 list. //567812 -> (1) true 1 2 3 4 5 6
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Search { | |
public static boolean binsearch(int [] a, int value){ | |
int low =0; | |
int high = arr.length - 1; | |
int mid = 0; | |
while(low <= high) { // binsearch(a, 1, 4, 4) | |
mid = (low+high) / 2; // 4 | |
if(a[mid] > value) { | |
high = mid - 1; | |
} else if (a[mid] < value) { | |
low = mid +1 ; | |
}else{ | |
return mid; | |
} | |
} | |
public static int recursiveSearch(int a[], int value, int low, int high) { | |
if(low > high){ | |
return -1; | |
} | |
low = 0; | |
high = | |
int mid = low + high / 2; | |
if(a[mid] == value){ | |
return 1; | |
} | |
if(a[mid] >= a[low]){ | |
// checking if value is within the subarray | |
if(value >= a[low] && value < a[middle]){ | |
// sorted array | |
return binsearch(a, value, low, middle-1); | |
} | |
return recursiveSearch(a, value, middle+1, high); | |
} | |
else if(a[mid] <= a[high]){ | |
// the other range | |
if(value > a[middle] && value <= a[high]){ | |
// sorted array | |
return binsearch(a, value, middle+1, high); | |
} | |
return recursiveSearch(a, value, low, middle-1); | |
}else{ | |
// asserting that it should be false; | |
return -1; | |
} | |
} | |
} | |
public static void main(String [] args){ | |
int [] arr = { 5, 6, 7, 8, 1, 2}; | |
System.out.println(recursiveSearch(a,1, 0, arr.length-1)?true:false); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment