首頁 >php教程 >php手册 >Quick Sort,quicksort

Quick Sort,quicksort

WBOY
WBOY原創
2016-06-13 09:21:42782瀏覽

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> ?>

 

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn