VOOZH about

URL: https://www.geeksforgeeks.org/dsa/median-of-an-unsorted-array-in-liner-time-on/

⇱ Median of an Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Median of an Array

Last Updated : 12 Jul, 2025

Given an array arr[], the task is to find the median of this array. The median of an array of size n is defined as the middle element when n is odd and the average of the middle two elements when n is even.

Examples:

Input: arr[] = [12, 3, 5, 7, 4, 19, 26]
Output:
Explanation: Sorted sequence of given array arr[] = [3, 4, 5, 7, 12, 19, 26] Since the number of elements is odd, the median is 4th element in the sorted sequence of given array arr[], which is 7

Input: arr[] = [12, 3, 5, 7, 4, 26] 
Output: 6
Explanation: Since number of elements are even, median is average of 3rd and 4th element in sorted sequence of given array arr[], which means (5 + 7)/2 = 6

[Naive Approach] By Sorting the Array - O(n log n) Time and O(1) Space

The basic idea is to sort the array and check the array size if it is odd then return the middle otherwise return the average of the two middle elements.


Output
4.5

Time Complexity: O(n log n) as we need to sort the array first. 
Auxiliary Space: O(1)

[Expected Approach]: Using Randomized QuickSelect

To find the median of an array, randomly select a pivot element and partition the array using the quicksort technique, placing smaller elements to the left and larger ones to the right. If the pivot lands at the middle index, it is the median. Otherwise, recursively apply this process to the relevant subarray. For even-sized arrays, find the two middle elements and calculate their average.


Output
6.5

Time Complexity:

  1. Best case analysis: O(1)
  2. Average case analysis: O(n)
  3. Worst case analysis: O(n2)

Auxiliary Space: O(n)

[Worst Case Linear Time Approach] - Using Order Statistics

The idea in this new method is similar to quickSelect(). We get worst-case linear time by selecting a pivot that divides the array in a balanced way (there are not very few elements on one side and many on another side). After the array is divided in a balanced way, we apply the same steps as used in quickSelect() to decide whether to go left or right of the pivot. Please refer K’th Smallest/Largest Element in Unsorted Array | Worst case Linear Time for implementation and more details.

Note : Although this approach looks good on paper, the previous quick select approach works better in practice.


Comment
Article Tags: