简体   繁体   中英

How to solve median without using vectors in C++?

I wanted to code a program to find the mean and median of a sorted array ( so that I can do my maths homework faster ) without using vectors. I wrote this program in HackerRank:

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

int main() {
    int arr[2500],x;
    double sum, mean;
    cin>>x;

    //solving for mean
    for(int i = 0; i <= x; i++) {
        cin>>arr[i];
    }
    sort(arr, arr + x);
    sum = 0.0;
    for (int i = 0; i <= (x-1); i++)
    {
        sum += arr[i];
    }
    mean = sum/x;
    cout<<fixed<<setprecision(1)<<mean<<endl;


    //solving for median
    if (x%2==0)
    cout<<fixed<<setprecision(1)<<arr[x/2]<<endl;
    else 
    cout<<fixed<<setprecision(1)<<((arr[(x-1)/2] + arr[x/2])/2.0)<<endl;
    
    return 0;
}

The input was:

10
64630 11735 14216 99233 14470 4978 73429 38120 51135 67060

And the expected output was:

43900.6
44627.5

But my output is:

43900.6
51135

I am unable to figure out the issue so please help🙏

if (x%2==0)
    cout<<fixed<<setprecision(1)<<arr[x/2]<<endl;
else 
    cout<<fixed<<setprecision(1)<<((arr[(x-1)/2] + arr[x/2])/2.0)<<endl;

if x is odd then (x-1)/2 and x/2 returns the same value, so (arr[(x-1)/2] + arr[x/2])/2.0 is just equivalent to arr[x/2] . You need to use

(arr[x/2] + arr[(x + 1)/2])/2.0

or

(arr[x/2] + arr[x/2 + 1])/2.0

Two issues:

The odd/even check is reversed. If the number of items is even the middle two numbers are averaged and if it is odd the middle number is the median.

if (x%2==0)

should be if (x%2!=0) or if (x%2) You could also swap the contents of the if and else .

The calculation of the two middle indices is incorrect.

((arr[(x-1)/2] + arr[x/2])/2.0)

should be

((arr[x / 2 - 1] + arr[x / 2]) / 2.0)

With both of those issues corrected the output is the expected

43900.6
44627.5

online example of corrected code

Minor issues:

for(int i = 0; i <= x; i++)

If x == 10 this will attempt to read 11 numbers. It should be i < x .

for (int i = 0; i <= (x-1); i++)

This is correct, but can be simplified to i < x .

Change your if condition. x is the length of the array from 0. So if length of array is 12, x will essentially be 11.

First of all, the input loop should be

for(int i=0;i<x;i++) {
    cin>>arr[i];
}

and the median should be like

if (x%2 == 1)
    cout<<fixed<<setprecision(1)<<arr[x/2]<<endl;
else 
    cout<<fixed<<setprecision(1)<<((arr[(x-1)/2] + arr[x/2])/2.0)<<endl;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM