首页 > 学院 > 逻辑算法 > 正文

PHP 实现的字典序排列算法

2024-09-08 23:18:44
字体:
来源:转载
供稿:网友

感谢 bird 告诉我 $_post[] 的用法。代码如下:

<?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>

商业源码热门下载www.html.org.cn

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表