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);