当前位置:编程学习 > php >>

PHP实现的字典序排列算法

<?php
if ($_POST["perdata"] == "")
{
$_POST["perdata"] = "1 2 3 4";
}
$data = chop (trim ($_POST["perdata"]));
$a = explode (" ", $data);
sort ($a);
$data = implode (" ", $a);
?>
<?php
function nextpermu (&$c)
{
$s = sizeof ($c);
$i = $s - 1;
while ($i > 0)
{
if ($c[$i] > $c[$i-1])
{
$j = $s-1;
while ($c[$j] <= $c[$i-1])
$j--;
$t = $c[$i-1];
$c[$i-1] = $c[$j];
$c[$j] = $t;
//echo $i."-".$j."<br>";
for ($j=$s-1; $i < $j; $i , $j--)
{
$t = $c[$i];
$c[$i] = $c[$j];
$c[$j] = $t;
}
return true;
}
$i--;
}
for ($i = 0, $j=$s-1; $i < $j; $i , $j--)
{
$t = $c[$i];
$c[$i] = $c[$j];
$c[$j] = $t;
}
return false;
}
?>
<html>
<head>
<title>排列-字典法</title></head><body>
<form action="permutation.php" method="post">
<table>
<tr>
<td><input type="text" name="perdata"></td>
<td><input type="submit" value="排列"></td>
</tr>
</table>
</form>
<p>当前元素:<? echo $data; ?></p> <table width="60%">
<tr>
<th width="50" bgcolor="yellow">序号</th>
<th bgcolor="EEEEFF">排列</th>
</tr><?php $num = 1; do {?> <tr>
<td align="center"><? echo $num; ?> </td>
<td><? echo implode (" ", $a); ?></td>
</tr><?php
$num ;
}
while (nextpermu ($a));
?>
</table>
</body>
</html>

补充:Php教程,Php基础 
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,