Median after K additional integers in C++

C++Server Side ProgrammingProgramming

Problem statement

Given an array of n integers. We are allowed to add k additional integer in the array and then find the median of the resultant array. We can choose any k values to be added

If input array is arr[] = { 5, 6 } and k = 1 then output will be 6 −

One of the possible solutions is to add 7 making the array {5, 6, 7}, whose median is 6


1. Sort the array in increasing order.
2. Since value of k is less than n and n+k is always odd, we can always choose to
   add k elements which are greater than the largest element of array and (n+k)/2th
   element is always a median of the arrays


#include <bits/stdc++.h<
using namespace std;
int getMedian(int *arr, int n, int k){
   sort(arr, arr + n);
   return arr[(n + k) / 2];
int main(){
   int arr[] = {5, 6};
   int k = 1;
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << "Median = " << getMedian(arr, n, k) << endl;
   return 0;


When you compile and execute the above program. It generates the following output −

Median = 6
Published on 10-Feb-2020 10:14:46