-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearchInRotatedArray.java
More file actions
executable file
·53 lines (47 loc) · 1.34 KB
/
searchInRotatedArray.java
File metadata and controls
executable file
·53 lines (47 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Neel_Kapadia
*/
import java.util.*;
public class searchInRotatedArray {
int search(int arr[], int element) {
int pivot = 0, index;
while (arr[pivot] < arr[pivot + 1]) {
pivot++;
}
if (element == arr[pivot]) {
return pivot;
}
if (element < arr[0]) {
index = binarySearch(pivot + 1, arr.length - 1, arr, element);
} else {
index = binarySearch(0, pivot, arr, element);
}
return index;
}
int binarySearch(int start, int end, int arr[], int element){
int mid;
while (start <= end) {
mid = (start + end) / 2;
if (arr[mid] == element) {
return mid;
}
if (element < arr[mid]) {
end = mid;
} else {
start = mid + 1;
}
}
return -1;
}
public static void main(String[] args) {
int arr[] = {4, 5, 6, 1, 2, 3};
searchInRotatedArray s = new searchInRotatedArray();
System.out.println(s.search(arr, 9));
}
}