我创建了两个函数,将整数从最小值排序到最大值,然后再排序到低值。这种类型存在吗?总之,我创建了以下两个排序函数,它们产生相同的输出。我在想这两种方法中哪一种效率最高?有什么改进吗?你知道吗
sortMiddleMax1
sortMiddleMax2
我试着让第二个比第一个更有效率。我没有在内存中创建一个新的列表,而是附加到末尾,而不是将整个列表向右推。我的假设正确吗?你知道吗
功能
def sortMiddleMax1(aList=None, verbose=False):
if aList == None or len(aList) < 2:
return aList
else:
sList = sorted(x, key=None, reverse=True)
if verbose: print sList
index = 1
while index < len(sList):
tmp = sList[index]
del sList[index]
sList.insert(0, tmp)
index+=2
if verbose: print sList
return sList
def sortMiddleMax2(aList=None, verbose=False):
if aList == None or len(aList) < 2:
return aList
else:
aList.sort()
if verbose: print aList
index = len(aList)-1
while index > 0:
tmp = aList[index]
del aList[index]
aList.append(tmp)
index-=2
if verbose: print aList
return aList
Main
x = [1,4,6,8,3,5,7,1,5,8,3,9,2,8]
print '############# sortMiddleMax1 #############'
x1 = sortMiddleMax1(x, True)
print '############# sortMiddleMax2 #############'
x2 = sortMiddleMax2(x, True)
输出
############# sortMiddleMax1 #############
[9, 8, 8, 8, 7, 6, 5, 5, 4, 3, 3, 2, 1, 1]
[8, 9, 8, 8, 7, 6, 5, 5, 4, 3, 3, 2, 1, 1]
[8, 8, 9, 8, 7, 6, 5, 5, 4, 3, 3, 2, 1, 1]
[6, 8, 8, 9, 8, 7, 5, 5, 4, 3, 3, 2, 1, 1]
[5, 6, 8, 8, 9, 8, 7, 5, 4, 3, 3, 2, 1, 1]
[3, 5, 6, 8, 8, 9, 8, 7, 5, 4, 3, 2, 1, 1]
[2, 3, 5, 6, 8, 8, 9, 8, 7, 5, 4, 3, 1, 1]
[1, 2, 3, 5, 6, 8, 8, 9, 8, 7, 5, 4, 3, 1]
############# sortMiddleMax2 #############
[1, 1, 2, 3, 3, 4, 5, 5, 6, 7, 8, 8, 8, 9]
[1, 1, 2, 3, 3, 4, 5, 5, 6, 7, 8, 8, 8, 9]
[1, 1, 2, 3, 3, 4, 5, 5, 6, 7, 8, 8, 9, 8]
[1, 1, 2, 3, 3, 4, 5, 5, 6, 8, 8, 9, 8, 7]
[1, 1, 2, 3, 3, 4, 5, 6, 8, 8, 9, 8, 7, 5]
[1, 1, 2, 3, 3, 5, 6, 8, 8, 9, 8, 7, 5, 4]
[1, 1, 2, 3, 5, 6, 8, 8, 9, 8, 7, 5, 4, 3]
[1, 2, 3, 5, 6, 8, 8, 9, 8, 7, 5, 4, 3, 1]
可以使用Python的扩展切片。
[::2]
意味着每一个元素都要执行一次。[::-2]
意味着从末尾开始每一个元素都向后工作。这里,对于偶数长度列表,第一个片段从0开始,对于奇数长度列表,第一个片段从1开始我怀疑你现在的两个版本完全一样。但是,它们都可以通过使用切片来获取列表中的值而不是通过删除和插入值来改进。你知道吗
每一个
del
和每一个insert
都是O(N)
,你对每一个都做了N/2
,所以排序将是O(N^2)
。切片也是O(N)
,但是只需要做两次。排序所用的时间O(N log N)
将逐渐占主导地位。你知道吗输出示例:
您可以使用list slice来获得结果,而不必使用for循环:
相关问题 更多 >
编程相关推荐