好久沒有來練習的自己的演算法技能了以至於很多基本的演算法都快忘記了。
以前用c寫的演算法也不多。那麼今天就開始吧!以後堅持每天晚上寫一些簡單的演算法,堅持練習!
第一篇冒泡排序
<code>冒泡排序是最简单基础的排序,但是由于好久没写代码了,一开始写下去还是不流畅。。。罪过罪过 冒泡排序原理,每次从待排序的序列里面选出一个最大或者最小的元素放到已经排好序的序列后面。知道最后待排序的序列为无; 以下是用php实现的冒泡排序, 注意以下几点: 1)当带排序的数组为无的时候直接退出,避免出错。 2) 尼玛数组都忘记怎么写了,我真是该死。 </code>
<code><span><?php</span><span><span>function</span><span>bubblesort</span><span>(<span>$array</span>)</span>{</span><span>$count</span> = count(<span>$array</span>); <span>if</span>(<span>$count</span> == <span>0</span>){ <span>return</span><span>$array</span>; } <span>echo</span><span>$count</span>; <span>for</span>(<span>$i</span> = <span>0</span>; <span>$i</span> < <span>$count</span>; <span>$i</span>++){ <span>for</span>(<span>$j</span> = <span>$count</span> - <span>1</span>; <span>$j</span> > <span>$i</span>; <span>$j</span>--){ <span>if</span>(<span>$array</span>[<span>$j</span>] < <span>$array</span>[<span>$j</span> - <span>1</span>]){ <span>$temp</span> = <span>$array</span>[<span>$j</span>]; <span>$array</span>[<span>$j</span>] = <span>$array</span>[<span>$j</span>-<span>1</span>]; <span>$array</span>[<span>$j</span>-<span>1</span>] = <span>$temp</span>; } } } <span>return</span><span>$array</span>; } <span>$array</span> = <span>array</span>(<span>1</span>,<span>45</span>,<span>2</span>,<span>4</span>,<span>54</span>,<span>2</span>,<span>45</span>,<span>6</span>); print_r(bubblesort(<span>$array</span>)); <span>?></span></code>
第二篇快速排序(quicksort)
<code> 原理: 快速排序是对冒泡排序的一种改进,基本思想是通过一趟排序将要排序的数据分成两部分,其中的一部 </code>
分比另一部分所有數據都小,然後按此方法對著兩部分的數據分別進行快速排序,整個排序過程可以遞歸進行,以此
達到資料變成有序序列。
<code><span><span><span><?php function quickSort<span>(<span>$arr</span>)</span>{ <span>$count</span> = count<span>(<span>$arr</span>)</span>; if<span>(<span>$count</span> <= <span>1</span>)</span>{ return <span>$arr</span>; } <span>$key</span> = <span>$arr</span>[<span>0</span>]; <span>$left_arr</span> = array<span>()</span>; <span>$right_arr</span> = array<span>()</span>; for<span>(<span>$i</span> = <span>1</span>; <span>$i</span> < <span>$count</span>; <span>$i</span>++)</span>{ if<span>(<span>$arr</span>[<span>$i</span>] <= <span>$key</span>)</span>{ <span>$left_arr</span>[] = <span>$arr</span>[<span>$i</span>]; }else{ <span>$right_arr</span>[] = <span>$arr</span>[<span>$i</span>]; } } <span>$left_arr</span> = quickSort<span>(<span>$left_arr</span>)</span>; <span>$right_arr</span> = quickSort<span>(<span>$right_arr</span>)</span>; return array_merge<span>(<span>$left_arr</span>,array<span>(<span>$key</span>)</span>,<span>$right_arr</span>)</span>; } <span>$arr</span> = array<span>(<span>23</span>,<span>4</span>,<span>6</span>,<span>46</span>,<span>34</span>,<span>23</span>,<span>6234</span>,<span>34</span>,<span>12</span>,<span>34</span>)</span>; print_r<span>(quickSort<span>(<span>$arr</span>)</span>)</span>;</span></span></span></code>
?>
版權聲明:本文為部落客原創文章,未經部落客允許不得轉載。
以上就介紹了php實作排序演算法(一) 冒泡排序 快速排序,包含了方面的內容,希望對PHP教程有興趣的朋友有所幫助。