Skip to content

Commit 6bd3353

Browse files
authored
Merge pull request darpanjbora#109 from rk-1620/master
new searching algorithm added
2 parents a4c63d6 + 97793e4 commit 6bd3353

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

Searching/exponential_search.java

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// Java program to
2+
// find an element x in a
3+
// sorted array using
4+
// Exponential search.
5+
import java.util.Arrays;
6+
7+
class exponential_search
8+
{
9+
// Returns position of
10+
// first occurrence of
11+
// x in array
12+
static int exponentialSearch(int arr[],int n, int x)
13+
{
14+
// If x is present at first location itself
15+
if (arr[0] == x)
16+
return 0;
17+
18+
// Find range for binary search by
19+
// repeated doubling
20+
int i = 1;
21+
while (i < n && arr[i] <= x)
22+
i = i*2;
23+
24+
// Call binary search for the found range.
25+
return Arrays.binarySearch(arr, i/2,Math.min(i, n-1), x);
26+
}
27+
28+
// Driver code
29+
public static void main(String args[])
30+
{
31+
int arr[] = {2, 3, 4, 10, 40};
32+
int x = 10;
33+
int result = exponentialSearch(arr,arr.length, x);
34+
35+
System.out.println((result < 0) ? "Element is not present in array" : "Element is present at index " + result);
36+
}
37+
}

0 commit comments

Comments
 (0)