Hi,
Trying to do a binary search but couldnt figure out where I am going wrong any help is greatly appreciated. I have product id and quantity as columns in database table and I am loading from the table to an array of structures. I am trying to find the quantity for a particular structure using binary search but it doesnt return the correct value.
#define MAX 3000
typedef struct {
long prodid;
long quantity;
} myrecords;
myrecords memdb[MAX];
main()
{
long prod_id, quant;
myrecords *p;
prod_id = 1874;
loadDBmem();
p = bsearch(&prod_id, memdb, MAX, sizeof(myrecords), comp);
printf("quantity: %d, product ID: %d\n", p->quantity,
p->prodid);
}
int comp(const void *a, const void *b)
{
long *myarray;
myarray = (long *)b;
if( *(long *)a == *myarray)
{
return 0;
}
else if( *(long *)a > *myarray)
{
return 1;
}
else
{
return -1;
}
}
int loadDBmem()
{
connect to database;
load product id and quantity into array of structures;
disconnect from database;
}
Thanks
Trying to do a binary search but couldnt figure out where I am going wrong any help is greatly appreciated. I have product id and quantity as columns in database table and I am loading from the table to an array of structures. I am trying to find the quantity for a particular structure using binary search but it doesnt return the correct value.
#define MAX 3000
typedef struct {
long prodid;
long quantity;
} myrecords;
myrecords memdb[MAX];
main()
{
long prod_id, quant;
myrecords *p;
prod_id = 1874;
loadDBmem();
p = bsearch(&prod_id, memdb, MAX, sizeof(myrecords), comp);
printf("quantity: %d, product ID: %d\n", p->quantity,
p->prodid);
}
int comp(const void *a, const void *b)
{
long *myarray;
myarray = (long *)b;
if( *(long *)a == *myarray)
{
return 0;
}
else if( *(long *)a > *myarray)
{
return 1;
}
else
{
return -1;
}
}
int loadDBmem()
{
connect to database;
load product id and quantity into array of structures;
disconnect from database;
}
Thanks