Home >Backend Development >PHP Tutorial >PHP quick sorting principle, implementation method and example analysis
This article mainly introduces the principle and implementation method of PHP quick sort, and analyzes the algorithm principle and specific implementation techniques of PHP quick sort in the form of examples. Friends in need can refer to it
The details are as follows:
<?php $n = array('13','14','55','10','54','2','79','106','89','90','22','60','111','77777','-110','-10','123'); function partition($n,$left,$right) { global $n; $pivot = $n[$left]; $lo=$left; $hi=$right+1; while($lo+1!=$hi) { if($n[$lo+1]<$pivot) $lo++; else if($n[$hi-1]>$pivot) $hi--; else{ $t=$n[$lo+1]; $n[$lo+1]=$n[$hi-1]; $n[$hi-1]=$t; $lo++; $hi--; } } $n[$left]=$n[$lo]; $n[$lo]=$pivot; return $lo; } function quicksort($n,$left,$right) { global $n; $dp = 0; if ($left<$right) { $dp=partition($n,$left,$right); quicksort($n,$left,$dp-1); quicksort($n,$dp+1,$right); } } quicksort($n,0,sizeof($n)-1); print_r($n); ?>
Quick sort is an improvement on bubble sort. Its basic idea is to divide the data to be sorted into two independent parts through one-way sorting. All the data in one part is smaller than all the data in the other part, and then the two parts of the data are sorted sequentially. For quick sorting, the entire sorting process can be performed recursively, so that the entire data becomes an ordered sequence.
Assuming that the array to be sorted is A[1]...A[N], first select any data (usually the first data) as the key data, and then put all numbers smaller than it In front of it, all numbers larger than it are placed behind it. This process is called one-position quick sort. The algorithm of quick sorting is:
1), set two variables I, J, when sorting starts, I: = 1, J: = N;
2), use the first array As key data, the element is assigned to X, that is, If there is a value less than ;
5), repeat steps 3 and 4 until I=J;
Quick sort is to recursively call this process - split the data sequence with 49 as the midpoint, and separate the previous part and The latter part performs similar quick sorting to complete the quick sorting of all data sequences, and finally turn this data sequence into an ordered sequence
Summary: The above is the entire content of this article, I hope it can be helpful to everyone learning helps.
Related recommendations:
phpDetailed explanation of WeChat development access example
php Detailed explanation of WeChat development access example
PHP MySQL implements fuzzy query employee information functionThe above is the detailed content of PHP quick sorting principle, implementation method and example analysis. For more information, please follow other related articles on the PHP Chinese website!