median
unsorted array
algorithm
data structures
programming

Finding the median of an unsorted array

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Finding the median of an unsorted array can be a common problem faced in statistical analysis and data processing tasks. The median is a measure of central tendency that refers to the middle value of a dataset when it is arranged in ascending or descending order. This article explores various approaches to find the median of an unsorted array, including technical explanations and examples.

Median Definition and Significance

The median represents a value that divides a dataset into two equal halves. It is less sensitive to extreme values (outliers) than the arithmetic mean, making it a reliable indicator of central tendency for skewed distributions.

Methods to Find the Median

To find the median of an unsorted array, you can choose from several approaches:

Sorting the Array

The simplest method is to first sort the array and then select the middle element(s).

  1. Sorting Algorithm: You can use algorithms like QuickSort, MergeSort, or any built-in sorting function.
  2. Identify Median:
    • For an array of odd length `n`, the median is the element at index `(n // 2)`.
    • For even length, it is the average of elements at indices `(n // 2 - 1)` and `(n // 2)`.

Example

Consider the unsorted array: `[3, 1, 5, 2, 4]`.

  • Sorted Array: `[1, 2, 3, 4, 5]`
  • Median: Since the array length is odd, the median is at position `5 // 2 = 2`, i.e., `3`.

Using Partition-based Algorithms

The median can be found more efficiently in O(n)O(n) time using algorithms inspired by QuickSelect, a selection algorithm related to QuickSort.

  1. QuickSelect: It is a recursive algorithm to find the `k`-th smallest element directly without fully sorting the array.
  2. Time Complexity: O(n)O(n) on average, similar in principle to QuickSort but only focusing on one partition.

Example

For the array `[3, 1, 5, 2, 4]`, if you aim to find the 3rd smallest element (the median for the 0-indexed odd-length array), QuickSelect helps eliminate unnecessary sort.

Median of Medians Algorithm

This algorithm ensures a deterministic linear time complexity, O(n)O(n), even in the worst case:

  1. Divide the Array: Split into groups of five.
  2. Find Medians: Compute the median for each group.
  3. Recursion: Use the median of these medians as a pivot to partition the array, similar to QuickSelect.
  4. Select Median: Apply recursive selection to find the exact median.

Example

Applying the Median of Medians to `[3, 1, 5, 2, 4]` involves grouping and selecting submedians periodically until the central element is found.

Comparative Analysis

MethodTime ComplexitySpace ComplexitySuitability
SortingO(nlogn)O(n \log n)O(1)O(1) or O(n)O(n)Simple, but slow for large arrays.
QuickSelectO(n)O(n) (average) O(n2)O(n^2) (worst)O(1)O(1)Fast for large datasets; average performance.
Median of MediansO(n)O(n)O(n)O(n)Always linear time; more complex to implement.

Additional Considerations

  • Handling Edge Cases: Consider arrays with duplicates, single-element arrays, or empty arrays, which require handling potential exceptions.
  • Implementation Complexity: While sorting methods are easy to implement, algorithms like QuickSelect and Median of Medians may require a deeper understanding of recursive logic and partitioning techniques.

Conclusion

Finding the median of an unsorted array is a fundamental problem in computational statistics and algorithm design. While straightforward methods like sorting are intuitive, algorithms like QuickSelect and the Median of Medians offer optimal solutions for real-world large data scenarios. Each method has its trade-offs regarding time and space complexity, implementation complexity, and application context. The choice of method should consider these factors alongside the specific use-case requirements.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.