Home >Backend Development >PHP Tutorial >Several program examples of php array sorting_PHP tutorial
A. Internal sorting (directly loaded into memory for sorting): including exchange sorting (bubble and quick methods), selection sorting, and insertion sorting B. External sorting (due to the large amount of data, external storage is required for sorting): including merge sort and direct merge sort
[Selection sort: The second to nth numbers are compared with the first number respectively, and then Exchange, the third to nth numbers are compared with the second number respectively, and exchange is performed until the arrangement is completed]
The code is as follows | Copy code | ||||
{ $temp=0; for($i=0;$i If($style=='bts') $op=$arr[$i]<$arr[$j]; else if($style=='stb') $op=$arr[$i]>$arr[$j]; If($op) $temp=$arr[$i]; $arr[$i]=$arr[$j]; $arr[$j]=$temp; } } } foreach ($arr as $key => $value) echo $value.','; } } $arr1=array(21.5,33,90,7,-4,5,55,11); selectSort($arr1,'stb'); |
[By default, the value is passed, not the address. If you add an & before $arr, it points to the same address as $arr1, and $arr1 outside the function is also arranged]
The code is as follows | Copy code | ||||
$temp=0; for($i=0;$i If($style=='bts') $op=$arr[$j]<$arr[$j+1]; else if($style=='stb') $op=$arr[$j]>$arr[$j+1]; If($op) $temp=$arr[$j]; $arr[$j]=$arr[$j+1]; $arr[$j+1]=$temp; } } } foreach ($arr as $key => $value) echo $value.','; } } $arr1=array(101,101,-9,-8,0,76,1,57,43,90,23,-56); maoPao($arr1,'stb');//small to big |
[Insertion sort: The second one is compared with the first one and exchanged, and the third one is compared with the first two and exchanged. . . . Compare the nth one with the first n-1 and exchange]
The code is as follows
|
Copy code | ||||
http: //www.bkjia.com/PHPjc/631612.html