Sort method is not ordering correctly

Asked

Viewed 102 times

4

I have the following code:

#include <bits/stdc++.h>

using namespace std;

int main()
{
int n, cases = 1, a[3];
cin >> n;
while(cases != n + 1)
{
    cin >> a[0] >> a[1] >> a[2];

    sort(a, a + 2);

    cout << "Sorted array: " << a[0] << " " << a[1] << " " << a[2] << endl;

    cout << "Case " << cases << ": " << a[1] << endl;

    cases++;
}
return 0;
}

For cases with the entries: 30 25 15, the array is: 25 30 15.

That would be a bug, or I was the one who implemented it wrong?

2 answers

5


There are several errors. This code is basically C and not C++. Use bits/stdc++.h is not recommended, is a waste of resource.

The logic is very strange. It is not sending the beginning and end of the array correctly, is not catching the last element. I just corrected this error which is what makes the biggest difference.

#include <iostream>
#include <bits/stdc++.h>
using namespace std;

int main() {
    int n, cases = 1, a[3];
    cin >> n;
    while (cases != n + 1) {
        cin >> a[0] >> a[1] >> a[2];
        sort(a, a + 3);
        cout << "Sorted array: " << a[0] << " " << a[1] << " " << a[2] << endl;
        cout << "Case " << cases << ": " << a[1] << endl;
        cases++;
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • I understood, I used + 2, because I thought it worked like this: a + 0 -> first position a + 1 -> second position a + 2 -> third position (for programming marathons), do you have any tips for me to improve my codes? Thank you!

  • Then you have to ask specific questions.

1

Really you are not asking to sort the last parameter.

Your array has size 3 and when calling Sort, you need to pass size 3 so that it orders not only the first two positions, but also the last one.

...

sort(a, a + 3);

...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.