Given [30, 10, 20]
//sort
sorted = [10, 20, 30]
middleIndex = sorted.length / 2 = 3/2 = 1.5
round down middleIndex = 1
median = sorted[middleIndex] = 20
Given [30, 10, 40, 20]
//sort
sorted = [10, 20, 30, 40]
index2 = sorted.length/2 = 4/2 = 2
index1 = index2 - 1 = 2 - 1 = 1
n1 = sorted[index1] = 20
n2 = sorted[index2] = 30
median = (n1 + n2) / 2
testMedianOddCase() { const unit = new Stats(30, 10, 20]); this.assertEquals(20, unit.median()); } testMedianEvenCase() { const unit = new Stats([30, 10, 40, 20]); this.assertEquals(25, unit.median()); } testMedianOneValue() { const unit = new Stats(200]); this.assertEquals(200, unit.median()); } testMedianEvenCaseFloatingPointCenter() { const unit = new Stats([20, 15, 20, 15]); this.assertEquals(17.5, unit.median()); } testMedianEmptyCase() { const unit = new Stats([]); this.assertEquals(null, unit.median()); }
let count = this.count() if (count == 0) return null
(n % 2) == 1
if nums.length is odd call Recipe (Odd Length Case) else call Recipe (Even Length Case)
middleIndex = Math.round(middleIndex);
nums = this.nums
sorted = nums sorted
middleIndex = sorted.length / 2
middleIndex = middleIndex rounded down
median = sorted[middleIndex]
return median
nums = this.nums
sorted = nums sorted
index2 = sorted.length / 2
index1 = index2 - 1
n1 = sorted[index1]
n2 = sorted[index2]
median = (n1 + n2) / 2
return median