您的位置:首页 > 编程语言 > Python开发

冒泡排序的三种实现方法-----python

2013-10-29 15:10 483 查看
def bubble(l):
    print l
    for index in range(len(l) - 1, 0 , -1):
        for two_index in range(index):
            if l[two_index] > l[two_index + 1]:
                l[two_index], l[two_index + 1] = l[two_index + 1], l[two_index]
    print l

l = [10, 20, 40, 50, 30, 60]
bubble(l)

方法1:就是依次遍历,把最小的数字沉到数组的最后

def bubble_improve(l):
    print l
    flag = 1
    for index in range(len(l) - 1, 0 , -1):
        if flag:
            flag = 0
            for two_index in range(index):
                if l[two_index] > l[two_index + 1]:
                    l[two_index], l[two_index + 1] = l[two_index + 1], l[two_index]
                    flag = 1
        else:
            break
    print l
    
l = [10, 20, 40, 50, 30, 60]
bubble_improve(l)

方法2:就是加一个标志用来判断一次遍历的时候,还是否有交换,如果没有交换就说明已经排列好了,则退出;否则继续进行遍历。

def bubble_improve2(l):
    print l
    flag = 1
    for index in range(len(l) - 1, 0 , -1):
        if flag:
            flag = 0
            for two_index in range(index):
                flag_in = 0
                if l[two_index] > l[two_index + 1]:
                    l[two_index], l[two_index + 1] = l[two_index + 1], l[two_index]
                    flag = 1
                    flag_in = 1
                if flag_in:
                    if two_index - 1 > 0:
                        if l[two_index - 1] > l[two_index]:
                            l[two_index - 1], l[two_index] = l[two_index], l[two_index - 1]
        else:
            break
    print l
    
l = [10, 20, 40, 50, 30, 60]
bubble_improve2(l)

文法2的变异,在一次移动之后和它之前的坐标相比较,如果符合条件就进行一次移动。

def bubble_improve1(l):
    print l
    flag = len(l) - 1
    while(flag > 0):
        k = flag
        flag = 0
        for j in range(k):
            if l[j] > l[j + 1]:
                l[j], l[j + 1] = l[j + 1], l[j]
                flag = j
    print l
       

l = [10, 20, 40, 50, 30, 60]
bubble_improve1(l)

方法3:也是 记录一个标志,这个标志是进行一次遍历的时候,最后交换的坐标,这样可以确定最后进行交换的位置,后面的就不需要再进行遍历了。

def bubble_improve(l):
    flag = 1
    bottom = 0
    top = len(l) - 1
    while flag:
        flag = 0
        for index in range(bottom, top, 1):
            if l[index] > l[index + 1]:
                l[index], l[index + 1] = l[index + 1], l[index]
                flag = 1
        top = top - 1
        
        for index in range(top, bottom, -1):
            if l[index] < l[index - 1]:
                l[index - 1], l[index] = l[index], l[index - 1]
                flag = 1
        bottom = bottom + 1
    print l
    
l = [10, 20, 40, 50, 30, 60]
bubble_improve(l)

方法四(鸡尾酒排序):思路和方法二的差别是来从头到尾和从尾到头的来回遍历。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: