Created
October 19, 2012 07:34
-
-
Save zubinJiang/3916745 to your computer and use it in GitHub Desktop.
字典排序算法实现全排列
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* 打印数组 | |
* | |
* @param int $num 数组内的元素个数 | |
*/ | |
function printArr($num){ | |
global $array;//全局数组 | |
for($i=0;$i<$num;$i++) | |
echo $array[$i]; | |
echo "<br>"; | |
} | |
/** | |
* 交换值 | |
* | |
* @param string $a | |
* @param string $b | |
*/ | |
function swap(&$a,&$b){ | |
$temp= $a; | |
$a = $b; | |
$b = $temp; | |
} | |
/** | |
* 将第$m个和$n个之间的数据倒置排序 | |
* | |
* @param int $m 数组中的位序$m | |
* @param int $n 数组中的位序$n | |
*/ | |
function convert($m,$n){ | |
global $array;//全局数组 | |
for ($i=$m,$j=$n;$j>$i;$i++,$j--) | |
swap($array[$i],$array[$j]); | |
} | |
/** | |
* 对1~n进行全排列 | |
* | |
* @param int $num 元素的总个数 | |
* @return 1 | |
*/ | |
function dictionary_sort($num){ | |
global $array;//全局数组 | |
if ($num==1){ | |
echo "1<br>"; | |
return 1; | |
} | |
while (1){ | |
printArr($num); //打印数组 | |
for ($i=$num-2;$i>=0;$i--){ //步骤1:从后向前找,找到第一个比下一个元素还小的地方,记下位置,标注$i | |
if ($array[$i]<$array[$i+1])break;//得到$i | |
if ($i==0)return 1; //函数出口 | |
} | |
for ($j=$num-1;$j>$i;$j--){ //步骤2:从后向前找,找到第一个比$i元素大的元素,记下位置,标注为$j | |
if ($array[$j]>$array[$i])break; | |
} | |
swap($array[$i],$array[$j]);//步骤3:交换$array[$i]和$array[$j]的数据 | |
convert($i+1,$num-1); //步骤4: 将$i个元素右边的序列逆序 | |
} | |
} | |
$array=array(); | |
$num=5; | |
for ($i=0;$i<$num;$i++){ | |
$array[$i]=$i+1; | |
} | |
dictionary_sort($num); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment