- <?php
- $array = array(13,15,6,10,20,6,3,19);
- $count = count($array);
- $n = $e = 0;
- for($i = 0; $i < $count; $i++)
- {
- for($j = $i + 1; $j < $count; $j++)
- {
- $n++;
- if($array[$j] < $array[$i]){
- $e++;
- $tmp = $array[$i];
- $array[$i] = $array[$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 )
- 共循环28次,共执行14次数据交换