3 回答
TA贡献1802条经验 获得超5个赞
你必须在未排序的 arr 上使用枚举
def sortPercent(unsortedArr):
unsortedArr = list(enumerate(unsortedArr)) # [(0, 38), (1, 33), (2, 30), (3, 31), (4, 25)]
n = len(unsortedArr)
for i, percent in enumerate(range(n-1)):
for j, percent in enumerate(range(0, n-i-1)):
if unsortedArr[j][1] > unsortedArr[j + 1][1]: # when j = 0, unsortedArr[j] = (0,38), unsortedArr[j][1] = 38, unsortedArr[j+1][1]=30
unsortedArr[j],unsortedArr[j+1] = unsortedArr[j+1], unsortedArr[j]
return unsortedArr
unsortedArr = [38, 33, 30, 31, 25]
print(sortPercent(unsortedArr))
# [(4, 25), (2, 30), (3, 31), (1, 33), (0, 38)]
TA贡献1845条经验 获得超8个赞
你根本不必使用enumerate(),这个函数定义做你想做的,用简单的代码:
def sortPercent(unsortedArr):
n = len(unsortedArr)
unsortedArr = [(i, unsortedArr[i]) for i in range(n)]
for i in range(n-1):
for j in range(0, n-i-1):
if unsortedArr[j][1] > unsortedArr[j + 1][1]:
unsortedArr[j],unsortedArr[j+1] = unsortedArr[j+1], unsortedArr[j]
return unsortedArr
TA贡献1860条经验 获得超9个赞
def sortPercent(unsortedArr):
n = len(unsortedArr)
for i, percent in enumerate(range(n-1)):
for j, percent in enumerate(range(0, n-i-1)):
if unsortedArr[j] > unsortedArr[j + 1]:
unsortedArr[j],unsortedArr[j+1] = unsortedArr[j+1], unsortedArr[j]
return unsortedArr
if __name__ == "__main__":
unsortedArr = [38, 33, 30, 31, 25]
sortedArr=sortPercent(unsortedArr.copy())
for i in range (len(unsortedArr)):
print(sortedArr[i],"-",unsortedArr.index(sortedArr[i]))
添加回答
举报