Skip to content

Commit 8b86539

Browse files
committed
Add exponential search algorithm
1 parent f53bc00 commit 8b86539

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package com.thealgorithms.searchs;
2+
3+
import java.util.Arrays;
4+
5+
public class ExponentialSearch {
6+
// Exponential Search algorithm
7+
public static int exponentialSearch(int[] arr, int x) {
8+
int n = arr.length;
9+
10+
// If the element is present at the first position
11+
if (arr[0] == x) return 0;
12+
13+
// Find the range for binary search by repeated doubling
14+
int i = 1;
15+
while (i < n && arr[i] <= x) {
16+
i = i * 2;
17+
}
18+
19+
// Do binary search in the found range
20+
return binarySearch(arr, x, i / 2, Math.min(i, n - 1));
21+
}
22+
23+
// Binary Search algorithm
24+
private static int binarySearch(int[] arr, int x, int low, int high) {
25+
while (low <= high) {
26+
int mid = low + (high - low) / 2;
27+
28+
if (arr[mid] == x) return mid;
29+
30+
if (arr[mid] < x) low = mid + 1;
31+
else high = mid - 1;
32+
}
33+
return -1; // Element not found
34+
}
35+
36+
public static void main(String[] args) {
37+
int[] arr = {1, 3, 5, 7, 9, 11, 15, 17, 19, 21};
38+
int x = 15;
39+
40+
int result = exponentialSearch(arr, x);
41+
42+
if (result == -1) {
43+
System.out.println("Element not found.");
44+
} else {
45+
System.out.println("Element found at index " + result);
46+
}
47+
}
48+
}

0 commit comments

Comments
 (0)