next higher number in a sorted array

I have a sorted array ( in ascending order) and I want to find the subscript of a number in the array which is the the next highest number to a given number. For example,if I have 67 as a given number and if I have an array x=(23,36,45,62,79,103,109), then how do I get the subscript 5 from x (to get 79 which is the next highest to 67) without using a  loop?

Comments

  1. do a binary search, and returns the index +1 when the algo stops.

    ReplyDelete
  2. normal binary search searches for number equality...please check.

    ReplyDelete
  3. Pseudo code:
    search(arr, left, right, val)
    {
    if(left == right)
    return left+1;
    mid = (left+right)/2
    if(val <= arr[mid])
    return search(arr, left, mid-1, val)
    return search(arr, mid+1, right, val)
    }

    ReplyDelete
  4. a fix:
    int search(int* arr, int left, int right, int val)
    {
    if(right < left)
    return right+1;
    int mid = (left+right)/2;
    if(val <= arr[mid])
    return search(arr, left, mid-1, val);
    return search(arr, mid+1, right, val);
    }
    is this correct?
    please response :)

    ReplyDelete
  5. @Or in your code if you will give 23 as input val then o/p index is 0 ,but according to problem it should be 1.so please check for equality condition rest if working fine...

    ReplyDelete
  6. please see this

    int search(int* arr, int left, int right, int val)
    {
    if(right < left)
    return -1;
    int mid = (left+right)/2;
    if(val < arr[mid] && (mid == 0 || val >= arr[mid-1]))
    return mid;
    if(val >= arr[mid])
    return search(arr, mid+1, right, val);
    return search(arr, left,mid-1, val);

    }

    ReplyDelete
  7. @PRIYARANJAN:
    if you give 23 as input then you get 0 which is actually good output because it's zero based.

    ReplyDelete
  8. @Or according to problem statement you have to find subscript of next higher number in the array.so on inputting 23 it should give next higher number than 23, and you haven't checked for non-existence of value..please comment..:)

    ReplyDelete
  9. Ok. now i hope that's fine:
    int search(int* arr, int left, int right, int val)
    {
    if(right < left)
    return right+1;
    int mid = (left+right)/2;
    if(val < arr[mid])
    return search(arr, left, mid-1, val);
    return search(arr, mid+1, right, val);
    }

    ReplyDelete

Post a Comment

Popular posts from this blog