From a012b6568f5402f92a07f3c3116ad728ef46cadd Mon Sep 17 00:00:00 2001 From: Madhan Murugan <91775905+Capt-Madhan@users.noreply.github.com> Date: Thu, 7 Oct 2021 23:46:13 +0530 Subject: [PATCH] chore(Java): added exponential search (#523) Co-authored-by: Ming Tsai <37890026+ming-tsai@users.noreply.github.com> --- algorithms/Java/README.md | 3 +- .../Java/searching/Exponential-search.java | 31 +++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 algorithms/Java/searching/Exponential-search.java diff --git a/algorithms/Java/README.md b/algorithms/Java/README.md index b787d685..63dc1929 100644 --- a/algorithms/Java/README.md +++ b/algorithms/Java/README.md @@ -44,7 +44,8 @@ 2. [Jump Search](searching/jump-search.java) 3. [Linear Search](searching/linear-search.java) 4. [Allocate minimum number of pages](searching/allocate-min-pages.java) -5. [Interpolation Search](searching/interpolation-search.java) +5. [Exponential Search](searching/Exponential-search.java) +6. [Interpolation Search](searching/interpolation-search.java) ## Sorting diff --git a/algorithms/Java/searching/Exponential-search.java b/algorithms/Java/searching/Exponential-search.java new file mode 100644 index 00000000..9525878f --- /dev/null +++ b/algorithms/Java/searching/Exponential-search.java @@ -0,0 +1,31 @@ +// Java program to find an element x in a sorted array using Exponential search. +import java.util.Arrays; + +class ExponentialSearch +{ + // Returns position of first occurrence of x in array + static int exponentialSearch(int arr[], int n, int x) + { + // If x is present at first location itself + if (arr[0] == x) + return 0; + + // Find range for binary search by repeated doubling + int i = 1; + while (i < n && arr[i] <= x) + i = i*2; + + // Call binary search for the found range. + return Arrays.binarySearch(arr, i/2, Math.min(i, n-1), x); + } + + // Driver code + public static void main(String args[]) + { + int arr[] = {2, 3, 4, 10, 40}; + int x = 10; + int result = exponentialSearch(arr, arr.length, x); + + System.out.println((result < 0) ? "Element is not present in array" : "Element is present at index " + result); + } +}