排序算法:
(1)冒泡排序
1 $arr = array(15,8,20,50,37,85,10,5,11,4); 2 //冒泡排序 3 function maoPao($arr){ 4 for($i = 0; $i < count($arr)-1; $i++){ 5 for($j = 0; $j < count($arr)-1; $j++){ 6 if($arr[$j] > $arr[$j+1]){ 7 $temp = $arr[$j]; 8 $arr[$j] = $arr[$j+1]; 9 $arr[$j+1] = $temp; 10 } 11 } 12 } 13 return $arr; 14 }
(2)快速排序
1 $arr = array(15,8,20,50,37,85,10,5,11,4); 2 //快速排序 3 function fastSort($arr){ 4 $len = count($arr); 5 6 if($len <= 1){ 7 return $arr; 8 } 9 10 $key = $arr[0]; 11 $left = array(); 12 $right = array(); 13 14 for($i = 1; $i < $len; $i++){ 15 if($arr[$i] > $key){ 16 $right[] = $arr[$i]; 17 } else { 18 $left[] = $arr[$i]; 19 } 20 } 21 22 $left = fastSort($left); 23 $right = fastSort($right); 24 25 return array_merge($left, array($key), $right); 26 }
查找算法:
(1):普通 (适用于无规则的数组,但效率相对较低)
1 function search($arr, $val){ 2 foreach($arr as $k => $v){ 3 if($v == $val){ 4 return $k; 5 } 6 } 7 return -1; 8 }
(2):二分查找(仅适用于有序的索引数组,效率较高)
1 //二分查找法 2 function binSearch($arr, $val){ 3 $len = count($arr); 4 $low = 0; 5 $end = $len - 1; 6 7 while($low <= $end){ 8 $mid = floor(($low+$end)/2); 9 10 if($arr[$mid] == $val){ 11 return $mid; 12 } else if($arr[$mid] > $val){ 13 $end = $mid - 1; 14 } else { 15 $low = $mid + 1; 16 } 17 } 18 19 return -1; 20 }