<?PHP$arr=Array(0,5,-1); $temp=0; for($i= 0;$i<Count($arr)-1;$i++) { for($j= 0;$j<Count($arr)-1-$i;$j++) { if($arr[$j]>$arr[$j+1]) { $temp=$arr[$j]; $arr[$j]=$arr[$j+1]; $arr[$j+1]=$temp; } } } foreach($arr as $val) { Echo"<br>".$val; } Selectsort ($arr); Print_r($arr); Insertsort ($arr); Print_r($arr); //Select Sort functionSelectsort (&$arr) { $temp=0; for($i= 0;$i<=Count($arr)-1;$i++) { //Let's say $i is the smallest number. $minval=$arr[$i]; //Record the subscript of the minimum number I think $minIndex=$i; for($j=$i+1;$j<Count($arr);$j++) { //describe the minimum value we think, not the smallest if($minval>$arr[$j]) { $minval=$arr[$j]; $minIndex=$j; } //the last Exchange $temp=$arr[$i]; $arr[$i]=$arr[$minIndex]; $arr[$minIndex]=$temp; } } } //Insert Sort functionInsertsort (&$arr) { //The default subscript is 0 This number is ordered for($i= 0;$i<Count($arr);$i++) { //$insertVal is the number that is ready to be inserted $insertVal=$arr[$i]; //prepare to compare with $insertindex first . $inserIndex=$i-1; //If this condition is met, it is stated that we have not found a suitable location while($inserIndex>0&&$insertVal<$arr[$inserIndex]) { //and move the number back $arr[$inserIndex+1]=$arr[$inserIndex]; $inserIndex--; } //Insert (then give $insertval the appropriate location) $arr[$inserIndex+1]=$insertVal; } }?>
PHP Learning Note 12 "array sorting"