PHP 選擇排序法

來源:互聯網
上載者:User

標籤:排序

選擇排序法的思路就是再第一次迴圈中,假設第一個數是最小的;然後跟第二個數比較,一直比到最後,找出最小值,然後把最小值跟第一個數的位置互換;再進行下一次迴圈,找出最小值跟第二個位置的數互換;一直迴圈數組的個數減去1次;數組就成了有序的了;

<?php$arr=array(3,1,7,-1);for ($i=0;$i<count($arr)-1;$i++){    $min=$arr[$i];    $mindex=$i;  for ($j=$i+1;$j<count($arr);$j++){    if ($min >$arr[$j]){      $min=$arr[$j];      $mindex=$j;    }}$temp=$arr[$i];$arr[$i]=$arr[$mindex];$arr[$mindex]=$temp;}print_r($arr);?>
[[email protected] html]# php sort2.php Array(    [0] => -1    [1] => 1    [2] => 3    [3] => 7)


本文出自 “每天進步1%” 部落格,請務必保留此出處http://jackyan.blog.51cto.com/2589874/1545939

PHP 選擇排序法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.