Searching an element of array type struct in c -
i have array of structures store basic informations pc within company (code,model,connected internet).
typedef struct database{ char code[5]; char brand[20]; char model[20]; int lab; int connect; }database;
now want search through array find pc coresponding code c01a
here little example of info stored in struct:
c01a hp sjh1740 1 0 b02a hp sj1290 3 1 a03b dell pq240 2 1 a02b dell pq240 3 1 c09h fujitsu np0001 1 0 a06d dell pq240 3 1 c00x fujitsu lp1050 2 0 b89a hp sj1290 3 1 a03f dell pt1000 2 0 c12p hp aa0012 1 1 d01d dell bb2300h 3 0
you can see first pc has code c01a
. here see 11 pc's randomly picked file in there can millions of pc's (imagine big company, array able hold 10 million pc's because can).
i search every single element in array until find right one. (using quick calculation dunno if it's ok). means have scroll trough 10.5mb of memory, quite lot if searching process not optimalized.
so came this:
step 1: sort array when program started.
step 2: start @ middle of array , check element
step 3: if element want search smaller element checked, check middle of first half, else check middle of second half
step 4: repeat until element found or until same element checked twice, in case element not exist.
here fast code tried:
database searchpc(database temp[],int n){ int i=n/2; char code [5]; printf("incerici codice da cercare: "); scanf("%s",code); getchar(); while(strcmp(temp[i].code,code)!=0){ if(strcmp(temp[i].code,code)>0) i=i/2; else i=i*2; } return temp[i]; }
this returns element if found, else gets stuck in loop (this work in process)
i tested on info above , searched, in example, c01a
pc. got stuck well.
what doing wrong? can done faster when realy have go trough lot of pc's?
if i
0 , try halve it, or if i * 2
larger n
, structure couldn't found.
Comments
Post a Comment