Home > Backend Development > PHP Tutorial > PHP implements quick sort method function code_PHP tutorial

PHP implements quick sort method function code_PHP tutorial

WBOY
Release: 2016-07-21 15:16:23
Original
1001 people have browsed it

Code 1:

Copy code The code is as follows:

function quicksort($str){
if(count($str)<=1) return $str;//If the number is not greater than one, return directly
$key=$str[0];//Take a value and use it later To compare;
$left_arr=array();
$right_arr=array();
for($i=1;$iif($str[$i]<=$key)
$left_arr[]=$str[$i];
else
$right_arr[]=$str[$i];
}
$left_arr=quicksort($left_arr);//Perform recursion;
$right_arr=quicksort($right_arr);
return array_merge($left_arr,array($key),$right_arr);//Merge the left, middle and right values ​​into an array;
}//The following is the test
$str=array(5,3, 8,2,5,9,7,2,1,4,0);
print_r(quicksort($str));
?>

Code 2:
Copy code The code is as follows:

/* @quicksort*/
function quickSort($left,$right ,$arr){
$l = $left;
$r = $right;
$pivot = $arr[($left+$right)/2];
$temp = 0;

while($l<$r){
while($arr[$l]<$pivot){
$l++;
}
while($arr[ $r]>$pivot){
$r--;
}

if($l>=$r) break;

$temp = $arr[ $l];
$arr[$l] = $arr[$r];
$arr[$r] = $temp;

if($arr[$l]== $pivot) --$r;
if($arr[$r]==$pivot) ++$l;
}

if($l==$r){
$l++;
$r--;
}

if($left<$r){
quickSort($left, $r, $arr);
}elseif($right>$l){
quickSort($l, $right, $arr);
}else{
return $arr;
}
}

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/325921.htmlTechArticleCode 1: Copy the code as follows: ?php function quicksort($str){ if(count($str) =1) return $str;//If the number is not greater than one, return directly $key=$str[0];//Get a value and use it later...
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