Insertion Sort,insertionsort_PHP教程

WBOY
发布: 2016-07-13 10:14:40
原创
865 人浏览过

Insertion Sort,insertionsort

insertion sort wikipedia

<span> 1</span> <?<span>php
</span><span> 2</span> <span>function</span> swap(&<span>$a</span>, &<span>$b</span><span>){
</span><span> 3</span>     <span>$c</span> = <span>$a</span><span>;
</span><span> 4</span>     <span>$a</span> = <span>$b</span><span>;
</span><span> 5</span>     <span>$b</span> = <span>$c</span><span>;
</span><span> 6</span> <span>}
</span><span> 7</span> 
<span> 8</span> <span>#</span><span> insertion sort</span>
<span> 9</span> <span>#</span><span> ascend</span>
<span>10</span> <span>function</span> sortInsertion(&<span>$a</span>){ <span>#</span><span> a is an array of numbers</span>
<span>11</span> 
<span>12</span>     <span>#</span><span> length of a</span>
<span>13</span>     <span>$m</span> = <span>count</span>(<span>$a</span><span>);
</span><span>14</span> 
<span>15</span>     <span>if</span>(<span>$m</span> < 2<span>){
</span><span>16</span>         <span>return</span><span>;
</span><span>17</span> <span>    }
</span><span>18</span> 
<span>19</span>     <span>#</span><span> for m numbers, we have m-1 numbers to insert</span>
<span>20</span>     <span>for</span>(<span>$i</span>=1; <span>$i</span><=<span>$m</span>-1; <span>$i</span>++<span>){
</span><span>21</span>         <span>for</span>(<span>$j</span>=<span>$i</span>; <span>$j</span>>0; <span>$j</span>--<span>){
</span><span>22</span>             <span>if</span>(<span>$a</span>[<span>$j</span>] < <span>$a</span>[<span>$j</span>-1<span>]){
</span><span>23</span>                 swap(<span>$a</span>[<span>$j</span>], <span>$a</span>[<span>$j</span>-1<span>]);
</span><span>24</span> <span>            }
</span><span>25</span> <span>        }
</span><span>26</span> <span>    }
</span><span>27</span> 
<span>28</span>     <span>return</span><span>;
</span><span>29</span> <span>}
</span><span>30</span> 
<span>31</span> <span>$arr</span> = <span>range</span>(5, 0<span>);
</span><span>32</span> sortInsertion(<span>$arr</span><span>);
</span><span>33</span> <span>echo</span> <span>implode</span>(', ', <span>$arr</span><span>);
</span><span>34</span> 
<span>35</span> <span>//</span><span> 0, 1, 2, 3, 4, 5</span>
<span>36</span> ?>
登录后复制

 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/908459.htmlTechArticleInsertion Sort,insertionsort 1 ? php 2 function swap( $a , $b ){ 3 $c = $a ; 4 $a = $b ; 5 $b = $c ; 6 } 7 8 # insertion sort 9 # ascend 10 function sortInsertion( $a ){ # a is a...
相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板