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
有人可以告诉我如何找到上述代码的最佳案例和最差情况下的演出时间吗?
答案 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)(我认为至少)