Sunday, June 24, 2018

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
  1. public class JumpSearchWithKDiff {
  2. public static void main(String[] args) {
  3. int a[] = { 2, 4, 6, 8, 6, 4, 2, -1, -3 };
  4. int s = -3; // 's' is the element to be searched
  5. int k = 2; // diff. b/w element
  6. int n = a.length; // length of array
  7. System.out.println("Element " + s + " is present at index " + searchAlgo(a, n, s, k));
  8. }
  9. static int searchAlgo(int a[], int n, int s, int k) {
  10. // scan the given array staring from leftmost element
  11. int i = 0;
  12. while (i < n) {
  13. // check if element is found
  14. if (a[i] == s)
  15. return i;
  16. // else jump to diff. b/w current array element & search element
  17. // divided by k We use max here to make sure that i moves at-least one step ahead
  18. i = i + Math.abs(a[i] - s) / k;
  19. // i = i + Math.max(1, Math.abs(a[i] - s) / k);
  20. }
  21. System.out.println("number is " + "not present!");
  22. return -1;
  23. }
  24. }
Output:
Element -3 is present at index 8

No comments:

Post a Comment

How to run standalone mock server on local laptop

 Please download the standalone wiremock server from Direct download section at the bottom of the page.  Download and installation Feel fre...