<?php $unsorted = array(); for ($i = 0; $i < 10; $i++) { $unsorted[] = rand(0,1000); } print "Unsorted Array. <br />"; print implode(',', $unsorted); print "<br />"; print "Sorted Array. <br />"; $sort = select_sort($unsorted); print implode(',',$sort); /** selection sort 1. 找到数组最小的数 2. 与第一个数交换 3. 重复余下的元素 */ function select_sort ($arr = array()) { $min = false; $n = count($arr); for ($i = 0; $i < $n; $i++) { $min = $i; for ($j = $i + 1; $j < $n; $j++) { if ($arr[$j] < $arr[$min]) { $min = $j; } } // $tmp = $arr[$min]; // $arr[$min] = $arr[$i]; // $arr[$i] = $tmp; list($arr[$min],$arr[$i]) = array($arr[$i],$arr[$min]); } return $arr; }
?