Tuesday, August 8, 2017

Exponential Search Algorithm and its implementation in java

Exponential Search

It works in O(Log n) time.We have discussed, linear search, binary search for this problem.

Exponential search involves two steps:

1)Find range where element is present

2)Do Binary Search in above found range.

How to find the range where element may be present?

The idea is to start with subarray size 1 compare its last element with x, then try size 2, then 4 and so on until last element of a subarray is not greater.

Once we find an index i (after repeated doubling of i), we know that the element must be present between i/2 and i (Why i/2? because we could not find a greater value in previous iteration).

Sample Code:

import java.util.Arrays;

class ExponentialSearchApp
{

static int exponentialSearch(int arr[], int n, int x)
{

if (arr[0] == x)
return 0;

int i = 1;
while (i < n && arr[i] <= x)
i = i*2;

return Arrays.binarySearch(arr, i/2, Math.min(i, n), x);
}

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);
}
}

Output: Element is present at index 3.

Time Complexity : O(Log n)

Auxiliary Space : The above implementation of Binary Search is recursive and requires O()Log n) space.
Iterative Binary Search, we need only O(1) space.

Applications of Exponential Search:

Exponential Binary Search is particularly useful for unbounded searches, where size of array is infinite.

Please google search about Unbounded Binary Search.

It works better than Binary Search for bounded arrays also when the element to be searched is closer to the first element.

No comments: