Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,907 questions

51,839 answers

573 users

How to find the median of an int vector in C++

1 Answer

0 votes
#include <iostream>
#include <algorithm>
#include <vector>

double find_median_of_int_array(std::vector<int>& vec) {
    std::sort(vec.begin(), vec.end());

    for (int num : vec) {
        std::cout << num << " ";
    }

    double median;
    int size = vec.size();

    if (size % 2 == 0) {
        median = (vec[size / 2 - 1] + vec[size / 2]) / 2.0;
    }
    else {
        median = vec[size / 2];
    }

    return median;
}

int main()
{
    std::vector<int> vec = { 40, 70, 60, 55, 90, 45, 100, 80, 65, 50, 82, 58 };
    
    /*  std::vector<int> vec = {24, 25, 26, 27, 28, 30, 32, 51, 34, 35, 36, 40, 60, 42, 49};
        24 25 26 27 28 30 32 34 35 36 40 42 49 51 60
        median = 34.00
    */

    double median = find_median_of_int_array(vec);

    std::cout << "\nmedian = " << median << std::endl;
}


  
/*
run:
  
40 45 50 55 58 60 65 70 80 82 90 100 
median = 62.5     
  
*/


 



answered Jul 17, 2024 by avibootz
...