Speeding up qsort usage.

Apr 4, 2012 at 1:10am
I'm currently using qsort to sort an array of Cable objects.

1
2
3
4
5
6
int comparator (const void *elem1, const void *elem2 )
{
	if((*(Cable**)elem1)->cost < (*(Cable**)elem2)->cost) return -1;
	else if((*(Cable**)elem1)->cost > (*(Cable**)elem2)->cost) return 1;
	else return 0;
}


qsort(cables,ncables, sizeof(Cable*), comparator);
The current sort takes approximately .2 seconds. I'm trying to make it so i can sort it in under .1 seconds.

cables is of type **Cable, ncables is the number of elements in cables.

Thanks for any help you can offer!
Apr 4, 2012 at 1:57am
If you're using C++, your first step should be switching to std::sort(), which is usually faster (although probably not by a factor of two).
Second step, use a profiler.
Last edited on Apr 4, 2012 at 1:58am
Apr 4, 2012 at 1:58am
I would, but i'm required to use qsort for the program i'm writing. I need to sort 499500 cables by cost(an element of the class) in less than .1 secs.
Apr 4, 2012 at 10:05am
Did you turn on optimizations? Never measure performance with optimizations turned off.

If cost is an int (or smaller) you can rewrite the function as
1
2
3
4
int comparator (const void *elem1, const void *elem2 )
{
	return (*(Cable**)elem1)->cost - (*(Cable**)elem2)->cost;
}
Topic archived. No new replies allowed.