5-选择排序-PHP版

75 阅读1分钟
<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2021.1.26
 * Time: 15:22
 */
include_once '../Util.php';
include_once './BubleSort.php';
include_once './InsertSort.php';
include_once './MergeSort.php';
function selectSort(array &$array) {
    $length = count($array);
    for ($i=0;$i<$length;$i++) {
        $minIndex = $i;
        for ($j = $i+1;$j<$length;$j++) {
            if($array[$minIndex] > $array[$j]) {
                $minIndex = $j;
            }
        }
        $temp = $array[$i];
        $array[$i] = $array[$minIndex];
        $array[$minIndex] = $temp;
    }
    return $array;
}



$array = makeArray(1000000);
echo "原始数组:".implode(",",$array)."\r\n";
echo "数组长度为:".count($array)."\r\n";
$a1 = $a2 = $a3 = $a4 = $array;


$startTime = time();
mergeSort($a4,0,count($a4)-1);

echo implode(",",$a4);
$endTime = time();
$diffTime = $endTime-$startTime;
echo "MergeSort:执行时间为:{$diffTime}秒"."\r\n";

$startTime = time();
$newArray = insertSort($a3);
$endTime = time();
$diffTime = $endTime-$startTime;
echo "InsertSort:执行时间为:{$diffTime}秒"."\r\n";

$startTime = time();
$newArray = selectSort($a2);
$endTime = time();
$diffTime = $endTime-$startTime;
echo "SelectSort:执行时间为:{$diffTime}秒"."\r\n";

$startTime = time();
bubbleSort($a1);
$endTime = time();
$diffTime = $endTime-$startTime;
echo "BubleSort:执行时间为:{$diffTime}秒"."\r\n";