<?php
/*
* 希尔排序
*/
set_time_limit(0);
header("Content-Type:text/html;charset=utf-8");
$dataLen=20001;
$data=array();
$i=0;
//make data
srand(time());
for($i=0; $i < $dataLen; $i++){
$data[$i] = rand();
}
//sort
$time1=explode(' ',microtime());
ShellSort($data, $dataLen);
$time2=explode(' ',microtime());
echo '耗时:'. (($time2[1]-$time1[1])+($time2[0]-$time1[0])).'<br />';
//输出结果
for ( $i = 0; $i < $dataLen; $i++){
echo $data[$i] ."\t";
}
echo '<br />消耗内存:';
echo memory_get_peak_usage() / (1024*1024) + memory_get_usage() / (1024*1024);
echo 'M';
function ShellSort(&$data, $dataLen) //希尔排序
{
$count = 0;
$ShellCount = 0;
$d = $dataLen; //一般增量设置为数组元素个数,不断除以2以取小
do
{
$d = intval($d / 2);
$ShellCount = ShellPass($data, $d, $dataLen);
$count += $ShellCount;
} while ($d > 1);
echo '<br />比较次数:'.$count .'<br />';
}
//一趟增量为d的希尔插入排序
function ShellPass(&$data, $d, $dataLen)
{
$temp;
$k = 0;
$i = 0;
$j = 0;
for ($i = $d; $i < $dataLen; $i+=$d)
{
if ($data[$i] < $data[$i - $d])
{
$temp = $data[$i];
$j = $i - $d;
do
{
$data[$j + $d] = $data[$j];
$j = $j - $d;
$k++;
} while ($j >-1 && $temp < $data[$j]);
$data[$j + $d] = $temp;
}
$k++;
}
return $k;
}