Problem statement: How do you do efficient search in an array where difference between adjacent elements is always 1
- public class JumpSearch {
- public static void main(String[] args) {
- int a[] = { 9, 10, 11, 12, 11, 10, 9, 8, 7, 6, 7, 8, 9, 8, 7, 6, 5};
- System.out.println(searchAlgo(a, 7)); // search element is 7
- }
- // 's' is the element to be searched in array a[0..n-1]
- static int searchAlgo(int a[], int s) {
- int n = a.length; // length of array
- // scan the given array staring from leftmost element
- int i = 0; // left first index
- 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
- i = i + Math.abs(a[i] - s);
- }
- return -1; // element does not found
- }
- }
Output: 8
Time complexity: less than O(n)
No comments:
Post a Comment