Sunday, June 24, 2018

How do you do search in an array where difference between adjacent elements is always 1

Problem statement: How do you do efficient search in an array where difference between adjacent elements is always 1
  1. public class JumpSearch {
  2. public static void main(String[] args) {
  3. int a[] = { 9, 10, 11, 12, 11, 10, 9, 8, 7, 6, 7, 8, 9, 8, 7, 6, 5};
  4. System.out.println(searchAlgo(a, 7)); // search element is 7
  5. }
  6. // 's' is the element to be searched in array a[0..n-1]
  7. static int searchAlgo(int a[], int s) {
  8. int n = a.length; // length of array
  9. // scan the given array staring from leftmost element
  10. int i = 0; // left first index
  11. while (i < n) {
  12. // check if element is found
  13. if (a[i] == s) {
  14. return i;
  15. }
  16. // else jump to diff. b/w current array element & search element
  17. i = i + Math.abs(a[i] - s);
  18. }
  19. return -1; // element does not found
  20. }
  21. }
Output: 8
Time complexity: less than O(n)

No comments:

Post a Comment

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...