TA的每日心情 | 开心 2016-1-18 12:18 |
---|
签到天数: 117 天 [LV.6]常住居民II
|
冒泡排序算法
<?php
//冒泡排序算法
$arr = array(12,52,14,43,24,58,15,64,24,57,17,56,45);
$count = count($arr);
for($i = $count-1; $i>0; --$i)
{
for($j = 0; $j < $i; ++$j)
{
if($arr[$j] > $arr[$j + 1])
{
$temp = $arr[$j];
$arr[$j] = $arr[$j+1];
$arr[$j+1] = $temp;
}
}
}
print_r($arr);
?>
复制代码
插入排序: <?php
for($i=0; $i<1000; ++$i)
{
$arr[] = mt_rand(1,1000);
}
$count = count($arr);
$start = microtime(true);
for ($i = 1; $i < $count ; ++$i)
{
$temp = $arr[$i];
$j = $i;
while($j > 0 && $arr[$j-1] >= $temp)
{
$arr[$j] = $arr[$j-1];
--$j;
}
$arr[$j] = $temp;
}
?>
复制代码
快速排序: <?php
$start = microtime(true);
function initArr()
{
for($i=0; $i<10; ++$i)
{
$arr[] = mt_rand(1,100);
}
return $arr;
}
function swap(&$arr, $leftptr, $rightptr)
{
$temp = $arr[$leftptr];
$arr[$leftptr] = $arr[$rightptr];
$arr[$rightptr] = $temp;
}
function quickSort()
{
$arr = initArr();
$count = count($arr);
recQuickSort($arr, 0, $count-1);
print_r($arr);
}
function recQuickSort(&$arr, $left, $right)
{
if($right - $left <=0)
return;
else{
$pivot = $arr[$right];
$partition = patitionIt($arr, $left, $right, $pivot);
recQuickSort($arr, $left, $partition-1);
recQuickSort($arr, $partition +1, $right);
}
}
function patitionIt(&$arr, $left, $right, $pivot)
{
$leftptr = $left - 1;
$rightptr = $right;
while (true)
{
while ($arr[++$leftptr] < $pivot)
{
;
}
while ($rightptr > 0 &&
$arr[--$rightptr] > $pivot)
{
}
if($leftptr >= $rightptr)
{
break;
}else
{
swap($arr, $leftptr, $rightptr);
}
}
return $leftptr;
}
quickSort();
$end = microtime(true);
echo $end - $start;
?>
复制代码 |
|