Reputation: 5438
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 for loop?
Upvotes: 0
Views: 438
Reputation: 10370
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));
}
}
Upvotes: 0
Reputation: 1498
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; }
Upvotes: 0
Reputation: 5693
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/
Upvotes: 1
Reputation: 3375
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?
Upvotes: 0
Reputation: 5388
Is this homework?
You can do it pretty easily with a recursive call, splitting the array in half each time.
Upvotes: 3