/**
* PHP four basic sorting algorithm running time comparison
* @authors Jesse (jesse152@163.com)
* @date 2016-08-11 07:12:14
*/
Bubble Sort Method
function Bubblesort ($array) {
$temp = 0;
for ($i = 0; $i < count ($array)-1; $i + +) {
for ($j = 0; $j < count ($array)-1-$i; $j + +) {
if ($array [$j] > $array [$j +1]) {//From small to large arrangement
$temp = $array [$j];
$array [$j] = $array [$j +1];
$array [$j +1] = $temp;
}
}
}
}
Select a Sort method
function Selectsort ($array) {
$temp = 0;
for ($i = 0; $i < count ($array)-1; $i + +) {
$minVal = $array [$i]; Assuming $i is the minimum value
$minValIndex = $i;
for ($j = $i +1; $j < count ($array); $j + +) {
if ($minVal > $array [$j]) {//From small to large arrangement
$minVal = $array [$j]; Find the minimum value
$minValIndex = $j;
}
}
$temp = $array [$i];
$array [$i] = $array [$minValIndex];
$array [$minValIndex] = $temp;
}
}
Insert Sort method
function Insertsort ($array) {//Small to large arrangement
First default $array[0], already ordered, is ordered table
for ($i = 1; $i < count ($array); $i + +) {
$insertVal = $array [$i]; $insertVal is the number of inserts to be inserted
$insertIndex = $i-1; Subscript for the number of comparisons in an ordered table
while ($insertIndex >= 0 && $insertVal < $array [$insertIndex]) {
$array [$insertIndex + 1] = $array [$insertIndex]; Move the array backward
$insertIndex--; Move the subscript forward to compare it to the previous one
}
if ($insertIndex + 1!== $i) {
$array [$insertIndex + 1] = $insertVal;
}
}
}
Quick Sort Method
function QuickSort ($array) {
if (!isset ($array [1]))
return $array;
$mid = $array [0]; Gets a keyword for segmentation, typically the first element
$leftArray = Array ();
$rightArray = Array ();
foreach ($array as $v) {
if ($v > $mid)
$rightArray [] = $v; Put the number larger than the $mid into an array.
if ($v < $mid)
$leftArray [] = $v; Put a number smaller than $mid into another array.
}
$leftArray = QuickSort ($leftArray); To split the smaller array again
$leftArray [] = $mid; Add the split element to the back of the small array and don't forget it.
$rightArray = QuickSort ($rightArray); To split the larger array again
Return Array_merge ($leftArray, $rightArray); Combination of two results
}
$a = Array_rand (range (1,3000), 1600); Generates a random array of 1600 elements
Shuffle ($a); To disrupt the order of an array
$t 1 = microtime (true);
Bubblesort ($a); Bubble sort
$t 2 = Microtime (true);
echo "bubble sort:". (($t 2-$t 1) *1000). ' Ms '. ' \ n ";
$t 3 = Microtime (true);
Selectsort ($a); Select sort
$t 4 = Microtime (true);
echo "Select sort When:". (($t 4-$t 3) *1000). ' Ms '. ' \ n ";
$t 5 = Microtime (true);
Insertsort ($a); Insert Sort
$t 6 = Microtime (true);
echo "Insert sort when:". (($t 6-$t 5) *1000). ' Ms '. ' \ n ";
$t 7 = Microtime (true);
QuickSort ($a); Quick Sort
$t 8 = Microtime (true);
echo "Quick sort when:". (($t 8-$t 7) *1000). ' Ms ';