Rumah  >  Artikel  >  pembangunan bahagian belakang  >  Quick Sort,quicksort_PHP教程

Quick Sort,quicksort_PHP教程

WBOY
WBOYasal
2016-07-13 10:14:41843semak imbas

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...
Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn