Median of Array

Last Updated : 4 Nov, 2026

Given an array arr[] of integers, calculate the median.

Examples: 

Input: arr[] = [90, 100, 78, 89, 67]
Output: 89
Explanation: After sorting the array middle element is the median

Input: arr[] = [56, 67, 30, 79]
Output: 61.5
Explanation: In case of even number of elements, average of two middle elements is the median.

Input: arr[] = [1, 2]
Output: 1.5
Explanation: The average of both elements will result in 1.5.

Try It Yourself
redirect icon

Sorting the Array - O(n log) Time and O(1) Space

The idea is to sort the array.

After sorting,

  • For an odd-sized array, return the middle element.
  • For an even-sized array, return the average of the two middle elements.
C++
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;

double findMedian(vector<int> &arr)
{
    int n = arr.size();

    // First we sort the array
    sort(arr.begin(), arr.end());

    // check for even case
    if (n % 2 != 0)
        return arr[n / 2];

    return (arr[(n - 1) / 2] + arr[n / 2]) / 2.0;
}

int main()
{
    vector<int> arr = {1, 3, 4, 2, 7, 5, 8, 6};
    double ans = findMedian(arr);
    cout << ans << endl;
    return 0;
}
Java
import java.util.Arrays;

class GFG {
    static double findMedian(int[] arr)
    {
        int n = arr.length;

        // First we sort the array
        Arrays.sort(arr);

        // check for even case
        if (n % 2 != 0)
            return arr[n / 2];

        return (arr[(n - 1) / 2] + arr[n / 2]) / 2.0;
    }

