php版:
<?php $arr = [1,3,8,2,4,9,7]; print_r(bubbleSort($arr)); function bubbleSort($arr){ $flag = false; $len = count($arr); $count_swap = $count_loop = 0; for($i = 1;$i < $len;$i++){ for($k = 0;$k < $len - $i;$k++){ $count_loop += 1; if($arr[$k] > $arr[$k + 1]){ $tmp = $arr[$k + 1]; $arr[$k + 1] = $arr[$k]; $arr[$k] = $tmp; $flag = true; $count_swap += 1; } } //如果2层循环没有交换的话,则退出,减少循环次数 if(!$flag){ break; } } echo '交换次数:' . $count_swap . '<br />'; echo '循环次数:' . $count_loop . '<br />'; return $arr; }
python版:
num_list = [ [1,9,8,5,6,7,4,3,2], [1,2,3,4,5,6,7,8,9], [1,2,3,4,8,6,7,9,5] ] nums = num_list[2]; print(nums); length = len(nums) count_swap = 0 count = 0 flag = False for i in range(length) : for j in range(length - i - 1) : count += 1 print(j,j+1) if nums[j] > nums[j + 1] : tmp = nums[j] nums[j] = nums[j + 1] nums[j + 1] = tmp count_swap += 1 flag = True print("swap") print("") if not flag : break print(nums,count_swap,count)