How to find the median of a large array in php

青灯夜游
Release: 2023-03-16 09:22:01
Original
2642 people have browsed it

Method: 1. Use sort() to sort the array, and use count() to find the length of the array; 2. Use "length%2==0" to determine whether the length is an even number or an odd number, and if it is an even number, the median It is "(array name [(length)/2] array name [((length)/2) 1])/2", otherwise it is "array [(length/2)-0.5".

How to find the median of a large array in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

php seeks a large array Median method

Implementation idea:

  • Use sort() to sort the array, Then use count() to find the length of the array

  • Determine whether the length of the array is even or odd

    If the length of the array is even, then the median will bearr[ Array length/2] arr[(array length/2) 1]/ 2.

    If the array length is odd, the median will be the middle element arr[(array length / 2) - 0.5].

Implementation code:

<?php
header("Content-type:text/html;charset=utf-8");
function f($arr){
	sort($arr);
	$len=count($arr);
	if($len%2==0){
		 // 如果长度是偶数
		 echo "中位数为: ".(($arr[$len/2]+$arr[($len/2)- 1])/2)."<br>";
	}else{
		// 如果长度是奇数
		echo "中位数为: ".($arr[($len/2)-0.5])."<br>";
	}
}
$arr1=[1, 4, 7, 9];
f($arr1);
$arr2=[1, 2, 4, 7, 9];
f($arr2);
?>
Copy after login

How to find the median of a large array in php

Recommended learning: "PHP video tutorial

The above is the detailed content of How to find the median of a large array in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template