    public static void main(String[] args)
    {
        int[] arr = { 1, 3, 4, 2, 7, 5, 8, 6 };
        double ans = findMedian(arr);
        System.out.println(ans);
    }
}
Python
def findMedian(arr):
    n = len(arr)
    
    # First we sort the array
    arr.sort()

    # check for even case
    if n % 2 != 0:
        return arr[n // 2]

    return (arr[(n - 1) // 2] + arr[n // 2]) / 2.0

if __name__ == "__main__":
  arr = [1, 3, 4, 2, 7, 5, 8, 6]
  ans = findMedian(arr)
  print(ans)
C#
using System;
using System.Linq;

class GFG {
    static double findMedian(int[] arr)
    {
        int n = arr.Length;
        // First we sort the array
        Array.Sort(arr);

        // check for even case
        if (n % 2 != 0)
            return arr[n / 2];

        return (arr[(n - 1) / 2] + arr[n / 2]) / 2.0;
    }

    static void Main()
    {
        int[] arr = { 1, 3, 4, 2, 7, 5, 8, 6 };
        double ans = findMedian(arr);
        Console.WriteLine(ans);
    }
}
JavaScript
function findMedian(arr)
{
    let n = arr.length;

    // First we sort the array
    arr.sort((a, b) => a - b);

    // check for even case
    if (n % 2 !== 0)
        return arr[Math.floor(n / 2)];

    return (arr[Math.floor(n / 2) - 1]
            + arr[Math.floor(n / 2)])
           / 2.0;
}

// Driver Code
let arr = [ 1, 3, 4, 2, 7, 5, 8, 6 ];
let ans = findMedian(arr);
console.log(ans);

Output
4.5

Randomized QuickSelect - O(n) Time and O(log n) Space 

The main idea is to find the middle element(s) directly without sorting the complete array.

First, identify the index or indices containing the median elements, then use Randomized QuickSelect to find them.

For an array of size n:

  • If n is odd, the median is at index n / 2.
  • If n is even, the two middle elements are at indices n / 2 - 1 and n / 2.

Randomized QuickSelect randomly chooses a pivot and partitions the array around it. Smaller elements are placed on the left and larger elements on the right, placing the pivot at its correct position in the sorted array.

  • If the pivot is at the required index, its value is found.
  • If the required index is smaller than the pivot position, continue searching in the left part.
  • If the required index is greater than the pivot position, continue searching in the right part.

Only the part containing the required index is processed further, so the complete array does not need to be sorted.

Let us understand with an example:
Input: arr[] = [12, 3, 6, 7, 4, 19].

  • Since n = 6, the median elements are at indices n/2 - 1 = 2 and n/2 = 3.
  • Choose 7 as the pivot. After partitioning, the array becomes [3, 6, 4, 7, 12, 19]. The pivot 7 is at index 3, so one median element is found.
  • Index 2 lies on the left of the pivot, so QuickSelect continues with [3, 6, 4].
  • Choose 4 as the pivot. After partitioning, it becomes [3, 4, 6]. The pivot is at index 1, so index 2 is searched in the right part.
  • The element at index 2 is 6.
  • The two middle elements are 6 and 7.

Median = (6 + 7) / 2 = 6.5.

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

// Function to partition the array around the pivot
int partition(vector<int> &arr, int l, int r)
{
    // Select the last element as pivot
    int lst = arr[r], i = l, j = l;

    while (j < r)
    {
        // Move elements smaller than pivot to the left
        if (arr[j] < lst)
        {
            swap(arr[i], arr[j]);
            i++;
        }
        j++;
    }

    // Place pivot at its correct position
    swap(arr[i], arr[r]);
    return i;
}

// Function to randomly select a pivot and partition the array
int randomPartition(vector<int> &arr, int l, int r)
{
    // Generate a random index within the current range
    int n = r - l + 1;
    int pivot = rand() % n;

    // Move the randomly selected pivot to the last position
    swap(arr[l + pivot], arr[r]);

    return partition(arr, l, r);
}

// Recursive function to find the middle element(s) using Quickselect
void medianUtil(vector<int> &arr, int l, int r, int k, int &a, int &b)
{
    if (l <= r)
    {
        // Partition the array using a random pivot
        int partitionIndex = randomPartition(arr, l, r);

        // If pivot reaches the middle index, store it
        if (partitionIndex == k)
        {
            b = arr[partitionIndex];
            if (a != -1)
                return;
        }

        // Store the element just before the middle index
        else if (partitionIndex == k - 1)
        {
            a = arr[partitionIndex];
            if (b != -1)
                return;
        }

        // If pivot is at or after k, search in the left part
        if (partitionIndex >= k)
            return medianUtil(arr, l, partitionIndex - 1, k, a, b);

        // Otherwise, search in the right part
        else
            return medianUtil(arr, partitionIndex + 1, r, k, a, b);
    }
    return;
}

// Function to find the median using Randomized Quickselect
double findMedian(vector<int> &arr)
{
    double ans;
    int a = -1, b = -1, n = arr.size();

    // For an odd-sized array, find the middle element
    if (n % 2 == 1)
    {
        medianUtil(arr, 0, n - 1, n / 2, a, b);
        ans = b;
    }
    // For an even-sized array, find both middle elements
    else
    {
        medianUtil(arr, 0, n - 1, n / 2, a, b);
        ans = (a + b) / 2.0;
    }

    return ans;
}

int main()
{
    vector<int> arr = {12, 3, 6, 7, 4, 19};

    // Find and print the median
    cout << findMedian(arr);

    return 0;
}
Java
import java.util.*;

class GFG {

    // Function to partition the array around the pivot
    static int partition(int[] arr, int l, int r)
    {

        // Select the last element as pivot
        int lst = arr[r], i = l, j = l;

        while (j < r) {

            // Move elements smaller than pivot to the left
            if (arr[j] < lst) {
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
                i++;
            }
            j++;
        }

        // Place pivot at its correct position
        int temp = arr[i];
        arr[i] = arr[r];
        arr[r] = temp;

        return i;
    }

    // Function to randomly select a pivot and partition the
    // array
    static int randomPartition(int[] arr, int l, int r)
    {

        // Generate a random index within the current range
        int n = r - l + 1;
        int pivot = new Random().nextInt(n);

        // Move the randomly selected pivot to the last
        // position
        int temp = arr[l + pivot];
        arr[l + pivot] = arr[r];
        arr[r] = temp;

        return partition(arr, l, r);
    }

    // Recursive function to find the middle element(s)
    // using Quickselect
    static void medianUtil(int[] arr, int l, int r, int k,
                           int[] result)
    {

        if (l <= r) {

            // Partition the array using a random pivot
            int partitionIndex = randomPartition(arr, l, r);

            // If pivot reaches the middle index, store it
            if (partitionIndex == k) {
                result[1] = arr[partitionIndex];

                if (result[0] != -1)
                    return;
            }

            // Store the element just before the middle
            // index
            else if (partitionIndex == k - 1) {
                result[0] = arr[partitionIndex];

                if (result[1] != -1)
                    return;
            }

            // If pivot is at or after k, search in the left
            // part
            if (partitionIndex >= k) {
                medianUtil(arr, l, partitionIndex - 1, k,
                           result);
            }

            // Otherwise, search in the right part
            else {
                medianUtil(arr, partitionIndex + 1, r, k,
                           result);
            }
        }
    }

    // Function to find the median using Randomized
    // Quickselect
    static double findMedian(int[] arr)
    {

        int n = arr.length;
        int[] result = { -1, -1 };

        // For an odd-sized array, find the middle element
        if (n % 2 == 1) {
            medianUtil(arr, 0, n - 1, n / 2, result);
            return result[1];
        }

        // For an even-sized array, find both middle
        // elements
        medianUtil(arr, 0, n - 1, n / 2, result);

        return (result[0] + result[1]) / 2.0;
    }

    public static void main(String[] args)
    {

        int[] arr = { 12, 3, 6, 7, 4, 19 };
        System.out.println(findMedian(arr));
    }
}
Python
import random

import random

# Function to partition the array around the pivot
def partition(arr, l, r):

    # Select the last element as pivot
    lst = arr[r]
    i = l
    j = l

    while j < r:

        # Move elements smaller than pivot to the left
        if arr[j] < lst:
            arr[i], arr[j] = arr[j], arr[i]
            i += 1

        j += 1

    # Place pivot at its correct position
    arr[i], arr[r] = arr[r], arr[i]

    return i


# Function to randomly select a pivot and partition the array
def randomPartition(arr, l, r):

    # Generate a random index within the current range
    n = r - l + 1
    pivot = random.randrange(n)

    # Move the randomly selected pivot to the last position
    arr[l + pivot], arr[r] = arr[r], arr[l + pivot]

    return partition(arr, l, r)


# Recursive function to find the middle element(s) using Quickselect
def medianUtil(arr, l, r, k, result):

    if l <= r:

        # Partition the array using a random pivot
        partitionIndex = randomPartition(arr, l, r)

        # If pivot reaches the middle index, store it
        if partitionIndex == k:
            result[1] = arr[partitionIndex]

            if result[0] != -1:
                return

        # Store the element just before the middle index
        elif partitionIndex == k - 1:
            result[0] = arr[partitionIndex]

            if result[1] != -1:
                return

        # If pivot is at or after k, search in the left part
        if partitionIndex >= k:
            medianUtil(arr, l, partitionIndex - 1, k, result)

        # Otherwise, search in the right part
        else:
            medianUtil(arr, partitionIndex + 1, r, k, result)


# Function to find the median using Randomized Quickselect
def findMedian(arr):

    n = len(arr)
    result = [-1, -1]

    # For an odd-sized array, find the middle element
    if n % 2 == 1:
        medianUtil(arr, 0, n - 1, n // 2, result)
        return result[1]

    # For an even-sized array, find both middle elements
    medianUtil(arr, 0, n - 1, n // 2, result)

    return (result[0] + result[1]) / 2.0

if __name__ == '__main__':
    arr = [12, 3, 6, 7, 4, 19]

    # Find and print the median
    print(findMedian(arr))
C#
using System;

class GFG {

    // Function to partition the array around the pivot
    static int partition(int[] arr, int l, int r) {

        // Select the last element as pivot
        int lst = arr[r], i = l, j = l;

        while (j < r) {

            // Move elements smaller than pivot to the left
            if (arr[j] < lst) {
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
                i++;
            }
            j++;
        }

        // Place pivot at its correct position
        int t = arr[i];
        arr[i] = arr[r];
        arr[r] = t;

        return i;
    }

    // Function to randomly select a pivot and partition the array
    static int randomPartition(int[] arr, int l, int r) {

        // Generate a random index within the current range
        int n = r - l + 1;
        int pivot = new Random().Next(n);

        // Move the randomly selected pivot to the last position
        int temp = arr[l + pivot];
        arr[l + pivot] = arr[r];
        arr[r] = temp;

        return partition(arr, l, r);
    }

    // Recursive function to find the middle element(s) using Quickselect
    static void medianUtil(int[] arr, int l, int r, int k,
                           int[] result) {

        if (l <= r) {

            // Partition the array using a random pivot
            int partitionIndex = randomPartition(arr, l, r);

            // If pivot reaches the middle index, store it
            if (partitionIndex == k) {
                result[1] = arr[partitionIndex];

                if (result[0] != -1)
                    return;
            }

            // Store the element just before the middle index
            else if (partitionIndex == k - 1) {
                result[0] = arr[partitionIndex];

                if (result[1] != -1)
                    return;
            }

            // If pivot is at or after k, search in the left part
            if (partitionIndex >= k) {
                medianUtil(arr, l, partitionIndex - 1, k, result);
            }

            // Otherwise, search in the right part
            else {
                medianUtil(arr, partitionIndex + 1, r, k, result);
            }
        }
    }

    // Function to find the median using Randomized Quickselect
    static double findMedian(int[] arr) {

        int n = arr.Length;
        int[] result = { -1, -1 };

        // For an odd-sized array, find the middle element
        if (n % 2 == 1) {
            medianUtil(arr, 0, n - 1, n / 2, result);
            return result[1];
        }

        // For an even-sized array, find both middle elements
        medianUtil(arr, 0, n - 1, n / 2, result);

        return (result[0] + result[1]) / 2.0;
    }

    static void Main() {

        int[] arr = { 12, 3, 6, 7, 4, 19 };
        Console.WriteLine(findMedian(arr));
    }
}
JavaScript
// Function to partition the array around the pivot
function partition(arr, l, r)
{

    // Select the last element as pivot
    let lst = arr[r];
    let i = l, j = l;

    while (j < r) {

        // Move elements smaller than pivot to the left
        if (arr[j] < lst) {
            [arr[i], arr[j]] = [ arr[j], arr[i] ];
            i++;
        }

        j++;
    }

    // Place pivot at its correct position
    [arr[i], arr[r]] = [ arr[r], arr[i] ];

    return i;
}

// Function to randomly select a pivot and partition the
// array
function randomPartition(arr, l, r)
{

    // Generate a random index within the current range
    let n = r - l + 1;
    let pivot = Math.floor(Math.random() * n);

    // Move the randomly selected pivot to the last position
    [arr[l + pivot], arr[r]] = [ arr[r], arr[l + pivot] ];

    return partition(arr, l, r);
}

// Recursive function to find the middle element(s) using
// Quickselect
function medianUtil(arr, l, r, k, result)
{

    if (l <= r) {

        // Partition the array using a random pivot
        let partitionIndex = randomPartition(arr, l, r);

        // If pivot reaches the middle index, store it
        if (partitionIndex === k) {
            result[1] = arr[partitionIndex];

            if (result[0] !== -1)
                return;
        }

        // Store the element just before the middle index
        else if (partitionIndex === k - 1) {
            result[0] = arr[partitionIndex];

            if (result[1] !== -1)
                return;
        }

        // If pivot is at or after k, search in the left
        // part
        if (partitionIndex >= k) {
            medianUtil(arr, l, partitionIndex - 1, k,
                       result);
        }

        // Otherwise, search in the right part
        else {
            medianUtil(arr, partitionIndex + 1, r, k,
                       result);
        }
    }
}

// Function to find the median using Randomized Quickselect
function findMedian(arr)
{

    let n = arr.length;
    let result = [ -1, -1 ];

    // For an odd-sized array, find the middle element
    if (n % 2 === 1) {
        medianUtil(arr, 0, n - 1, Math.floor(n / 2),
                   result);
        return result[1];
    }

    // For an even-sized array, find both middle elements
    medianUtil(arr, 0, n - 1, n / 2, result);

    return (result[0] + result[1]) / 2.0;
}

// Driver code
let arr = [ 12, 3, 6, 7, 4, 19 ];
console.log(findMedian(arr));

Output
6.5

Median of Medians - O(n) Time and O(1) Space

Unlike the Randomized Quickselect Approach, we use the Median of Medians technique to guarantee O(n) worst-case time complexity.

Note that this approach is theoretically better, but due to high constants, the previous approach works better for practical purposes.

Working of Approach:

  • Divide the array into groups of five elements and sort each group.
  • Find the median of each group and store these medians in a separate list.
  • Recursively find the median of the medians list and use it as the pivot.
  • Partition the array around the pivot and determine its correct position.
  • If the pivot is at the required median index, return it. Otherwise, continue searching in the relevant partition.
C++
#include <bits/stdc++.h>
using namespace std;

// Function to partition the array around the pivot
int partitionAroundPivot(vector<int> &arr, int l, int r, int pivot)
{
    int pivotValue = arr[pivot];
    swap(arr[pivot], arr[r]);

    int i = l;

    // Move elements smaller than pivot to the left
    for (int j = l; j < r; j++)
    {
        if (arr[j] < pivotValue)
        {
            swap(arr[i], arr[j]);
            i++;
        }
    }

    // Place pivot at its correct position
    swap(arr[i], arr[r]);
    return i;
}

// Function to find the median of a small group
int findMedian(vector<int> &arr, int l, int r)
{
    sort(arr.begin() + l, arr.begin() + r + 1);
    return l + (r - l) / 2;
}

// Function to find the median of medians
int medianOfMedians(vector<int> &arr, int l, int r)
{
    int n = r - l + 1;

    // Base case: sort and return the median index
    if (n <= 5)
        return findMedian(arr, l, r);

    vector<int> medians;

    // Divide the array into groups of five
    for (int i = l; i <= r; i += 5)
    {
        int subRight = min(i + 4, r);
        int medianIndex = findMedian(arr, i, subRight);
        medians.push_back(arr[medianIndex]);
    }

    // Find the median of the medians
    int medianIndex = medianOfMedians(medians, 0, medians.size() - 1);

    // Use the median value as pivot
    int pivotValue = medians[medianIndex];

    // Find the pivot value in the original array
    for (int i = l; i <= r; i++)
    {
        if (arr[i] == pivotValue)
            return partitionAroundPivot(arr, l, r, i);
    }

    return l; // Fallback
}

// Function to find the kth smallest element
int kthSmallest(vector<int> &arr, int l, int r, int k)
{
    if (l == r)
        return arr[l];

    // Select a pivot using Median of Medians
    int pivotIndex = medianOfMedians(arr, l, r);

    if (pivotIndex == k)
        return arr[pivotIndex];

    if (pivotIndex > k)
        return kthSmallest(arr, l, pivotIndex - 1, k);

    return kthSmallest(arr, pivotIndex + 1, r, k);
}

// Function to find the median
double findMedian(vector<int> &arr)
{
    int n = arr.size();

    if (n % 2 == 1)
        return kthSmallest(arr, 0, n - 1, n / 2);

    int a = kthSmallest(arr, 0, n - 1, n / 2 - 1);
    int b = kthSmallest(arr, 0, n - 1, n / 2);

    return (a + b) / 2.0;
}

int main()
{
    vector<int> arr = {12, 3, 6, 7, 4, 19};

    cout << findMedian(arr);
    return 0;
}
Java
import java.util.*;

class GFG {

    // Function to partition the array around the pivot
    static int[] partitionAroundPivot(int[] arr, int l,
                                      int r, int pivot)
    {
        int i = l, j = l, gt = r;

        // Place elements smaller than pivot on the left
        // and greater elements on the right
        while (j <= gt) {
            if (arr[j] < pivot) {
                int temp = arr[i];
                arr[i++] = arr[j];
                arr[j++] = temp;
            }
            else if (arr[j] > pivot) {
                int temp = arr[j];
                arr[j] = arr[gt];
                arr[gt--] = temp;
            }
            else
                j++;
        }

        return new int[] { i, gt };
    }

    // Function to find the median of medians
    static int medianOfMedians(int[] arr, int l, int r)
    {
        int n = r - l + 1;

        // Base case: sort and return the median
        if (n <= 5) {
            Arrays.sort(arr, l, r + 1);
            return arr[l + n / 2];
        }

        int[] medians = new int[(n + 4) / 5];
        int idx = 0;

        // Divide the array into groups of five
        for (int i = l; i <= r; i += 5) {
            int end = Math.min(i + 4, r);

            Arrays.sort(arr, i, end + 1);

            int mid = i + (end - i) / 2;
            medians[idx++] = arr[mid];
        }

        // Find the median of the medians
        return kthSmallest(medians, 0, idx - 1, idx / 2);
    }

    // Function to find the kth smallest element
    static int kthSmallest(int[] arr, int l, int r, int k)
    {
        if (l == r)
            return arr[l];

        // Select a pivot using Median of Medians
        int pivot = medianOfMedians(arr, l, r);

        // Partition the array around the pivot
        int[] range
            = partitionAroundPivot(arr, l, r, pivot);

        // Search in the relevant partition
        if (k < range[0])
            return kthSmallest(arr, l, range[0] - 1, k);

        if (k > range[1])
            return kthSmallest(arr, range[1] + 1, r, k);

        return arr[k];
    }

    // Function to find the median
    static double findMedian(int[] arr)
    {
        int n = arr.length;

        // For an odd-sized array
        if (n % 2 == 1)
            return kthSmallest(arr, 0, n - 1, n / 2);

        // For an even-sized array
        int a = kthSmallest(arr, 0, n - 1, n / 2 - 1);
        int b = kthSmallest(arr, 0, n - 1, n / 2);

        return (a + b) / 2.0;
    }

    public static void main(String[] args)
    {
        int[] arr = { 12, 3, 6, 7, 4, 19 };

        System.out.println(findMedian(arr));
    }
}
Python
# Function to partition the array around the pivot
def partitionAroundPivot(arr, l, r, pivot):
    i = l
    j = l
    gt = r

    # Place smaller elements on the left
    # and greater elements on the right
    while j <= gt:
        if arr[j] < pivot:
            arr[i], arr[j] = arr[j], arr[i]
            i += 1
            j += 1

        elif arr[j] > pivot:
            arr[j], arr[gt] = arr[gt], arr[j]
            gt -= 1

        else:
            j += 1

    return i, gt


# Function to find the median of medians
def medianOfMedians(arr, l, r):
    n = r - l + 1

    # Base case: sort and return the median
    if n <= 5:
        arr[l:r + 1] = sorted(arr[l:r + 1])
        return arr[l + n // 2]

    medians = []

    # Divide the array into groups of five
    for i in range(l, r + 1, 5):
        end = min(i + 4, r)

        group = sorted(arr[i:end + 1])
        medians.append(group[len(group) // 2])

    # Find the median of the medians
    return kthSmallest(medians, 0, len(medians) - 1,
                       len(medians) // 2)


# Function to find the kth smallest element
def kthSmallest(arr, l, r, k):
    if l == r:
        return arr[l]

    # Select a pivot using Median of Medians
    pivot = medianOfMedians(arr, l, r)

    # Partition the array around the pivot
    left, right = partitionAroundPivot(arr, l, r, pivot)

    if k < left:
        return kthSmallest(arr, l, left - 1, k)

    if k > right:
        return kthSmallest(arr, right + 1, r, k)

    return arr[k]


# Function to find the median
def findMedian(arr):
    n = len(arr)

    # For an odd-sized array
    if n % 2 == 1:
        return kthSmallest(arr, 0, n - 1, n // 2)

    # For an even-sized array
    a = kthSmallest(arr, 0, n - 1, n // 2 - 1)
    b = kthSmallest(arr, 0, n - 1, n // 2)

    return (a + b) / 2.0


if __name__ == '__main__':
    arr = [12, 3, 6, 7, 4, 19]

    print(findMedian(arr))
C#
using System;

class GFG {
    // Function to partition the array around the pivot
    static int[] partitionAroundPivot(int[] arr, int l,
                                      int r, int pivot)
    {
        int i = l, j = l, gt = r;

        // Place smaller elements on the left
        // and greater elements on the right
        while (j <= gt) {
            if (arr[j] < pivot) {
                int temp = arr[i];
                arr[i++] = arr[j];
                arr[j++] = temp;
            }
            else if (arr[j] > pivot) {
                int temp = arr[j];
                arr[j] = arr[gt];
                arr[gt--] = temp;
            }
            else
                j++;
        }

        return new int[] { i, gt };
    }

    // Function to find the median of medians
    static int medianOfMedians(int[] arr, int l, int r)
    {
        int n = r - l + 1;

        // Base case: sort and return the median
        if (n <= 5) {
            Array.Sort(arr, l, n);
            return arr[l + n / 2];
        }

        int[] medians = new int[(n + 4) / 5];
        int idx = 0;

        // Divide the array into groups of five
        for (int i = l; i <= r; i += 5) {
            int end = Math.Min(i + 4, r);

            Array.Sort(arr, i, end - i + 1);

            int mid = i + (end - i) / 2;
            medians[idx++] = arr[mid];
        }

        // Find the median of the medians
        return kthSmallest(medians, 0, idx - 1, idx / 2);
    }

    // Function to find the kth smallest element
    static int kthSmallest(int[] arr, int l, int r, int k)
    {
        if (l == r)
            return arr[l];

        // Select a pivot using Median of Medians
        int pivot = medianOfMedians(arr, l, r);

        // Partition the array around the pivot
        int[] range
            = partitionAroundPivot(arr, l, r, pivot);

        if (k < range[0])
            return kthSmallest(arr, l, range[0] - 1, k);

        if (k > range[1])
            return kthSmallest(arr, range[1] + 1, r, k);

        return arr[k];
    }

    // Function to find the median
    static double findMedian(int[] arr)
    {
        int n = arr.Length;

        // For an odd-sized array
        if (n % 2 == 1)
            return kthSmallest(arr, 0, n - 1, n / 2);

        // For an even-sized array
        int a = kthSmallest(arr, 0, n - 1, n / 2 - 1);
        int b = kthSmallest(arr, 0, n - 1, n / 2);

        return (a + b) / 2.0;
    }

    static void Main()
    {
        int[] arr = { 12, 3, 6, 7, 4, 19 };

        Console.WriteLine(findMedian(arr));
    }
}
JavaScript
// Function to partition the array around the pivot
function partitionAroundPivot(arr, l, r, pivot)
{
    let i = l;
    let j = l;
    let gt = r;

    // Place smaller elements on the left
    // and greater elements on the right
    while (j <= gt) {
        if (arr[j] < pivot) {
            [arr[i], arr[j]] = [ arr[j], arr[i] ];
            i++;
            j++;
        }
        else if (arr[j] > pivot) {
            [arr[j], arr[gt]] = [ arr[gt], arr[j] ];
            gt--;
        }
        else {
            j++;
        }
    }

    return [ i, gt ];
}

// Function to find the median of medians
function medianOfMedians(arr, l, r)
{
    let n = r - l + 1;

    // Base case: sort and return the median
    if (n <= 5) {
        let group
            = arr.slice(l, r + 1).sort((a, b) => a - b);
        return group[Math.floor(n / 2)];
    }

    let medians = [];

    // Divide the array into groups of five
    for (let i = l; i <= r; i += 5) {
        let end = Math.min(i + 4, r);

        let group
            = arr.slice(i, end + 1).sort((a, b) => a - b);

        medians.push(group[Math.floor(group.length / 2)]);
    }

    // Find the median of the medians
    return kthSmallest(medians, 0, medians.length - 1,
                       Math.floor(medians.length / 2));
}

// Function to find the kth smallest element
function kthSmallest(arr, l, r, k)
{
    if (l === r)
        return arr[l];

    // Select a pivot using Median of Medians
    let pivot = medianOfMedians(arr, l, r);

    // Partition the array around the pivot
    let [left, right]
        = partitionAroundPivot(arr, l, r, pivot);

    if (k < left)
        return kthSmallest(arr, l, left - 1, k);

    if (k > right)
        return kthSmallest(arr, right + 1, r, k);

    return arr[k];
}

// Function to find the median
function findMedian(arr)
{
    let n = arr.length;

    // For an odd-sized array
    if (n % 2 === 1)
        return kthSmallest(arr, 0, n - 1,
                           Math.floor(n / 2));

    // For an even-sized array
    let a = kthSmallest(arr, 0, n - 1, n / 2 - 1);
    let b = kthSmallest(arr, 0, n - 1, n / 2);

    return (a + b) / 2.0;
}

// Driver code
let arr = [ 12, 3, 6, 7, 4, 19 ];

console.log(findMedian(arr));

Output
6.5
Comment