Find the Median

The median of a list of numbers is essentially its middle element after sorting. The same number of elements occur after it as before. Given a list of numbers with an odd number of elements, find the median?

Example:

Input:  n=7, arr[]={0,1,2,4,6,5,3}
Output: 3

Approach

Java


import java.util.Arrays;

public class FindMedian {
    public static void main(String[] args) {

        int[] arr = { 0124653 };
        int result = findMedian(arr);
        System.out.println(result);
    }

    static int findMedian(int[] arr) {
        Arrays.sort(arr);
        int n = arr.length;
        return arr[n / 2];
    }
}

C++

#include <bits/stdc++.h>
using namespace std;

int findMedian(vector<intarr)
{
    sort(arr.begin(), arr.end());
    int n = arr.size();
    return arr[n / 2];
}

int main()
{
    int n = 7;

    vector<intarr = {0124653};
    int result = findMedian(arr);

    cout << result << "\n";

    return 0;
}


No comments:

Post a Comment