首页 > php基础 > 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>当前元素:<?php
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"><?php
    echo $num; ?> </td>
<td><?php
    echo implode(" ", $a); ?></td>
</tr><?php
    $num;
} while (nextpermu($a));
?>
</table>
</body>
</html>


教程网址:http://www.phprm.com/base/f285c7262bb112b2d9670ed2d23c97f9.html

欢迎收藏∩_∩但请保留本文链接。

标签:none

发表留言