插入排序,从小到大得输入参数 这段代码哪有问题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 List[currIndex] < List[currIndex - 1] and currIndex >= 0: List[currIndex - 1], List[currIndex] = List[currIndex], List[currIndex - 1] currIndex -= 1 else: for i in range(lenList): currIndex = i while List[currIndex] > List[currIndex - 1] and currIndex >= 0: List[currIndex - 1], List[currIndex] = List[currIndex], List[currIndex - 1] currIndex -= 1 return List
时间: 2024-01-31 17:03:49 浏览: 67
排序,输入整数,从小到大,字符则反串
5星 · 资源好评率100%
这段代码有两个问题:
1. 在 while 循环中,应该要加上 `currIndex > 0` 的判断条件,否则会出现下标越界的情况。
2. 在 while 循环中,应该要将 `currIndex` 前移,而不是后移,因为我们是要插入当前元素到前面已排序的序列中。
下面是修改后的代码:
```
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
```
阅读全文