当前位置: 首页 > 后端技术 > PHP

php插入排序,快速排序,归并排序,堆排序

时间:2023-03-30 00:32:53 PHP

//冒泡排序函数bubble_sort(&$arr){//php把数组当做基本类型,所以必须对原数组进行修改,传入引用for($i=0;$i$arr[$j+1]){$temp=$arr[$j];$arr[$j]=$arr[$j+1];$arr[$j+1]=$temp;}}插入排序函数insertSort(&$arr){for($i=1;$i=0&&$arr[$j]>$temp;$j--){$arr[$j+1]=$arr[$j];$arr[$j]=$temp;}}}快速排序publicfunctionquickSort($arr){$len=count($arr);如果($len<=1)返回$arr;$左=$右=[];$mid_index=$len>>1;echo$len,'.......',$mid_index,"
";$mid_value=$arr[$mid_index];对于($i=0;$i<$len;$i++){如果($i==$mid_index)继续;如果($arr[$i]<$mid_value)$left[]=$arr[$i];否则$right[]=$arr[$i];}返回array_merge($this->quickSort($left),(array)$mid_value,$this->quickSort($right));}归并排序publicfunctionmerge_sort($arr){$len=count($arr);如果($len<=1)返回$arr;$half=($len>>1)+($len&1);dd(($len>>1));$arr2d=array_chunk($arr,$half);$left=$this->merge_sort($arr2d[0]);$right=$this->merge_sort($arr2d[1]);while(count($left)&&count($right)){如果($left[0]<$right[0])$reg[]=array_shift($left);否则$reg[]=array_shift($right);}返回array_merge($reg,$left,$right);}堆排序publicfunctionswap(&$x,&$y){$t=$x;$x=$y;$y=$t;}公共函数max_heapify(&$arr,$start,$end){$dad=$start;$儿子=$爸爸*2+1;如果($son>=$end)返回;如果($son+1<$end&&$arr[$son]<$arr[$son+1])$son++;如果($arr[$dad]<$arr[$son]){$this->swap($arr[$dad],$arr[$son]);$this->max_heapify($arr,$son,$end);}}publicfunctionheap_sort($arr){$len=count($arr);//获取个数for($i=ceil($len/2)-1;$i>=0;$i--){//处理一半的数据$this->max_heapify($arr,$i,$len);}for($i=$len-1;$i>0;$i--){$this->swap($arr[0],$arr[$i]);$this->max_heapify($arr,0,$i);}返回$arr;}