1 <?php 2 3 $arr = array(28,43,54,62,21,66,32,78,36,76,39); 4 $res = bubble_sort($arr); 5 var_dump($res); 6 7 $res = quick_sort($arr); 8 var_dump($res); 9 10 $hs = half_search($arr, 78); 11 var_dump($hs); 12 //冒泡排序 13 function bubble_sort($arr){ 14 if(empty($arr) || !is_array($arr)) return $arr; 15 $count=count($arr); 16 if($count<2) return $arr; 17 18 for($i=$count;$i>0;$i--){ 19 for($j=0;$j<$i;$j++){ 20 if($arr[$j]<$arr[$j-1]){ 21 $temp = $arr[$j-1]; 22 $arr[$j-1] = $arr[$j]; 23 $arr[$j] = $temp; 24 } 25 } 26 } 27 return $arr; 28 } 29 30 //快速排序 31 function quick_sort($arr){ 32 if(!is_array($arr)) return $arr; 33 $len = count($arr); 34 if($len<2) return $arr; 35 $i=rand(1, $len-1); 36 $left = $right = array(); 37 for($j=0;$j<$len;$j++){ 38 if($j==$i) continue; 39 if($arr[$j]<$arr[$i]){ 40 $left[] = $arr[$j]; 41 }else{ 42 $right[] = $arr[$j]; 43 } 44 } 45 $left = quick_sort($left); 46 $right = quick_sort($right); 47 $res = array_merge($left, array($arr[$i]), $right); 48 return $res; 49 } 50 51 //二分查找 52 function half_search($arr, $val){ 53 if(!is_array($arr)) return null; 54 $len = count($arr); 55 if($len<2) return $arr; 56 57 $i = 0; 58 $m = intval(($i+$len)/2); 59 while($i<$len){ 60 61 if($val<$arr[$m]){//在左边 62 $m -= 1; 63 }elseif($val>$arr[$m]){ 64 $m += 1; 65 }else{ 66 return $m; 67 } 68 } 69 70 71 72 }