Median after K additional integers in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array of n integers and we are adding K elements to the array and then find the median of the resultant array. Given the condition, N+k is odd.

Let’s take an example to understand the problem,


array = {23, 65, 76, 67} ; k =1



To solve this problem, we will sort the given elements in ascending order and then add k elements at the end of the array i.e. we will take k greater elements.

The condition is given that n+k is odd. So, the median can be calculated using the formula, (n+k)/2.


Program to find the median,

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int findMedianAfterK(int arr[], int n, int K) {
   sort(arr, arr + n);
   return arr[((n + K)/2)];
int main() {
   int array[] = {3,56, 8, 12, 67, 10 };
   int k = 3;
   int n = sizeof(array) / sizeof(array[0]);
   cout<<"The median after adding "<<k<<" elements is "<<findMedianAfterK(array, n, k);
   return 0;


The median after adding 3 elements is 56
Updated on 03-Jun-2020 07:24:50