Reputation: 39
Whenever I am comparing string in qsort, the order is completely wrong. For example, the input is
45 4 9 22 2
but my output is
22 45 4 9 2
here is my comparing function
int cmpString(const void *a, const void *b) {
const Node *a1 = *(const Node **)a;
const Node *b1 = *(const Node **)b;
return a1->s.c_str() - b1->s.c_str();
}
and dont tell me to use sort(), I can't for this assignment
Upvotes: 1
Views: 76
Reputation: 3427
This line is your code's major problem.
return a1->s.c_str() - b1->s.c_str();
The reason behind this is that you are subtracting two pointers here which is not what comparator is supposed to do in this case. Comparator does the comparison on the basis of content.
Instead, try this:
int length1 = a1->s.size();
int length2 = b1->s.size();
for (int i = 0; i < min(length1, length2); i++) {
if (a1->s[i] != b1->s[i]) { // if characters are not same, return difference of their ASCII values.
return a1->s[i] - b1->s[i];
}
}
return length1 - length2; // if they are same till now, then shorter string should appear first. That's why it is required.
Suggestion:
If you are coding in C++, then please use STL. There is a nice function sort()
given by <algorithm>
which allows you to do the same thing without using void *
Update:
As rightly suggested by user4581301, you may use std::string::compare directly.
Like this:
return (a1->s).compare(b1->s);
Upvotes: 1