Maison > Article > développement back-end > php的一些容易算法程序(冒泡、快速等)
php的一些简单算法程序(冒泡、快速等)
<span style="color: #0000ff;">function</span> buttle_sort(<span style="color: #800080;">$array</span><span style="color: #000000;">) { </span><span style="color: #800080;">$len</span>=<span style="color: #008080;">count</span>(<span style="color: #800080;">$array</span><span style="color: #000000;">); </span><span style="color: #0000ff;">if</span>(<span style="color: #800080;">$len</span>){ <span style="color: #0000ff;">return</span> <span style="color: #800080;">$array</span><span style="color: #000000;">; } </span><span style="color: #0000ff;">for</span>(<span style="color: #800080;">$i</span>=0;<span style="color: #800080;">$i</span>$len;<span style="color: #800080;">$i</span>++<span style="color: #000000;">){ </span><span style="color: #800080;">$flag</span> = <span style="color: #0000ff;">false</span>;<span style="color: #008000;">//</span><span style="color: #008000;">本趟排序开始前,交换标志应为假</span> <span style="color: #0000ff;">for</span>(<span style="color: #800080;">$j</span>=<span style="color: #800080;">$len</span>-1;<span style="color: #800080;">$j</span>><span style="color: #800080;">$i</span>;<span style="color: #800080;">$j</span>--<span style="color: #000000;">){ </span><span style="color: #0000ff;">if</span>(<span style="color: #800080;">$array</span>[<span style="color: #800080;">$j</span>]$array[<span style="color: #800080;">$j</span>-1<span style="color: #000000;">]){ </span><span style="color: #800080;">$tmp</span> = <span style="color: #800080;">$array</span>[<span style="color: #800080;">$j</span><span style="color: #000000;">]; </span><span style="color: #800080;">$array</span>[<span style="color: #800080;">$j</span>] = <span style="color: #800080;">$array</span>[<span style="color: #800080;">$j</span>-1<span style="color: #000000;">]; </span><span style="color: #800080;">$array</span>[<span style="color: #800080;">$j</span>-1] = <span style="color: #800080;">$tmp</span><span style="color: #000000;">; </span><span style="color: #800080;">$flag</span> = <span style="color: #0000ff;">true</span>;<span style="color: #008000;">//</span><span style="color: #008000;">发生了交换,故将交换标志置为真</span><span style="color: #000000;"> } } } </span><span style="color: #0000ff;">if</span>(!<span style="color: #800080;">$flag</span>)<span style="color: #008000;">//</span><span style="color: #008000;">本趟排序未发生交换,提前终止算法</span> <span style="color: #0000ff;">return</span> <span style="color: #800080;">$array</span><span style="color: #000000;">; }</span>
待补充