안녕하세요 저는 지금이 선택 정렬을 구현하는 데 많은 어려움을 겪고 있습니다. 내 코드가 그 코드에 가깝다고 느끼지만 왜 코드를 가져 오지 못하는지 알 수 없습니다. 여기 Selectionsort가 올바른 결과를 출력하지 않습니다. Python
는이 결과가 이것 대신에[4, 2, 1, 3, 5]
을 얻고있다
def selectionSort(aList):
#For each index in the list...
for i in range(len(aList)):
#Assume first that current item is already correct...
minIndex = i
#For each index from i to the end...
for j in range(i + 1, len(aList)):
if aList[j] >= aList[j - 1]:
break
aList[j], aList[j - 1] = aList[j - 1], aList[j]
minIndex = aList.index(aList[j - 1])
#Save the current minimum value since we're about
#to delete it
minValue = aList[minIndex]
#Delete the minimum value from its current index
del aList[minIndex]
#Insert the minimum value at its new index
aList.insert(i, minValue)
#Return the resultant list
return aList
의견 내 코드입니다 : 사전에 도움을
[1, 2, 3, 4, 5]
감사
정렬중인 목록에서 항목을 삭제하고 추가하지 마십시오. 그들을 교환하십시오. – kindall
팁 : 필자는 오래전에 Ken Thompson (원래 Unix의 설계자이자 개발)이 그의 코드에 인쇄 명령문을 넣어 디버깅을 많이 했었다고 생각합니다. 하나 더 말할 필요하십니까? –