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 Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

a better qsort

Status
Not open for further replies.

Setzer

Programmer
Joined
Jan 5, 2002
Messages
9
Location
RO


I need a function like qsort() wich doesnt need the size of the elements to be sorted( because they vary). If you ever heard of such a function or if u have some algoritm for it post an answer, pls.
 
That is the wonderful thing about iteration and while loops. I am assuming the elements are stored as a double or int type. In that case, create a while loop with a counter adding from zero every time an element is encountered. After you've reached the end of your array, the while loop will exit with the appropriate number of elements. Just send that value down to qsort as it is, but subtract one from the counter, since you start at element 0.
 
Hi,
The wonderful thing about SORTING is you don't really have to sort the elements. You really only need to sort the indexes.

The reason QSORT needs to know the size of the elements is because it 'SWAPS' the elements in the array.

However, there is no reason you need to pass in the real elements. You could pass in an array of indexes or pointers to the elements and sort the indexes.

something like

cmp(void *a, void *b )
{
elem *ma = (elem *)a;
elem *mb = (elem *)b;

return ( ma->data - mb->data )
}

then you create an array of pointers to your elements
I assume you aren't using an array for your list since they are different sizes, a linked list was the next assumption.

curr = head;
x = 0;
while ( curr != NULL )
{
ray[x] = curr;
curr = curr->next;
x ++;
}

qsort(ray,x,sizeof(elem *),cmp);

Then when you come back you don't access them through the linked list anymore but through the array.

for ( y = 0 ; y < x ; y ++ )
{
printf(&quot;%d\n&quot;,ray[x]->elem );
}


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top