Quick Sort,quicksort_PHP教程

WBOY
發布: 2016-07-13 10:14:41
原創
845 人瀏覽過

Quick Sort,quicksort

<span> 1</span> <?<span>php
</span><span> 2</span> <span>function</span> sortQuick(<span>$a</span>){ <span>#</span><span> a is an array of numbers</span>
<span> 3</span> 
<span> 4</span>     <span>#</span><span> length of a</span>
<span> 5</span>     <span>$m</span> = <span>count</span>(<span>$a</span><span>);
</span><span> 6</span>     
<span> 7</span>     <span>if</span>(<span>$m</span> < 2<span>){
</span><span> 8</span>         <span>return</span> <span>$a</span><span>;
</span><span> 9</span> <span>    }
</span><span>10</span>     
<span>11</span>     <span>$pivot</span> = <span>$a</span>[0<span>];
</span><span>12</span>     
<span>13</span>     <span>//</span><span> declare two partitions</span>
<span>14</span>     <span>$left</span> = <span>$right</span> = <span>array</span><span>();
</span><span>15</span>     
<span>16</span>     <span>for</span>(<span>$i</span> = 1; <span>$i</span> < <span>$m</span>; <span>$i</span>++<span>){
</span><span>17</span>         <span>if</span>(<span>$a</span>[<span>$i</span>] < <span>$pivot</span><span>){
</span><span>18</span>             <span>$left</span>[] = <span>$a</span>[<span>$i</span><span>];
</span><span>19</span> <span>        }
</span><span>20</span>         <span>else</span><span>{
</span><span>21</span>             <span>$right</span>[] = <span>$a</span>[<span>$i</span><span>];
</span><span>22</span> <span>        }
</span><span>23</span> <span>    }
</span><span>24</span>     
<span>25</span>     <span>//</span><span> use recursion to now sort the left and right lists</span>
<span>26</span>     <span>return</span> <span>array_merge</span>(sortQuick(<span>$left</span>), <span>array</span>(<span>$pivot</span>), sortQuick(<span>$right</span><span>));
</span><span>27</span> <span>}
</span><span>28</span> 
<span>29</span> <span>$arr</span> = <span>range</span>(5, 0<span>);
</span><span>30</span> <span>echo</span> <span>implode</span>(', ', sortQuick(<span>$arr</span><span>));
</span><span>31</span> 
<span>32</span> <span>//</span><span> 0, 1, 2, 3, 4, 5</span>
<span>33</span> ?>
登入後複製

 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/908458.htmlTechArticleQuick Sort,quicksort 1 ? php 2 function sortQuick( $a ){ # a is an array of numbers 3 4 # length of a 5 $m = count ( $a ); 6 7 if ( $m 2 ){ 8 return $a ; 9 } 10 11 $pivot = $a [0...
相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板