time-to-botec

Benchmark sampling in different programming languages
Log | Files | Refs | README

median.js (1680B)


      1 /**
      2 * @license Apache-2.0
      3 *
      4 * Copyright (c) 2018 The Stdlib Authors.
      5 *
      6 * Licensed under the Apache License, Version 2.0 (the "License");
      7 * you may not use this file except in compliance with the License.
      8 * You may obtain a copy of the License at
      9 *
     10 *    http://www.apache.org/licenses/LICENSE-2.0
     11 *
     12 * Unless required by applicable law or agreed to in writing, software
     13 * distributed under the License is distributed on an "AS IS" BASIS,
     14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     15 * See the License for the specific language governing permissions and
     16 * limitations under the License.
     17 */
     18 
     19 'use strict';
     20 
     21 // MODULES //
     22 
     23 var floor = require( '@stdlib/math/base/special/floor' );
     24 
     25 
     26 // FUNCTIONS //
     27 
     28 /**
     29 * Comparator function used to sort values in ascending order.
     30 *
     31 * @private
     32 * @param {number} a - first number
     33 * @param {number} b - second number
     34 * @returns {number} difference between `a` and `b`
     35 */
     36 function ascending( a, b ) {
     37 	return a - b;
     38 }
     39 
     40 
     41 // MAIN //
     42 
     43 /**
     44 * Computes the median of an array.
     45 *
     46 * @param {Array} arr - input array
     47 * @returns {number} median value
     48 */
     49 function median( arr ) {
     50 	var len = arr.length;
     51 	var id;
     52 	var d;
     53 	var i;
     54 
     55 	if ( !len ) {
     56 		return null;
     57 	}
     58 
     59 	// Copy and sort data in ascending order:
     60 	d = [];
     61 	for ( i = 0; i < len; i++ ) {
     62 		d.push( arr[ i ] );
     63 	}
     64 	d.sort( ascending );
     65 
     66 	// Get the middle index:
     67 	id = floor( len / 2 );
     68 
     69 	if ( len % 2 ) {
     70 		// The number of elements is not evenly divisible by two, hence we have a middle index:
     71 		return d[ id ];
     72 	}
     73 	// Even number of elements, so must take the mean of the two middle values:
     74 	return ( d[ id-1 ] + d[ id ] ) / 2.0;
     75 }
     76 
     77 
     78 // EXPORTS //
     79 
     80 module.exports = median;