samedi 25 avril 2015

C++: Why is my vector not returning the median? [duplicate]


This question already has an answer here:

I need to take the median of a sorted vector for a homework assignment. I have tried a few different ways but I'm not sure how to properly tell the program to take the median. I have tried things like taking the size and dividing it by 2 then rounding up and attempting to return data[i] at this position, but with no success. This is where I'm at (does not compile). Any help will be well appreciated.

#include <iostream>
#include <stdlib.h>
#include <vector>
#include <cmath>

using namespace std;

void bubbleSort(vector<int>& data)
{
    if(data.size() <= 1)
        return;

    for(int i=1; i<data.size(); i++)
    {
        for(int j=0; j<data.size()-i; j++)
        {
            if(data.at(j) > data.at(j+1))
            {
                int temp = data.at(j+1);
                data.at(j+1) = data.at(j);
                data.at(j) = temp;
            }
        }
    }
}

int main()
{
    int n;
    vector<int> data;

    cout << "Vector Length?: ";
    cin >> n;

    // Filling vector
    for(int i=0; i<n; i++)
        data.push_back(rand()%10+1);

    cout << "Vector: ";
    for(int i=0; i<data.size(); i++)
        cout << data.at(i) << ", ";

    // Sorting
    bubbleSort(data);

    cout << endl << "Sorted Vector: ";
    for(int i=0; i<data.size(); i++)
        cout << data.at(i) << ", ";




    //Average & Median
    //average = accumulate(data.begin(), data.end(), 0.0)/data.size();
    double median = 0.0;
    if (data.size() % 2)
    {
        cout<<endl;
        cout<<"Vector is odd"<<endl;
        median = data.end(i/2);
        cout<<"Median: "<<median<<endl;



    }
    else{
        cout<<"Vector is even"<<endl;
        median = ((data.size()/2.0-1.0) + (data.size()/2.0+1.0)/2.0);
        cout<<"Median: "<<median<<endl;


    }




    system ("pause");

    return 0;





}


Aucun commentaire:

Enregistrer un commentaire