diff --git a/Searching Algorithms/ExponentialSearch.java b/Searching Algorithms/ExponentialSearch.java new file mode 100644 index 0000000..82c5819 --- /dev/null +++ b/Searching Algorithms/ExponentialSearch.java @@ -0,0 +1,23 @@ +import java.util.Arrays; + +class ExponentialSearch { + 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 - 1), x); + } + + public static void main(String[] args) { + int[] arr = { 0, 1, 2, 2, 3, 4, 5, 6, 7, + 8, 11, 34, 56, 89, 90, 90 }; + int x = 5; + int result = exponentialSearch(arr, arr.length, x); + + System.out.println((result < 0) ? "Element is not present in array" : "Element is present at index " + result); + } +} diff --git a/Searching Algorithms/InterpolationSearch.java b/Searching Algorithms/InterpolationSearch.java new file mode 100644 index 0000000..3b033c5 --- /dev/null +++ b/Searching Algorithms/InterpolationSearch.java @@ -0,0 +1,33 @@ +class InterpolationSearch { + public static int interpolationSearch(int[] arr, int lo, int hi, int x) { + int pos; + + if (lo <= hi && x >= arr[lo] && x <= arr[hi]) { + pos = lo + (((hi - lo) / (arr[hi] - arr[lo])) * (x - arr[lo])); + if (arr[pos] == x) + return pos; + + if (arr[pos] < x) + return interpolationSearch(arr, pos + 1, hi, x); + + if (arr[pos] > x) + return interpolationSearch(arr, lo, pos - 1, x); + } + return -1; + } + + public static void main(String[] args) { + + int[] arr = { 0, 1, 2, 2, 3, 4, 5, 6, 7, + 8, 11, 34, 56, 89, 90, 90 }; + int n = arr.length; + + int x = 5; + int index = interpolationSearch(arr, 0, n - 1, x); + + if (index != -1) + System.out.println("Element found at index " + index); + else + System.out.println("Element not found."); + } +}