Minimum number of elements to add to make median equals x using C++.

C++Server Side ProgrammingProgramming

Problem statement

Given an array “arr” of size n and element x, the task is to find a minimum number of elements to be added in array to make median equals x.

A median in an array with the length of n is an element which occupies position number (n-1)/2 after we sort the elements in the non-decreasing order. For example, in below array median is 20 −

arr1[] = {10, 20, 30, 40}

If arr[] = {1, 2, 3} and x = 4 then we have to add 4 number i.e. {4, 5, 5, 5} in array to make median equal to 4


The algorithm is very simple. We have to add one number x to the array until the median of the array equals to x


#include <iostream>
#include <algorithm>
using namespace std;
int minNumbersToBeAdded(int *arr, int n, int x){
   sort(arr, arr + n);
   int cnt = 0;
   while (arr[(n - 1)/2] != x) {
      arr[n] = x;
      sort(arr, arr + n);
   return cnt;
int main(){
   int arr[20] = {1, 2, 3};
   int x = 4;
   int n = 3;
   cout << "Minimum numbers to be added = " << minNumbersToBeAdded(arr, n, x) << endl;
   return 0;


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

Minimum numbers to be added = 4
Published on 31-Oct-2019 06:45:26