Heim  >  Artikel  >  php教程  >  Insertion Sort,insertionsort

Insertion Sort,insertionsort

WBOY
WBOYOriginal
2016-06-13 09:21:411022Durchsuche

Insertion Sort,insertionsort

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

 

Stellungnahme:
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