Heim > php教程 > php手册 > Quick Sort,quicksort

Quick Sort,quicksort

WBOY
Freigeben: 2016-06-13 09:21:42
Original
785 Leute haben es durchsucht

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> ?>
Nach dem Login kopieren

 

Verwandte Etiketten:
Quelle:php.cn
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Empfehlungen
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage