Interactive online courses HTML Academy
2026-03-09 14:05 Diff

The sorting program is ready and tested. Now let’s proceed to calculation of the median. The median is a median value, i.e. literally an element located in the middle of the array.

The median differs from the average value with its resistance to deviations:

// Average: 3 [1, 2, 3, 4, 5] // Median: 3 [1, 2, 3, 4, 5] // Average: 12 [1, 2, 3, 4, 50] // Median: 3 [1, 2, 3, 4, 50]

It is easy to calculate a median for an array with an odd number of elements. To do this, you need to correctly calculate the average element index. Let’s try to derive the formula:

// Array length 3, middle element index 1 [1, 2, 3] // Array length 5, middle element index 2 [1, 2, 3, 4, 5] // Array length 7, middle element index 3 [1, 2, 3, 4, 5, 6, 7]

Let’s subtract one from the array length, divide it by two, and we got the index.

Muffin can send data arrays of different lengths, so you’ll have to check the number of elements for parity and, depending on result, find the median. To check for parity, let’s use the operator we are already familiar with: %.