Insertion Sort: Each time a record to be sorted is inserted into the appropriate position in the previously sorted sub-file according to its key size, until all records are inserted.
//插入排序(一维数组) function insert_sort($arr) { $count = count($arr); for($i=1; $i<$count; $i++) { $tmp = $arr[$i]; $j = $i - 1; while($arr[$j] > $tmp) { $arr[$i] = $arr[$j]; $arr[$j] = $tmp; $j--; } } return $arr; }
//选择排序(一维数组) function selection_sort($arr) { $count = count($arr); for($i=0; $i<$count; $i++) { $k = $i; for($j=$i+1; $j<$count; $j++) { if($arr[$k] > $arr[$j]) { $k = $j; } if($k != $i) { $tmp = $arr[$i]; $arr[$i] = $arr[$k]; $arr[$k] = $tmp; } } } return $arr; }
//冒泡排序(一维数组) //实际效果是:每次循环将数组中最小的值放置到数组的最前段,然后,下一次循环不再循环已放置正确数组值的键,以此类推 function selection_sort($arr) { $count = count($arr); if($count <= 0) return false; for($i=0; $i<$count; $i++) { for($j=$count-1; $j>$i; $j--) { if($arr[$j] < $array[$j-1]) { $tmp = $arr[$j]; $arr[$j] = $arr[$j-1]; $arr[$j-1] = $tmp; } } } return $arr; }
//快速排序(一维数组) function quick_sort($arr) { $count = count($arr); if($count <= 1) return $arr; $key = $arr[0]; $left_arr = array(); $right_arr = array(); for($i=1; $i<$count; $i++) { if($arr[$i] <= $key) $left_arr[] = $arr[$i]; else $right_arr[] = $arr[$i]; } $left_arr = quick_sort($left_arr); $right_arr = quick_sort($right_arr); return array_merge($left_arr,array($arr), $right_arr); }
The above introduces the implementation of common sorting algorithms in PHP, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.