Implement Exponential Search Algorithm (fixes #54) #124
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This pull request addresses issue #54 by implementing the Exponential Search Algorithm. I have a solid understanding of searching algorithms and am confident in delivering an efficient solution.
High-Level Approach
Exponential Search Function:
Created a function exponentialSearch to locate the range in which the target element might be present.
Performed a binary search within that interval to find the target element.
Binary Search Function:
Created a helper function binarySearch to conduct the search within the identified range from the Exponential Search Function.
Testing the Implementation:
Built test sorted arrays and thoroughly tested the functions to ensure proper working.
Detailed Implementation
Exponential Search Function
java
public static int exponentialSearch(int[] arr, int target) {
int n = arr.length;
if (arr[0] == target) {
return 0;
}
int i = 1;
while (i < n && arr[i] <= target) {
i = i * 2;
}
return binarySearch(arr, target, i / 2, Math.min(i, n - 1));
}
Binary Search Function
java
public static int binarySearch(int[] arr, int target, int left, int right) {
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
}
if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1; // target not found
}
Main Method for Testing
java
public static void main(String[] args) {
int[] arr = {2, 3, 4, 10, 40, 50, 60, 70, 80, 90};
int target = 10;
int result = exponentialSearch(arr, target);
if (result != -1) {
System.out.println("Element found at index: " + result);
} else {
System.out.println("Element not found in array.");
}
}
Testing
Created test arrays with different target values to verify the implementation.
Ensured that both edge cases and typical scenarios are handled correctly.
Verified that the solution works efficiently on large arrays.