PHP array Sort: PHP implements various sorts
Last Update:2017-02-28
Source: Internet
Author: User
<?php
/**
* Various sort
* @author Zhaojaingwei
* @since 2011/11/21 16:14
*
*/
$list = Array (3,5,1,2,10,8,15,19,20);
Quick Platoon
Function Fast (& $list, $low, $high) {
if ($high-$low > 5) {
while ($low < $high) {
$key = Excute ($list, $low, $high);
Fast ($list, $low, $key-1);
Fast ($list, $key + 1, $high);//Common recursive implementation
$low = $key + 1;//tail Recursive implementation
}
}else{
Insert ($list);
}
}
Perform a sort on a fast schedule
Function Excute (& $list, $low, $high) {
Swap ($list, $low, ($low + $high)/2);
$temp = $list [$low];
while ($low < $high) {
while ($low < $high && $list [$high] > $temp) {
$high--;
}
$list [$low] = $list [$high];
while ($low < $high && $list [$low] < $temp) {
$low + +;
}
$list [$high] = $list [$low];
}
$list [$low] = $temp;
return $low;
}
Heap Sort
function heap (& $list) {
Buildheap ($list);
for ($i = count ($list)-1; $i > 0; $i-) {
Swap ($list, $i, 0);
Heapfy ($list, 0, $i-1);
}
}
Creating heaps
Function Buildheap (& $list) {
for ($i = (count ($list)-2)/2; $i >= 0; $i-) {
Heapfy ($list, $i, COUNT ($list)-1);
}
}
Maintenance heap
Function Heapfy (& $list, $low, $high) {
$temp = $list [$low];
for ($i = ($low * 2 + 1); $i <= $high; $i = ($i * 2 + 1)) {
if ($i < $high && $list [$i] < $list [$i + 1]) {
$i + +;
}
if ($temp < $list [$i]) {
Swap ($list, $i, $low);
$low = $i;
}else{
Break
}
}
$list [$low] = $temp;
}
Hill sort
function shell (& $list) {
$a = 0;
$code = count ($list)/3 + 1;
while ($code >= 1) {
for ($i = $code; $i < count ($list); $i + +) {
$a + +;
if ($list [$i] < $list [$i-$code]) {
$temp = $list [$i];
$list [$i] = $list [$i-$code];
$j = $i -2* $code;
for (; $j >= 0 && $list [$j] > $temp; $j-= $code) {
$list [$j + $code] = $list [$j];
$a + +;
}
$list [$j + $code] = $temp;
}
}
$code = $code/3;
}
echo $a;
}
Direct Insert Sort
function Insert (& $list) {
$a = 0;
for ($i = 1; $i < count ($list); $i + +) {
$a + +;
if ($list [$i] < $list [$i-1]) {
$temp = $list [$i];
$list [$i] = $list [$i-1];
$j = $i-2;
for (; $list [$j] > $temp; $j-) {
$a + +;
$list [$j + 1] = $list [$j];
}
$list [$j + 1] = $temp;
}
}
echo $a;
}
Simple selection Sort
Function Select (& $list) {
$a = 0;
for ($i = 0; $i < count ($list); $i + +) {
$min = $i;
$a + +;
for ($j = $i + 1; $j < count ($list); $j + +) {
$a + +;
if ($list [$j] < $list [$min]) {
$min = $j;
}
}
if ($min!= $i)
Swap ($list, $i, $min);
}
echo $a;
}
Bubble sort
Function Bubble (& $list) {
$swap = true;
$a = 0;
for ($i = 0; $i < count ($list) && $swap; $i + +) {
$swap = false;
$a + +;
for ($j = count ($list)-2; $j >= $i; $j-) {
$a + +;
if ($list [$j] > $list [$j + 1]) {
$swap = true;
Swap ($list, $j, $j + 1);
}
}
}
echo $a;
}
Move or swap functions
Function Swap (& $list, $i, $j) {
$temp = $list [$i];
$list [$i] = $list [$j];
$list [$j] = $temp;
}
?> This article links http://www.cxybl.com/html/wlbc/Php/20120607/28506.html