- <?php
- $array = array(13,15,6,10,20,6,3,19);
- $count = count($array);
- $n = $e = 0;
- for($i = 1; $i < $count; $i++)
- {
- $tmp = $array[$i];
- $j = $i;
- while($array[$j-1] > $tmp){
- $n++;
- $e++;
- $array[$j] = $array[$j-1];
- $j--;
- }
- $array[$j] = $tmp;
- }
- print_r($array);
- echo "共循环{$n}次,共执行{$e}次数据交换";
- ?>
执行结果为:
- Array ( [0] => 3 [1] => 6 [2] => 6 [3] => 10 [4] => 13 [5] => 15 [6] => 19 [7] => 20 )
- 共循环15次,共执行15次数据交换