# Median after K additional integers in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

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,

Input

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

Output

67

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.

## Example

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;
}

## Output

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