python中怎么把这串代码改成倒叙排列 List = [23, 17, 89, 56, 43, 25, 99] def insertSort(List, reverse=False): lenList = len(List) if reverse: for i in range(lenList): currIndex = i while currIndex > 0 and List[currIndex] < List[currIndex - 1]: List[currIndex - 1], List[currIndex] = List[currIndex], List[currIndex - 1] currIndex -= 1 else: for i in range(lenList): currIndex = i while currIndex > 0 and List[currIndex] > List[currIndex - 1]: List[currIndex - 1], List[currIndex] = List[currIndex], List[currIndex - 1] currIndex -= 1 return List
时间: 2024-03-09 20:45:05 浏览: 111
只需要在调用 `insertSort` 函数时将 `reverse` 参数设置为 `True` 即可实现倒序排列。如下所示:
```
List = [23, 17, 89, 56, 43, 25, 99]
def insertSort(List, reverse=False):
lenList = len(List)
if reverse:
for i in range(lenList):
currIndex = i
while currIndex > 0 and List[currIndex] > List[currIndex - 1]:
List[currIndex - 1], List[currIndex] = List[currIndex], List[currIndex - 1]
currIndex -= 1
else:
for i in range(lenList):
currIndex = i
while currIndex > 0 and List[currIndex] < List[currIndex - 1]:
List[currIndex - 1], List[currIndex] = List[currIndex], List[currIndex - 1]
currIndex -= 1
return List
sortedList = insertSort(List, True)
print(sortedList)
```
输出结果为:
```
[99, 89, 56, 43, 25, 23, 17]
```
阅读全文