Skip to content

Commit 72878fe

Browse files
committed
Sorted and Rotated array search
1 parent 6226b12 commit 72878fe

2 files changed

Lines changed: 49 additions & 0 deletions

File tree

729 Bytes
Binary file not shown.
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
public class SearchinSortedArray {
2+
public static int Search(int arr[], int target, int start, int end) {
3+
4+
// Base Case
5+
if (start > end) {
6+
return -1;
7+
}
8+
9+
int mid = start + (end - start) / 2;
10+
// if the target element is at the middle of the array
11+
if (target == arr[mid]) {
12+
return mid;
13+
}
14+
// If mid lie on line one
15+
if (arr[start] <= arr[mid]) {
16+
// Left Side: if target is greater then starting element but less than the
17+
// middle element
18+
if (arr[start] <= target && target <= arr[mid]) {
19+
return Search(arr, target, start, mid - 1);
20+
}
21+
// Right Side: if target is
22+
else {
23+
return Search(arr, target, mid + 1, end);
24+
}
25+
26+
}
27+
// If mid lies on the line two
28+
else {
29+
// Right Side: if target is greater then starting element but less than the
30+
// middle element
31+
if (arr[mid] <= target && target <= arr[end]) {
32+
return Search(arr, target, start, mid - 1);
33+
}
34+
// left Side:
35+
else {
36+
return Search(arr, target, mid + 1, end);
37+
}
38+
}
39+
40+
}
41+
42+
public static void main(String[] args) {
43+
int arr[] = { 4, 5, 6, 7, 0, 1, 2, 3 };
44+
int target = 4;
45+
int index = Search(arr, target, 0, arr.length - 1);
46+
System.out.println(index);
47+
}
48+
49+
}

0 commit comments

Comments
 (0)