Sort method is not sorting correctly

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 entries: 30 25 15, the array is: 25 30 15.

Would this be a bug, or was it implemented wrongly?

    
asked by anonymous 08.07.2016 / 08:31

2 answers

4

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

The logic is pretty weird. You are not sending the beginning and end of the array correctly, you are not picking up the last element. I only fix 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++;
    }
    return 0;
}

See running on ideone and on CodingGround .

    
08.07.2016 / 13:53
1

You really are not asking to sort the last parameter.

Your array is size 3 and when you call sort, you need to pass size 3 so that it sorts not only the first two positions, but also the last one.

...

sort(a, a + 3);

...
    
08.07.2016 / 13:51