Click to See Complete Forum and Search --> : qsort question, urgent!


tobias_
March 17th, 2002, 04:58 PM
Can someone help me with qsort problem, I would like to use the inbuilt qsort function? I have a struct like this:

typedef struct{
int hours;
int minutes;
int seconds;
}Times;

I have calculated the times in a global struct table
Times TotalTimes[10];

How do I sort them by checking first hours, then minutes and finally seconds?
All values are given as two-digit decimal numbers.

Please help me out, I tried several different cases but I can't sort all numbers (hours, mins, secs) correctly.

I think the syntax of qsort is something like:
qsort(inputArray,numberOfCharsToCompare
,charTableLength,strcmp);

Paul McKenzie
March 17th, 2002, 08:55 PM
First, I suggest using a little ingenuity. To sort the numbers, combine them into a single number and compare.

Second, since I code in C++, I never use qsort. Since this is C++ (and I'm assuming you are programming in C++), you should use what C++ provides -- and that is the std::sort function.

Here is an example of how you would sort the numbers. Please study this -- you may never get a chance to learn this in any class you take in school (unfortunately):

#include <algorithm>
#include <iostream>
using namespace std;
//...
struct Times
{
int hours;
int minutes;
int seconds;
};
//...
unsigned long GetSingleValue(const Times& TValue) {
return (long)TValue.hours * 10000L +
(long)TValue.minutes * 100L +
(long)TValue.seconds;
}
//...
bool lessTime(const Times& T1, const Times& T2)
{
return GetSingleValue(T1) < GetSingleValue(T2);
}
//...
int main()
{
Times TotalTimes[10];
//...
std::sort(TotalTimes, TotalTimes + 10,
lessTime);
}



I defined a function that combines the components (hours, minutes, seconds) into a single number. This number will then be used to compare whether one time is less than another. The other thing I did was to define a function that returned true or false, depending on whether one time is less than another time. In main(), I called the standard C++ std::sort() function. This function takes a beginning and end range arguments, and a pointer to a function used to compare two elements.

This is the way that a C++ should use sort. qsort should only be used for 'C' programs in this day and age. Even if you do decide to use qsort, you should still combine the components into one, and sort the single component.

Regards,

Paul McKenzie

Andrew Koudr
May 14th, 2002, 08:18 AM
Hi, you should use not strcmp in qsort, but your own routine that will compare your structure.


Sincerely, Andrew Koudryavtsev