2017-12-14 1 views
0

안녕하세요 저는 지금이 선택 정렬을 구현하는 데 많은 어려움을 겪고 있습니다. 내 코드가 그 코드에 가깝다고 느끼지만 왜 코드를 가져 오지 못하는지 알 수 없습니다. 여기 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] 

감사

+0

정렬중인 목록에서 항목을 삭제하고 추가하지 마십시오. 그들을 교환하십시오. – kindall

+0

팁 : 필자는 오래전에 Ken Thompson (원래 Unix의 설계자이자 개발)이 그의 코드에 인쇄 명령문을 넣어 디버깅을 많이 했었다고 생각합니다. 하나 더 말할 필요하십니까? –

답변

0
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]) 

선택 정렬은 목록에서 최소 요소를 반복적으로 찾는 방식으로 정렬됩니다. 첫 번째 요소를 최소값으로 설정하고 현재 요소가 최소값보다 작 으면 최소값으로 기록하고 인덱스를 기록하면 목록을 반복합니다. 이후 부분이 정확합니다.

def selectionSort(aList): 

    #For each index in the list... 
    for i in range(len(aList)): 

     minIndex = i 

     #For each index from i+1 to the end... 
     for j in range(i + 1, len(aList)): 

      if aList[minIndex] > aList[j]: 
      minIndex = j 

     #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 

감사 한 번 더 : 여기

+0

게시하기 전에 시도했지만 작동하지 않았습니다. 나는이 라인을 의미한다 – user8964866

+0

minIndex = aList.index (aList [j - 1]) – user8964866

0

는 작업 코드들입니다. 두 줄의 코드만으로도 악몽을 꾼 것으로 믿을 수 없습니다. pheew

0

당신은 삭제하고 삽입 할 필요가 없습니다, 그냥 스왑!

def selectionSort(aList): 

     #For each index in the list (not the last one) 
     for i in range(len(aList)-1): 

      #initialized minIndex 
      minIndex = i 

      #For each index from i+1 to the end... 
      for j in range(i + 1, len(aList)): 
       #find the min of the list and update minIndex 
       if aList[j] < aList[minIndex]: 
        minIndex = j; 

      #if minIndex changed, swap i and minIndex values 
      if minIndex != i: 
       aList[i], aList[minIndex] = aList[minIndex], aList[i] 

     #Return the resultant list 
     return aList 
관련 문제