5-11 3,382 views
方法一 : while 循环
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def bubble(bubbleList):
listLength = len(bubbleList)
while listLength > 0:
for i in range(listLength - 1):
if bubbleList[i] > bubbleList[i+1]:
sum1 = bubbleList[i]
bubbleList[i] = bubbleList[i+1]
bubbleList[i+1] = sum1
listLength -= 1
print bubbleList
if __name__ == '__main__':
bubbleList = [3, 4, 1, 2, 5, 8, 0,0,5,2,4,23]
bubble(bubbleList)
方法二 : 2层for循环
arr = [1,2,65,4,2,23,23,231,65]
def bubblesort(numbers):
for j in range(len(numbers)-1,-1,-1):
for i in range(j):
if numbers[i]>numbers[i+1]:
numbers[i],numbers[i+1] = numbers[i+1],numbers[i]
return numbers
print bubblesort(arr);