找到代码的最佳情况和最差情况下的性能时间

时间:2014-03-31 17:26:24

标签: python

def sorting(seq):
    prev = seq[0]
    conf = True
    for itr in seq:
        if itr < prev:
            conf = False
            break
        prev = itr
    if conf: return seq
    for i in range(len(seq)):
        j = i
        while j>0 and seq[j]<seq[j-1]:
            seq[j],seq[j-1]=seq[j-1],seq[j]
            j = j-1
    return seq

有人可以告诉我如何找到上述代码的最佳案例和最差情况下的演出时间吗?

1 个答案:

答案 0 :(得分:-1)

def sorting(seq):
    prev = seq[0]
    conf = True
    for itr in seq:
        if itr < prev:
            conf = False
            break
        prev = itr
    if conf: return seq
    for i in range(len(seq)):
        j = i
        while j>0 and seq[j]<seq[j-1]:
            seq[j],seq[j-1]=seq[j-1],seq[j]
            j = j-1
    return seq

最好的情况显然是列​​表已经排序 您可以看到一次通过列表(O(n))

最糟糕的情况是列表的顺序相反 这是O(n ^ 2)(我认为至少)