Rumah >pembangunan bahagian belakang >tutorial php >php 冒泡排序
<code><span>/** * 冒泡排序 *<span> @global</span> obj $db *<span> @param</span> array 排序数組 *<span> @param</span> value 按照此字段的大小排序 */</span><span><span>function</span><span>bubble_sort</span><span>(<span>$array</span>, <span>$value</span>)</span> {</span><span>$array</span> = array_values(<span>$array</span>); <span>//将数据键值按照数字重新排序</span><span>$count</span> = count(<span>$array</span>); <span>if</span>(<span>$count</span> 0 || <span>empty</span>(<span>$value</span>)) <span>continue</span>; <span>for</span> (<span>$i</span>=<span>0</span>; <span>$i</span> $count ; <span>$i</span>++) { <span>for</span> (<span>$m</span>=<span>$count</span>-<span>1</span>; <span>$m</span> > <span>$i</span>; <span>$m</span>--) { <span>if</span>(<span>$array</span>[<span>$m</span>][<span>$value</span>] $array[<span>$m</span> -<span>1</span>][<span>$value</span>]){ <span>$tmp</span> = <span>$array</span>[<span>$m</span>]; <span>$array</span>[<span>$m</span>] = <span>$array</span>[<span>$m</span>-<span>1</span>]; <span>$array</span>[<span>$m</span>-<span>1</span>] = <span>$tmp</span>; } } } <span>return</span><span>$array</span>; }</code>
<code><span>$array</span> = <span>array</span>( <span>'5'</span>=><span>array</span>(<span>'a'</span>=><span>'a'</span>,<span>'b'</span>=><span>'b'</span>,<span>'value'</span>=><span>''</span>), <span>'6'</span>=><span>array</span>(<span>'b'</span>=><span>'c'</span>,<span>'d'</span>=><span>'d'</span>,<span>'value'</span>=><span>4</span>), <span>'3'</span>=><span>array</span>(<span>'value'</span>=><span>3</span>), <span>'4'</span>=><span>array</span>(<span>'value'</span>=><span>2</span>) ); <span>$m</span> = bubble_sort(<span>$array</span>, <span>'value'</span>); print_r(<span>$m</span>);</code>
打印输出
Array ( [0] => Array ( [a] => a [b] => b [value] => )
[1] => Array ( [value] => 2 )
[2] => Array ( [value] => 3 )
[3] => Array ( [b] => c [d] => d [value] => 4 ) )
以上就介绍了php 冒泡排序,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。