php数据结构之简单选择排序

来源:互联网 发布:ubuntu下chmod 编辑:程序博客网 时间:2024/06/05 20:22
    <?php
  1.     $array = array(13,15,6,10,20,6,3,19);
  2.     $count = count($array);
  3.     $n = $e = 0;
  4.     for($i = 1; $i < $count; $i++)
  5.     {
  6.         //find the min item from $i to last
  7.         $min_index = $i;
  8.         for($j = $i+1; $j < $count; $j++)
  9.         {
  10.             $n++;
  11.             if($array[$j] < $array[$min_index]) $min_index = $j;
  12.         }
  13.       
  14.         if($array[$min_index] < $array[$i-1])
  15.         {
  16.             $e++;
  17.         $tmp = $array[$i-1];
  18.         $array[$i-1] = $array[$min_index];
  19.         $array[$min_index] = $tmp;
  20.         }
  21.     }
  22.     print_r($array);
  23.     echo "共循环{$n}次,共执行{$e}次数据交换";
  24. ?>




执行结果为:

    Array ( [0] => 3 [1] => 6 [2] => 6 [3] => 10 [4] => 13 [5] => 15 [6] => 19 [7] => 20 )
  1. 共循环21次,共执行5次数据交换