Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

help in using binary search

Status
Not open for further replies.

huskers

Programmer
Jan 29, 2002
75
US
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
 
hi,

I belive your comp function would play as:

int comp(const void *a, const void *b)
{
struct myrecords *p1, *p2;

p1 = (*myrecords) a ;
p2 = (*myrecords) b ;

return( p1->quantity - p2->quantity )

}

P.S.: it seems to me that memdb has to be sorted before.
(use qsort)


bye
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top