$Arr = array(1,5,4,2,7,9,3,6,6); $falg =TRUE; $Arrlen = count($Arr); $CountSum=0;
for ( $i = 0 ; $i <$Arrlen-1; $i++) {
for($j =0; $j<$Arrlen-1-$i; $j++ ) { if($Arr[$j] >$Arr[$j+1]) { //升序 $CountSum++;
/* 用於理解異或 $a = 4; $b = 5; $a = $a^$b ; //4^5 $b = $a^$b; // (4^5)^5 = 4 $a = $a^$b; // (4^5)^4 =5 */
/* 普通冒泡 $temp = $Arr[$j]; $Arr[$j] = $Arr[$j+1]; $Arr[$j+1] = $temp; */ //異或冒泡 位運算直接對二進制位進行操做,效率高 $Arr[$j] = $Arr[$j] ^ $Arr[$j+1]; $Arr[$j+1] = $Arr[$j] ^ $Arr[$j+1]; $Arr[$j] = $Arr[$j] ^ $Arr[$j+1]; $falg = false; } } if ($falg) { break; } } echo '<pre>'; var_dump($Arr); echo '</pre>'; echo $CountSum;