2017-12-14 12 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のデザイナーと開発)は、printステートメントを自分のコードに入れてデバッグをたくさん行っていたことを、ずっと前から読んでいると思います。誰かがもっと言う必要がありますか? –

答えて

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

は、作業コードの男です。 ちょうど2行のコードが私に悪夢を与えたとは思いません。ひょうたん

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 
関連する問題