2.选择排序
<?php
/**
* 基础选择排序
*
*/
function selectionSort($sortData)
{
$count = count($sortData);
$sortCount = 0;
for ($i = $count - 1; $i > 0; $i--) {
$max = $i;
for ($j = 0; $j < $i; $j++) {
$sortCount++;
if ($sortData[$max] < $sortData[$j]) {
$max = $j;
}
}
if ($max != $i) {
$temp = $sortData[$max];
$sortData[$max] = $sortData[$i];
$sortData[$i] = $temp;
}
}
echo 'selectionSort Count:' . $sortCount;
echo PHP_EOL;
return $sortData;
}
/**
* 优化1:每次取最大和最小的
*
*/
function selectionSort_2($sortData)
{
$count = count($sortData);
$sortCount = 0;
for ($i = $count - 1, $sortFrom = 0; $i > $sortFrom; $i--, $sortFrom++) {
$max = $i;
$min = $sortFrom;
for ($j = $sortFrom; $j <= $i; $j++) {
$sortCount++;
if ($sortData[$max] < $sortData[$j]) {
$max = $j;
}
if ($sortData[$min] > $sortData[$j]) {
$min = $j;
}
}
if ($min != $sortFrom) {
$temp = $sortData[$min];
$sortData[$min] = $sortData[$sortFrom];
$sortData[$sortFrom] = $temp;
}
//此处是先排最小值的位置,所以得考虑最大值(arr[max])在最小位置(left)的情况。
if ($max == $sortFrom){
$max = $min;
}
if ($max != $i) {
$temp = $sortData[$max];
$sortData[$max] = $sortData[$i];
$sortData[$i] = $temp;
}
}
echo 'selectionSort_2 Count:' . $sortCount;
echo PHP_EOL;
return $sortData;
}
$testSortData = [3, 2, 9, 234, 3432, 43, 22, 33, 21312, 123];
$sortResult = selectionSort($testSortData);
echo 'selectionSort Result:';
echo PHP_EOL;
echo (implode(',', $sortResult));
echo PHP_EOL;
$sortResult = selectionSort_2($testSortData);
echo 'selectionSort_2 Result:';
echo PHP_EOL;
echo (implode(',', $sortResult));
echo PHP_EOL;