<?php /** * Created by PhpStorm. * User: brady * Date: 2019/8/19 * Time: 14:52 */ function bubble_sort($arr = []) { if(empty($arr) || !is_array($arr)){ return []; } $max = count($arr); $change_count = 0; $total_count = 0; for($i=0;$i<$max-1; $i++){ print_r("<br>第".($i+1)."趟比较开始<br>"); for($j=0;$j<$max-1-$i;$j++){ if($arr[$j] > $arr[$j+1]){ $tmp = $arr[$j]; $arr[$j] = $arr[$j+1]; $arr[$j+1] = $tmp; print_r("<br>"); print_r(join(',',$arr)); $change_count++; } $total_count ++; } } var_dump("一共比较".$change_count); var_dump("总共循环".$total_count); return $arr; } $list = [12,3,4,5,7,2,3,4,55,66,22,11]; echo "<pre>"; print_r("比较前"); print_r(join(',',$list)); $res = bubble_sort($list); print_r("比较后"); print_r(join(',',$res));
python
#coding=utf-8 #冒泡排序 def bubble_sort(input_list): if len(input_list) <= 0: return [] else: for i in range(len(input_list)-1): print('第',i+1,'趟循环 ') for j in range(len(input_list)-1-i): if input_list[j] > input_list[j+1]: input_list[j],input_list[j+1] = input_list[j+1],input_list[j] print("第",j,'次排序后结果',input_list,' ') if __name__ == '__main__': input_list = [4,2,3,7,8,1] print('排序前:',input_list) sorted_list = bubble_sort(input_list) print('排序后:',sorted_list)
https://www.cnblogs.com/jingmoxukong/p/4302718.html
https://cuijiahua.com/blog/2017/12/algorithm_1.html