- function Maopao ($arr, $style)//The value is passed by default, not the address. If you add a & before $arr, and $arr1 point to the same address, the $ARR1 outside the function is also lined up.
- {
- $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 transverse cycle down the flag==false, indicating that each of the adjacent elements in the longitudinal cycle is relatively large hours if the condition is not satisfied, that is, from small to large has been lined up, no further transverse cycle
- }
- }
- foreach ($arr as $key = $value)
- {
- echo $value. ', ';
- }
- }
- $arr 1=array (101,101,-9,-8,0,76,1,57,43,90,23,-56);
- Maopao ($arr 1, ' STB ');//small to Big
- ?>
Copy Code
For examples of bubble sorting, you can also refer to the following article: Php bubble sort of exchange sorting method another PHP bubble sort (bubble sort) example PHP implementation bubble sort algorithm code PHP bubble sorting algorithm A case of PHP bubble sort and Quick sort Example 2, Select Sort: The second number to the nth number is compared with the first number, and the third number to the nth number is compared with the second number respectively, and is exchanged until the sorting is complete.
-
/**
- *
- *
- *
- */
- 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. ', ';
- }
- }
- $arr 1=array (21.5,33,90,7,-4,5,55,11);
- Selectsort ($arr 1, ' STB ');
-
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. ', ';
- }
- }
- $arr 1=array (21.5,33,90,7,-4,5,55,11);
- Selectsort ($arr 1, ' STB ');
- echo "
";
- ?>
Copy Code |