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

Insertion Sort,insertionsort

WBOY
Lepaskan: 2016-06-13 09:21:41
asal
1064 orang telah melayarinya

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> ?>
Salin selepas log masuk

 

Label berkaitan:
sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Cadangan popular
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan