my_list = [12, 5, 13, 8, 9, 65]
def bubble(bad_list):
length = len(bad_list) - 2
sorted = False
while not sorted:
sorted = True
for i in range(length):
if bad_list[i] > bad_list[i+1]:
sorted = False
bad_list[i], bad_list[i+1] = bad_list[i+1], bad_list[i]
bubble(my_list)
print my_list
算法:
初始列表尚未排序,所以sorted = False。
当进入while循环后,假设列表已经排好序。然后从头到尾遍历列表,如果发现有两个相邻元素顺序错位,则把sorted置回False,这样的话sorted只有在没有元素顺序错位时保持True。
以上是用python写的,可以很方便的写一个PHP版本的:
$myList = array(12, 5, 13, 8, 9, 65);
function bubble($list)
{
$length = count($list) - 2;
$sorted = false;
while(!$sorted)
{
$sorted = true;
foreach(range(0,$length) as $i)
{
if($list[$i] > $list[$i + 1])
{
$sorted = false;
list($list[$i],$list[$i + 1]) = array($list[$i + 1],$list[$i]);
}
}
}
return $list;
}
bubble($myList);
