Hello! I have a problem: that sorting would work correctly, I have to artificially increase the size of the array! And when changing the sorting to the opposite, everything stops working again.

The code itself:

#include <iostream> using namespace std; int n; int a[1001]; int cmp(const void *x1, const void *x2); int main(int argc, char *argv[]) { cin >> n; for(int i = 0; i < n; i++) cin >> a[i], cout << i << endl; qsort(a, n + 1, sizeof(int), cmp); for(int i = 1; i <= n; i++) cout << a[i] << " "; cout << endl; return 0; } int cmp(const void *x1, const void *x2) { return (*(int*)x1 - *(int*)x2); } 

What is this line

 qsort(a, n + 1, sizeof(int), cmp); 

Better than this?

 qsort(a, n, sizeof(int), cmp); 

This is a bit strange for me, because I scored an array as it should, from scratch, cmp (auxiliary function) wrote correctly. Such crutches are a little scary, because in some cases they probably spoil everything.

  • one
    And nothing, that you output an array starting from the second element in n+1 ? - PinkTux
  • Oh, get it wrong. Oh, oh. This was for qSort output which I wrote manually. Earned by the way. In any case, even after the normal output of the array, the first output element equals zero - witaway
  • And what should be equal? Give an example of the input data and what happens at the output. - PinkTux
  • Input: "5 5 4 3 2 1" Conclusion: "1 2 3 4 5" It turned out: "0 2 3 4 5" - witaway
  • The output does not repeat (after changing the index of the initial element and the number of elements to be sorted): coliru.stacked-crooked.com/a/ebc5ff9e9d55ae81 - awesoon

1 answer 1

Both of these lines are bad, because qsort is a legacy of C. When you write in C ++, you should use std::sort :

 #include <iostream> #include <algorithm> using namespace std; int n; int a[1001]; int main(int argc, char *argv[]) { cin >> n; for(int i = 0; i < n; i++) cin >> a[i], cout << i << endl; sort(a, a + n); for(int i = 0; i < n; i++) cout << a[i] << " "; cout << endl; return 0; } 

Run code online

But in fact, the problem is not in sorting, but in the output of elements:

 for(int i = 1; i <= n; i++) // ^^^^^ 

You enter elements starting from zero, and output from the first.