初版:
lst = [1, 2, 3, 4, 5]
def sort(iterable, reverse=False):
def comp(a, b):
flag = a > b if reverse else a < b
return flag
ret = []
for x in iterable:
for i, y in enumerate(ret):
if comp(x, y):
ret.insert(i, x)
break
else:
ret.append(x)
return ret
print(sort(lst, True))
优化1:
lst1 = [1, 2, 3, 4, 5]
def comp(a, b, reverse=False):
return a > b if reverse else a < b
def sort(iterable, key=comp):
ret = []
for x in iterable:
for i, y in enumerate(ret):
if key(x, y, True):
ret.insert(i, x)
break
else:
ret.append(x)
return ret
print(sort(lst1))
优化二:
lst2 = [1, 2, 3, 4, 5]
def comp(a, b):
return a > b
def sort(iterable, key=comp, reverse=False):
ret = []
for x in iterable:
for i, y in enumerate(ret):
flag = comp(x, y) if reverse else comp(y, x)
if flag:
ret.insert(i, x)
break
else:
ret.append(x)
return ret
print(sort(lst2, key=comp, reverse=True))
优化四:
lst2 = [1, 2, 3, 4, 5]
def sort(iterable, key=lambda a, b: a > b):
ret = []
for x in iterable:
for i, y in enumerate(ret):
if key(x, y):
ret.insert(i, x)
break
else:
ret.append(x)
return ret
print(sort(lst2, lambda a, b: a < b))