// Documentation Begins
void qsort ( void * base, int num, int size, int ( * comparator ) ( const void *, const void * ) );
base
Pointer to the first element of the array to be sorted.
num
Number of elements in the array pointed at by base.
size
Size in bytes of each element in the array.
comparator
Function that compares two elements. The function shall follow this prototype:
int comparator ( const void * elem1, const void * elem2 );
The function must accept two parameters that are pointers to elements, type-casted as void*. These parameters should be cast back to some data type and be compared.
The return value of this function should represent whether elem1 is considered less than, equal, or greater than elem2 by returning, respectively, a negative value, zero or a positive value.
// End of qsort documentation
Lets say I have an array of Strings defined, how would I use qsort to alphabetically sorth them.
I need help with qsort in C++?
/************************************
Name: qsort.c
Sorry -- it's in C, but it's a short
walk to C++
For strings, change Ascend() and Descend() to handle strings...
int Ascend(const void *p1, const void *p2)
{
char *s1 = (char *)p1;
char *s2 = (char *)p2;
return strcmp(s1,s2);
}
*************************************/
#include %26lt;stdlib.h%26gt;
#include %26lt;stdio.h%26gt;
int num[]={1,3,5,4,2,9,0,8,6,7};
int Ascend(const void *p1, const void *p2)
{
int i=*(int *)p1;
int j=*(int *)p2;
return i-j;
}
int Descend(const void *p1, const void *p2)
{
int i= *(int *)p1;
int j= *(int *)p2;
return j-i;
}
int main()
{
int i;
printf("\nOrig array: ");
for (i=0; i%26lt;10; i++)
printf("%d ", num[i]);
qsort(num, 10, sizeof(int), Ascend);
printf("\nSorted array[Ascending]: ");
for (i=0; i%26lt;10; i++)
printf("%d ", num[i]);
qsort(num, 10, sizeof(int),Descend);
printf("\nSorted array[Descending]: ");
for (i=0; i%26lt;10; i++)
printf("%d ", num[i]);
}
bottle palm
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment