简体   繁体   English

Python 3:优化的冒泡排序

[英]Python 3: Optimised Bubble Sort

please help. 请帮忙。 I need to optimize my Bubble Sort algorithm in order to get less total comparisons than the non-optimised bubbleSort. 我需要优化我的冒泡排序算法,以便比非优化的bubbleSort获得更少的总比较。 I managed to create just the 'Normal Bubble sort (only travels from left to right): 我设法创建了'正常冒泡排序(仅从左到右):

def bubbleSort(values):
    n = len(values) - 1
    swap = True
    ncomp = 0 # My total comparisons counter
    while swap:
        swap = False
        for i in range(n): # i = 0, 1, 2, ..., n-1
            ncomp += 1
            if values[i] > values[i+1]:
                temp = values[i]
                values[i] = values[i+1]
                values[i+1] =  temp
                swap = True
    return values, ncomp

So basically i dont know how to create an 'optimised bubbleSort', a bubbleSortPlus function in which bubbles travel in both directions: from left to right, immediately followed by a travel from right to left. 所以基本上我不知道如何创建一个'优化的bubbleSort',一个bubbleSortPlus函数,其中气泡在两个方向上传播:从左到右,紧接着是从右到左的旅行。 In theory, in each pass the travel of the bubbles should be shortened (saving in a variable the position of the last swap in a travel, and make the next travel start at that position. I tried so hard but i'm just a python newbie, please help. 理论上,在每次传球中,应该缩短气泡的行程(在变量中保存行程中最后一次交换的位置,并使下一次行程从该位置开始。我努力但我只是一条蟒蛇新手,请帮忙。

I guess it has been optimized... The naive Bubble sort does not include the swap flag. 我猜它已被优化了...天真的冒泡排序不包括swap标志。 So it will not return until finish all O(n^2) comparisons in any cases. 因此,在任何情况下完成所有O(n ^ 2)比较之前它不会返回。 But with swap flag, the number of comparison will be almost linear if the input sequence has been "almost sorted". 但是使用swap标志,如果输入序列已经“几乎排序”,则比较的数量几乎是线性的。

Here's some skeleton code that shows how to scan the array forwards and backwards, while shrinking the list on each iteration. 这是一些框架代码,显示如何向前和向后扫描数组,同时缩小每次迭代的列表。

values = 100,101,102,103,104,105

start = 0
stop = len(values)-1

while stop > start:
    for i in range(start, stop):
        print i, "compare", values[i], "with", values[i+1]
    print "moved a large value to index", stop
    print

    stop = stop - 1
    if stop == start:
        break

    for i in range(stop, start, -1):
        print i, "compare", values[i], "with", values[i-1]
    print "moved a small value to index", start
    print

    start = start + 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM