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

Quick Sort,quicksort

WBOY
发布: 2016-06-13 09:21:42
原创
784 人浏览过

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> ?>
登录后复制

 

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门推荐
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板