Sorting algorithms
<?phpnamespace iphp\algorithm;/** * Created by PhpStorm. * User: 123 * date: 14-9-3 * time: pm 3:53 */class sort{ /** * bubble sort * algorithm, 2 adjacent elements compared, if the former is greater than the latter, Swap position * First comparison, the largest element is ranked at the end. * need n-1 times bubble * @param $arr * @return mixed */ public static function bubble ($arr) { $num =count ($arr) if ($num <=1) return $arr; //Some logos are used to judge if there is no exchange at one time. Then there is no need for the next cycle &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBsp; $flag =false; for ($i =0; $i < $num-1; $i + +) { for ($j = 0 $j < $num $i $j + +) { //Exchange Elements if ($arr [$j]> $arr [$j +1]) { $tmp = $arr [$j]; $arr [$j]= $arr [$j +1]; $arr [$j +1]= $tmp; $flag =true; } } if ($flag ==false) break; } return $arr; } /** * Select Sort * First, take the minimum value between each 1-n element, compare it to the No. 0 element, and put the smallest one in front. * @param $arr * @return mixed */ public static function select ($arr) { $num =count ($arr); if ($num <= 1) return $arr; for ($i =0; $i < $num-1; $i + +) { $minValue = $arr [$i]; $minIndex = $i; for ($j = $i +1; $j < $num; $j + +) { if ($minValue > $arr [$j]) { $minValue = $arr [$j]; $minIndex = $j; } } //Swap Location if ($i! = $j) { $tmp = $arr [$i]; $arr [$i]= $minValue; $arr [$minIndex]= $tmp; } } return $arr; } /** * Insert Sort * initially treats the first element of the array as a sorted array. The subsequent elements are compared with the ordered, inserted into the sorted position. * @param $arr * @return mixed */ public static function insert ($arr) { $num =count ($arr); if ($num <=1) return $arr, for ($i =1; $i < $num; $i +) { $ Insertvalue= $arr [$i];&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBsp; $insertIndex = $i -1; while ($insertIndex >=0 && $insertValue < $arr [$insertIndex]) { $arr [$insertIndex +1]= $arr [$insertIndex]; $insertIndex--; } $arr [$insertIndex +1]= $insertValue; } return $arr; } /* * * Quick Sort * @param $arr * @return Array */ public static function quick ($arr ) { $num =count ($arr); if ($num <=1) return $arr; $middle = $arr [0]; $leftArr =array (); $rightArr =array (); for ($i =1; $i < $num; $i + +) { if ($arr [$i]<=$ Middle) $ leftarr[]= $arr [$i]; else $RIGHTARR []= $arr [$i]; } $leftArr =self::quick ($LEFTARR); $rightArr =self::quick ($RIGHTARR); return array_merge ($LEFTARR, Array ($middle), $RIGHTARR); }}
This article from the "PHP Programmer" Blog, reproduced please contact the author!
PHP Common sorting algorithm