开发者

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开发者_Go百科,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 for loop?


Is this homework?

You can do it pretty easily with a recursive call, splitting the array in half each time.


You must use binary search. See wikipedia. http://en.wikipedia.org/wiki/Binary_search

Also in C you can use built-in library function bsearch for binary searching . http://www.cplusplus.com/reference/clibrary/cstdlib/bsearch/


The following code will find the index of the next highest number in an array. But...

#include <stdio.h>

int findIndex(int *array, int value) {
    static int index = 0;
    index++;
    if(array[index] > value)
        printf("Index: %d\n", index);
    else
        return findIndex(array, value);
} // findIndex

int main() {
    int x[] = {23, 36, 45, 62, 79, 103, 109};

    findIndex(x, 67);

    return 0;
}

There is a flaw in this code. Did you notice it?


a: array. low : starting index. high : largest index. number : number to search.

**int subscript( int a[], int low, int high, int number)

{

int mid;

if (number > a[low] && number < a[high])
{

    mid = (low+high)/2;

if a[mid] > number 
        {
             if ( a[mid-1]<=number)
           return mid;
            else return subscript(a, low, mid-1); 
      }

if a[mid]<=number 
         {
             if( a[mid+1] > number)
              return mid+1;
             else
              return subscript(a, mid+1, high);
        }
}

return -1; }


I tested this one out:

~>a.out ARR=23 36 45 62 79 103 109 value: 79, index: 4

there is no bounds checking in this code...

#include <stdio.h>

int findNum(int, int *, int *); 

int main(int argc, char** argv) {
  int list[7] = {23,36,45,62,79,103,109};
  int i, val, idx = 0;

  printf("ARR=");
  for (i=0; i<7; i++) {
    printf("%d ", list[i]);
  }

  val = findNum(67, list, &idx);
  printf("\nvalue: %d, index: %d\n\n", val, idx);

  return(0);
}

int findNum(int num, int *list, int *idx) {

  if (*list <= num) {
    *idx = (*idx)++;
    return(findNum(num,list+1,idx));
  }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