Some array sorting methods in php are Shared

  • 2020-05-19 04:21:57
  • OfStack

A. Internal sort (direct load into memory sort) : including switching sort (bubbling and quickacting), selection sort, insertion sort
B. External sorting (due to the large amount of data, it needs external storage to sort) : including merge sorting, direct merge sorting

[bubble sort: compare the sorting codes of adjacent elements from the back to the front, and if the reverse order is found, it will be exchanged. After the end of one round, another round will be added, until all adjacent Numbers have no reverse order, that is, they will be sorted in order.]
 
function maoPao($arr,$style)// The default is to pass the value, not the address $arr Before adding a & , and $arr1 Point to the same 1 Address, outside of the function $arr1 And it's already lined up.  
{ 
$temp=0; 
$flag=false; 
for($i=0;$i<count($arr)-1;$i++) 
{ 
for($j=0;$j<count($arr)-1-$i;$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 1 The next horizontal loop comes down flag==false; Indicates that each adjacent element in the vertical cycle is relatively large if Conditions are not met, that is, from small to large has been arranged, no need to cycle again  
} 
} 
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 

Selection sort: the number of the second to the number of n is compared with the number of the first to exchange, and the number of the third to the number of n is compared with the number of the second to exchange, until the end of sorting.
 
function selectSort($arr,$style) 
{ 
$temp=0; 
$flag=false; 
for($i=0;$i<count($arr)-1;$i++) 
{ 
for($j=$i+1;$j<count($arr);$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'); 

 
function selectSort($arr,$style) 
{ 
$temp=0; 
$flag=false; 
for($i=0;$i<count($arr)-1;$i++) 
{ 
for($j=$i+1;$j<count($arr);$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 "<br/>"; 

Related articles: