Several Ways to Calculate the Middle Value in JavaScript
Before we start coding, let’s order our ideas. Let’s recall what a median actually is. In a sorted list of numbers, the median is the middle number (if the list has an odd length) and is the average of the two middle numbers (if the list has an even length).
To get the median number of an array of numbers, you can use one of these ways:
1. The most intuitive way uses sorting:
function getMedian(numbers) {
const sorted = [...numbers].sort((a, b) => a - b);
const mid = Math.floor(sorted.length / 2);
return sorted.length % 2 !== 0
? sorted[mid]
: (sorted[mid - 1] + sorted[mid]) / 2;
}
// Example usage:
console.log(getMedian([5, 3, 1, 2, 4])); // 3 (middle of [1,2,3,4,5])
console.log(getMedian([10, 2, 8, 4])); // 6 (average of 4 and 8)
2. To get the median number for large arrays, we can optimize by only sorting the part we need:
function quickSelectMedian(arr) {
const mid = Math.floor(arr.length / 2);
if (arr.length % 2 === 1) {
return quickSelect(arr, mid);
} else {
return (quickSelect(arr, mid - 1) + quickSelect(arr, mid)) / 2;
}
}
function quickSelect(arr, k) {
// Implementation of quickselect algorithm
// (O(n) average time complexity)
}
Note: The quickSelect
function here implements the Quickselect algorithm (similar to Quicksort but only partially sorts the array).
3. For streaming data where numbers arrive one by one, two heaps can efficiently track the median number:
class MedianFinder {
constructor() {
this.maxHeap = new MaxHeap(); // Lower half
this.minHeap = new MinHeap(); // Upper half
}
addNum(num) {
this.maxHeap.insert(num);
this.minHeap.insert(this.maxHeap.extractMax());
if (this.maxHeap.size() < this.minHeap.size()) {
this.maxHeap.insert(this.minHeap.extractMin());
}
}
findMedian() {
return this.maxHeap.size() > this.minHeap.size()
? this.maxHeap.peek()
: (this.maxHeap.peek() + this.minHeap.peek()) / 2;
}
}
Practical Applications Of The Median Number?
Median number calculations can used in many cases, e.g.,
- Data analysis in (outlier detection)
- Salary statistics (more meaningful than average)
- Computer vision (image processing)
- Machine learning (data normalization)