-
- function maoPao($arr,$style)//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
- {
- $temp=0;
- $flag=false;
- for($i=0; $i{
- for($j=0;$j{
- 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;
- $flag=true;
- }
- }
- if($flag==false)
- {
- break;//When a horizontal loop comes down, flag==false; indicates that each adjacent element in the vertical loop When comparing sizes, the if conditions are not met, that is, they have been arranged from small to large, and there is no need to loop horizontally
- }
- }
- 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
- ?>
Copy code
For examples of bubble sorting, you can also refer to the following articles:
php bubble sort exchange sort method
Another example of php bubble sort
php code to implement bubble sort algorithm
An example of php bubble sorting algorithm
Examples of php bubble sort and quick sort
2. Select sorting:
The second to nth numbers are compared with the first number respectively and exchanged, and the third to nth numbers are compared with the second number respectively and exchanged until the sorting is completed.
-
-
/** - *
- *
- *
- */
- function selectSort($arr,$style)
- {
- $temp=0;
- $flag=false;
- for ($i=0;$i{
- for($j=$i+1;$j{
- 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 ;
- $flag=true;
- }
- }
- if($flag==false)
- {
- break;
- }
- }
- foreach ($arr as $key => $value)
- {
- echo $value. ',';
- }
- }
- $arr1=array(21.5,33,90,7,-4,5,55,11);
- selectSort($arr1,'stb');
- < ;p>function selectSort($arr,$style)
- {
- $temp=0;
- $flag=false;
- for($i=0;$i{
- for($j=$i+1;$j{
- 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;
- $flag=true;
- }
- }
- if($flag==false)
- {
- break;
- }
- }
- foreach ($arr as $key => $value)
- {
- echo $value.',';
- }
- }
- $arr1=array(21.5,33,90,7, -4,5,55,11);
- selectSort($arr1,'stb');
- echo "
";
- ?>
-
Copy code
|