Home > php教程 > php手册 > Insertion Sort,insertionsort

Insertion Sort,insertionsort

WBOY
Release: 2016-06-13 09:21:41
Original
1062 people have browsed it

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> ?>
Copy after login

 

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template