I have an array of this data structure:
typedef struct {
unsigned long id; // Node identification
char *name;
double lat, lon; // Node position
} node;
And I want to do a binary search through the id. I tried defining the function like this
unsigned long bi_search(unsigned long *Vector, unsigned long Vlen, unsigned long target) {
imin = 0; imax = Vlen-1;
while (imax > imin) {
imid = (imax + imin)/2;
if (Vector[imid] == target) {
return imid;
}
else if (Vector[imid] < target) {
imin = imid + 1;
}
else {
imax = imid - 1;
}
}
return -1;
}
And calling it with
bi_search(&nodes->id, nnodes, 0)
The function works for a vector, but I'm not able to make it work to search inside an array of structures.
You need to adjust the signature of your search function and the way you call it.
You have to take a pointer to the first element of an array of the structure type. Inside the function, you'll use vector[i].id
to access the id
member of the i
th element of the array.
unsigned long bi_search(node *vector, unsigned long vlen, unsigned long target)
{
unsigned long imin = 0;
unsigned long imax = vlen - 1;
while (imax > imin)
{
unsigned long imid = (imax + imin) / 2;
if (vector[imid].id == target)
return imid;
else if (vector[imid].id < target)
imin = imid + 1;
else
imax = imid - 1;
}
return ULONG_MAX; // -1 isn't an option
}
You then call it with the start of the array:
unsigned long index = bi_search(nodes, nnodes, 0);