冒泡排序
Posted nr-zhang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了冒泡排序相关的知识,希望对你有一定的参考价值。
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)
以上是关于冒泡排序的主要内容,如果未能解决你的问题,请参考以下文章