Home >Backend Development >PHP Tutorial >A small example of quick sort

A small example of quick sort

WBOY
WBOYOriginal
2016-07-29 09:04:571073browse

function quickSort($array)
{
if( !isset( $array[1] ) ) return $array;
$mid = $array[0]; //Get a keyword for splitting , usually the first element
$leftArray = array();
$rightArray = array();
foreach( $array as $v )
{
if($v > $mid)
$rightArray[] = $ v; //Put the number larger than $mid into an array
                                                                                                                                                                                                                                              can be put the numbers larger than $mid into an array.
}
$leftArray = quickSort($leftArray); //Split the smaller array again
$leftArray[] = $mid;
$rightArray = quickSort($rightArray); //Split the larger array again
return array_merge($leftArray,$rightArray); //Combine the two results
}
print_r( quickSort( array( '6' ,'5','3','7','9' ) ) );
The above introduces a small example of quick sorting, including aspects of content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
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