我正在制作一个非常简单的排序程序来练习气泡排序/交换例程。我遇到了这个代码的问题,我不能为我的生活弄清楚。我将不胜感激任何批评和帮助使这些代码工作和有用的技巧,以提高我在Python排序方面的知识。谢谢大家。
脚本的目的:按降序排序员工+收入。
错误:
Traceback (most recent call last):
File "C:/Users/Bar/Desktop/IS115/A8.py", line 28, in <module>
main()
File "C:/Users/Bar/Desktop/IS115/A8.py", line 25, in main
bubblesort(earnings, names)
File "C:/Users/Bar/Desktop/IS115/A8.py", line 17, in bubblesort
swap(A, first, second, E)
File "C:/Users/Bar/Desktop/IS115/A8.py", line 3, in swap
temp2 = E[x]
IndexError: list index out of range
def swap(A, x, y, E):
temp1 = A[x]
temp2 = E[x]
A[x] = A[y]
E[x] = E[y]
A[y] = temp1
E[y] = temp2
def bubblesort(A, E):
for i in range(len(A)):
for k in range(len(A) - 1):
first = k
second = k + 1
if (A[first] > A[second]):
swap(A, first, second, E)
print(A)
temp = input("Hit enter for the next step:\n")
def main():
names = ["Albert, Andy, Bill, Carl, David, Edward, Frank, George, Harry"]
earnings = [92300, 94200, 81800, 75400, 61300, 53900, 41200, 32300, 29400]
bubblesort(earnings, names)
main()