Tuesday, July 28, 2009

How to use qsort function in stdlib.h ?

/*In the file stdlib.h, I find this procedure*/





_CRTIMP void __cdecl qsort(void *, size_t, size_t, int (__cdecl *)


(const void *, const void *));





/*which is why I think that this is actually a command to quick sort some kind of struct.


If there is a struct defined like below*/





struct DataBase


{ int Value;


char Name[20],Address[20];


float A,B,C;


} *VData;





void main(void)


{ int NumOfData;


NumOfData=TakeDataFromFile


(VData,"DataFile.txt");





????





WriteSortedData


(NumOfData,VData,"SortedData.txt");


}





/*Please write on the ???? how to sort the struct using the qsort procedure in the stdlib.h


Please also tell me if I have to make some kind of procedure outside the void main(void) */

How to use qsort function in stdlib.h ?
The qsort() is a generic function to sort any array. Let's assume that in the given structure you would like to sort on Name. Just incase two people have the same name you would like to sort on Value.





You need to write a custom compare function that would implement the above logic.





// Function to compare two DataBase elements.


int DataBaseCmp(const void *elem1, const void *elem2) {


// Typecast elements back to DataBase* type from void*


Database *dbelem1 = (const Database *)elem1;


Database *dbelem2 = (const Database *)elem2;


int diff;


// Compare names


diff = strcmp(dbelem1-%26gt;Name, dbelem2-%26gt;Name);


// If names are same, compare values


if( diff == 0 ) {


return dbelem1-%26gt;Value - dbelem2-%26gt;Value;


}


else {


return diff;


}


}





== qsort signature ==


void qsort(


void *base,


size_t num,


size_t width,


int (__cdecl *compare )(const void *, const void *)


);


=================


qsort(VData, NumOfData, sizeof(Database), DataBaseCmp);
Reply:http://www.cppreference.com/stdother/qso...





Generally,searching on Google proves to be very useful.
Reply:If we have DataBase itemA and itemB, under what condition itemA is less than itemB? Sort by value, by name or by address? You should define this first.


No comments:

Post a Comment