From c579b8aa879ccab7bc19522fcbec5591966cb3d1 Mon Sep 17 00:00:00 2001 From: Nisarg Bhavsar <86922099+NisargBhavsar25@users.noreply.github.com> Date: Wed, 19 Oct 2022 21:13:25 +0530 Subject: [PATCH 1/2] Added Interpolation Search --- Searching Algorithms/InterpolationSearch.java | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Searching Algorithms/InterpolationSearch.java 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."); + } +} From 9a580f8ec18479809def2a73e345dcd6a1c7b9c0 Mon Sep 17 00:00:00 2001 From: Nisarg Bhavsar <86922099+NisargBhavsar25@users.noreply.github.com> Date: Wed, 19 Oct 2022 21:20:25 +0530 Subject: [PATCH 2/2] Added Exponential Search --- Searching Algorithms/ExponentialSearch.java | 23 +++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Searching Algorithms/ExponentialSearch.java 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); + } +}