Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 这个排序函数的算法复杂度是多少?_Python_Sorting_Complexity Theory - Fatal编程技术网

Python 这个排序函数的算法复杂度是多少?

Python 这个排序函数的算法复杂度是多少?,python,sorting,complexity-theory,Python,Sorting,Complexity Theory,我在玩乐高积木的时候设计了下面的排序算法,基于这样一个想法:总是把较小的积木堆在较大的积木上,直到你遇到一个积木两端都不适合的积木 我最初的印象是它最好的行为是O(n),最坏的行为是O(n^2),因为它类似于串排序,但我在大学里做算法分析已经很久了,我不知道它的平均行为是什么。看起来它应该比strand sort的平均O(n^2)好,但我不知道如何证明它或它是什么 我的实现使用一个链表来允许在两端插入,但deque也可以工作。以下是为了方便描述的Python代码,但是C++版本更有效。 impo

我在玩乐高积木的时候设计了下面的排序算法,基于这样一个想法:总是把较小的积木堆在较大的积木上,直到你遇到一个积木两端都不适合的积木

我最初的印象是它最好的行为是O(n),最坏的行为是O(n^2),因为它类似于串排序,但我在大学里做算法分析已经很久了,我不知道它的平均行为是什么。看起来它应该比strand sort的平均O(n^2)好,但我不知道如何证明它或它是什么

我的实现使用一个链表来允许在两端插入,但deque也可以工作。以下是为了方便描述的Python代码,但是C++版本更有效。
import math

def merge(x, y):
    output = []
    xp = 0
    yp = 0
    if len(y) == 0 or len(x) == 0 or y[0] > x[-1]:
        return x + y
    elif x[0] > y[-1]:
        return y + x
    while xp < len(x) and yp < len(y):
        if x[xp] < y[yp]:
            output.append(x[xp])
            xp = xp + 1
        else:
            output.append(y[yp])
            yp = yp + 1
    if xp < len(x):
        output = output + x[xp:]
    elif yp < len(y):
        output = output + y[yp:]
    return output

def treeMerge(heads, accum):
    currHead = 0
    while heads[currHead] is not None:
        accum = merge(heads[currHead], accum)
        heads[currHead] = None
        currHead = currHead + 1
    heads[currHead] = accum
    return heads

def legoSort(input):
    heads = [None] * int(math.log(len(input), 2) + 1)
    accum = []
    for i in input:
        # can be <= for speed at the cost of sort stability
        if len(accum) == 0 or i < accum[0]: 
            accum.insert(0,i)
        elif i >= accum[-1]:
            accum.append(i)
        else:
            heads = treeMerge(heads, accum)
            accum = [i]
    for i in heads:
        if i is not None:
            accum = merge(accum, i)
    return accum
导入数学
def合并(x,y):
输出=[]
xp=0
yp=0
如果len(y)==0或len(x)==0或y[0]>x[-1]:
返回x+y
elif x[0]>y[-1]:
返回y+x
当xp
研究用未知语言编写的未知代码相当枯燥。您最好在分析结束时在这里找到它。

看起来您得到了类似于timsort或自然合并的东西。

它是Python。:/这并不是一种未知的语言。同意,尽管投票结果是上升的,因为这绝对是合并排序的一种变体,而且他所指的变体似乎就是你可能正在做的事情。他可能也在攻击你,因为python使用了Timsort,这涉及到合并排序。是的,我知道这就是python。我的意思是我不知道。这对我来说很难将程序转换成算法,我觉得这不像是合并排序(当然,除了合并列表);它没有任何递归行为。我看到了与蒂姆索特的相似之处;谢谢你的提示。最大的区别在于,该算法的双亲性允许提取反向运行(或者更复杂的是,像5 6 4 7 3 8 2 9 1这样的运行被当作一个运行来处理),但奔腾过程在概念上看起来确实相似。虽然没有递归,但似乎相似。如果我错了,也许我应该删除答案。是的,一种使用向前和向后运行的自然合并。