1

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

jordan neely
  • 39
  • 1
  • 6
  • Shortcut: [std::string::compare](https://en.cppreference.com/w/cpp/string/basic_string/compare). – user4581301 Feb 07 '19 at 01:42
  • *and dont tell me to use sort()* -- The standard tells you this is undefined behavior. [See this](https://en.cppreference.com/w/cpp/algorithm/qsort), and pay attention to this passage: *The type of the elements of the array must be a TrivialType, otherwise the behavior is undefined.* -- Tell your teacher to have a look and ponder what they're teaching you. If you're calling `qsort` on an array of `std::string`, then your code is broken, regardless if you accepted the answers given. – PaulMcKenzie Feb 07 '19 at 02:02
  • An array of non-trivial types is also no good. So if `Node` is a non-trivial type, then `qsort` can't be used, regardless of the restrictions made to you by the teacher. No C++ program should be using `qsort`, unless there is something inherently "better" in using `qsort` (with the caveat that it only works for non-trivial types). – PaulMcKenzie Feb 07 '19 at 02:12

1 Answers1

1

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);
Kunal Puri
  • 3,419
  • 1
  • 10
  • 22