How do you do search in an array where difference between adjacent elements is k
Problem statement: How do you do efficient search in an array where difference between adjacent elements is k
- public class JumpSearchWithKDiff {
- public static void main(String[] args) {
- int a[] = { 2, 4, 6, 8, 6, 4, 2, -1, -3 };
- int s = -3; // 's' is the element to be searched
- int k = 2; // diff. b/w element
- int n = a.length; // length of array
- System.out.println("Element " + s + " is present at index " + searchAlgo(a, n, s, k));
- }
- static int searchAlgo(int a[], int n, int s, int k) {
- // scan the given array staring from leftmost element
- int i = 0;
- while (i < n) {
- // check if element is found
- if (a[i] == s)
- return i;
- // else jump to diff. b/w current array element & search element
- // divided by k We use max here to make sure that i moves at-least one step ahead
- i = i + Math.abs(a[i] - s) / k;
- // i = i + Math.max(1, Math.abs(a[i] - s) / k);
- }
- System.out.println("number is " + "not present!");
- return -1;
- }
- }
Output:
Element -3 is present at index 8
Comments
Post a Comment