Home > Backend Development > PHP Tutorial > PHP example code: various sorting algorithms_PHP tutorial

PHP example code: various sorting algorithms_PHP tutorial

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-07-13 10:22:29
Original
754 people have browsed it

php example code: various sorting algorithms

// Bubble sort

Function maopao_sort($demo){

 $num = count($demo);

for($i=0;$i<$num;$i++){

for($j=$num-1;$j>$i;$j--){

 if($demo[$j]<$demo[$j-1]){

$temp = $demo[$j];

$demo[$j]=$demo[$j-1];

 $demo[$j-1]= $temp;

 }

 }

 }

return $demo;

 }

 //Insertion sort

Function charu_sort($demo){

 $num = count($demo);

for($i=1;$i<$num;$i++){

$temp=$demo[$i];

 $dqweizhi = $i-1;//Record the current position

While(($dqweizhi>=0)&&($temp<$demo[$dqweizhi])){

 $demo[$dqweizhi+1] = $demo[$dqweizhi];

 $dqweizhi--;

 }

 $demo[$dqweizhi+1] = $temp;

 }

return $demo;

 }

// Sorting by selection method

Function select_sort($demo){

 $num = count($demo);

for($i=0;$i<$num-1;$i++){

$temp=$demo[$i];

 $dqweizhi=$i;

for($j=$i+1;$j<$num;$j++){

 if($demo[$j]<$temp){

$temp=$demo[$j];

 $dqweizhi=$j;

 }

 }

 $demo[$dqweizhi]=$demo[$i];

$demo[$i]=$temp;

 }

return $demo;

 }

//Quick sort

Function quick_sort($demo)

 {

 $num = count($demo);

 if($num<=1){

return $demo;

 }

 $key=$demo[0];

 $left_array=array();

$right_array=array();

for($i=1;$i<$num;$i++){

 if($demo[$i]<=$key){

$left_array[]=$demo[$i];

 }else{

$right_array[]=$demo[$i];

 }

 }

 $left_array =quick_sort($left_array);

$right_array=quick_sort($right_array);

Return array_merge($left_array,array($key),$right_array);

 }

 $test = array('43','154','3','78','13','284','167','2','56','2234','121 ','57','345');

 $sss = quick_sort($test);

var_dump($sss);

 ?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/848318.htmlTechArticlephp example code: various sorting algorithms //bubble sort function maopao_sort($demo){ $num = count($demo); for($i=0;$i$num;$i++){ for($j=$num-1;$j$i;$j--){ if($demo[$j ]$demo[$j-1]){...
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template