冒泡排序-Python与PHP实现版
Python实现
import random a=[random.randint(1,999) for x in range(0,33)] # 冒泡排序,python中数组是按引用传递的,会直接在原数组上修改 def bubbleSort(array): flag = True i=0 while i<len(array) and flag: j=len(array)-1
flag = False while j>i: if array[j-1] > array[j]: array[j-1],array[j] = array[j],array[j-1] flag = True j=j-1 i = i + 1 bubbleSort(a) print(a)
PHP实现
<?php $a = []; for($i=0;$i<36;$i++){ array_push($a,mt_rand(1,999)); } shuffle($a); function bubbleSort(&$a){ $flag = true; for($i = 0;$i<count($a) && $flag;$i++){ $flag = false; for($j = count($a)-1;$j>$i;$j--){ if($a[$j-1] > $a[$j]){ $a[$j] += $a[$j-1]; $a[$j-1] = $a[$j]-$a[$j-1]; $a[$j] -= $a[$j-1]; $flag = true; } } } } bubbleSort($a);