Search code examples
javascriptarrayssortingmedian

Proper explanation of median javascript code listed below


I'm just looking for a solid explanation of the code listed below? I understand how median works but am unsure why this format properly finds the median each time.

   function median(array) {
  array.sort(function(a, b) {
  return a - b;
  });
  var middle = array.length / 2;
  return middle % 1 ? array[middle - 0.5] : (array[middle - 1] + 
  array[middle]) / 2;
   }

Solution

  • It would actually help if you put a console.log(array) right after the array.sort to visualize it better:

    function median(array) {
      array.sort(function(a, b) {
        return a - b;
      });
      console.log(array)  // <-- so you can see the sorted array
      var middle = array.length / 2;
      return middle % 1 ? array[middle - 0.5] : (array[middle - 1] + array[middle]) / 2;
    }
    
    console.log(median([5,4,3,2,1]))

    By definition median is:

    The median is the value separating the higher half from the lower half of a data sample. For a data set, it may be thought of as the "middle" value. For example, in the data set {1, 3, 3, 6, 7, 8, 9}, the median is 6, the fourth largest, and also the fourth smallest, number in the sample

    So first the array must be sorted so we can figure out which is the smallest and which the largest number. Then we find out the middle of the array. After that we simply check if the length was an even or odd number by using the % modulus operator => (5/2)%1 would be 0.5 where (4/2)%1 would be 0 and based on that we select the proper item by index from the array (Note array indexes start from 0).

    Lets use array of [5,4,3,2,1] as an example:

    Sorted that would be [1,2,3,4,5], the remainder of the length of the array divided by 2 would be 2.5 and modulus 1 of that would mean 0.5. So in this case we would pick array[middle-0.5] value from the array which would mean array[2.5-0.5] which would be 2. Our array at index 2 has the value of 3 hence the median of that array is 3.

    In the case of [1,2,3,4] the median would be 2.5 since the modulus would return 0 and we would go to the else of the ternary operator which is:

    (array[middle - 1] + array[middle]) / 2

    That in our case would mean (array[2-1] + array[2]) / 2 that when we replace the values from the array indexes would be (2+3)/2 = 2.5

    Hope this clears it.