Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// This is returning the index of that element
class Rotated_Binary_Search{
public static void main(String[] args) {

int[] arr = { 4, 5, 6, 7, 0, 1, 2 };
System.out.println(search(arr,5));
}

static int search(int[] nums, int target) {
int pivot = findPivot(nums);
if(pivot ==-1){
return Binarysearch(nums, target, 0, nums.length-1);
}
if(nums[pivot]==target){
return pivot;
}
if(target>=nums[0]){
return Binarysearch(nums, target, 0, pivot-1);
}
return Binarysearch(nums, target, pivot+1, nums.length-1);
}

static int Binarysearch(int[] arr, int target, int start, int end) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This function name should follow camel case.'B' should be small.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A 's' should be capital.


while (start <= end) {
int mid = start + (end - start) / 2;
if (target < arr[mid]) {
end = mid - 1;
} else if (target > arr[mid]) {
start = mid + 1;
} else {
return mid;
}
}
return -1;
}

static int findPivot(int[] arr) {
int start = 0;
int end = arr.length - 1;
while (start <= end) {
int mid = start + (end - start) / 2;
if (mid < end && arr[mid] > arr[mid + 1]) {
return mid;
}
if (mid > start && arr[mid] < arr[mid - 1]) {
return mid - 1;
}
if (arr[mid] <= arr[start]) {
end = mid - 1;
} else {
start = mid + 1;
}
}
return -1;
}
}