2017-02-24 47 views
1

練習でPythonを学ぼうとすると、私はPythonを使ってクイックソートアルゴリズムを実装してテストしようとしています。 、負の数を持つPythonソートリスト

Iは

[ '35' リストを並べ替える場合 '-1'、 '-2'、 ':

実装自体は、しかしながら、ソートの結果が多少不可解であり、困難ではなかったです-7' 、 '-8'、 '3'、 '-4'、 '20'、 '-6'、 '53']

結果は[私

を与える '-1'、 '-2'、 '-3'、 '-4'、 '-6'、 '-7'、 '-8'、 '20'、 '35'、 '53']

stはソートされますが、負の整数は逆の順序でソートされます。

私はファイルから読み込んだintのリストをソートしていて、intの型は実際はintではなく、何か他のもの(文字列、おそらく)です。おそらくこの問題を解決するには?ここ

は、すべてのヘルプは高く評価されてクイックソートの実装

#quicksort -> the conquer part of the algorithm 
def quicksort(input_list, start_index, end_index): 
    if start_index < end_index: 
     #partition the list of integers. 
     pivot = partition(input_list, start_index, end_index) 
     #recursive call on both sides of the pivot, that is excluding the pivot itself 
     quicksort(input_list, start_index, pivot-1) 
     quicksort(input_list, pivot+1, end_index) 
    return input_list 

#divide part of the algorithm 
def partition(input_list, start_index, end_index): 
    #declare variables required for sorting 
    pivot = input_list[start_index] 
    left = start_index + 1 
    right = end_index 
    sorted = False 

    while not sorted: 
     #break condition so that left index is crossed with right index 
     #or if the value of left crosses the pivot value 
     while left <= right and input_list[left] <= pivot: 
      #increment left index 
      left = left + 1 
     #break the loop when right and left indexes cross 
     #or if the right value crosses the pivot value 
     while right >= left and input_list[right] >= pivot: 
      right = right-1 
     if right < left: 
      sorted = True 
     else: 
      #swap places for left value and the right value cause they are not in order 
      temp = input_list[left] 
      input_list[left] = input_list[right] 
      input_list[right] = temp 
    #swap the value at start index with what's now at the right half. Then return right for the new pivot 
    temp = input_list[start_index] 
    input_list[start_index] = input_list[right] 
    input_list[right] = temp 
    return right 

ためのコードです。あなたの時間と助けに感謝します。

答えて

1

数字ではなく文字列をソートするので、数値順ではなくアルファベット順にソートされます。 int()関数は文字列を数値に変換できます。

0

数字はすべて文字列です。あなたの入力に肯定的または否定的な整数だけが必要な場合は、比較が行われるときにint()とラップしてください。

0

文字列が辞書順にソートされているため(最初の文字、最初に一致する場合は2番目、2番目の一致の場合は3番目など)、コードは正しく動作します。あなたが数値的にソートしたい場合は、最も簡単な方法は、あなたのlistを修正することがあるので、それは実際にint値です:必要な場合は、その後strに戻って変換することができ

# Possibly read from file as list of string 
strlist = ['35', '-1', '-2', '-7', '-8', '-3', '-4', '20', '-6', '53'] 

intlist = map(int, strlist) # list(map(int, strlist)) on Python 3 

quicksort(intlist) 

。そうでない場合は、key関数のサポートを実装して(/sortedのような計算値の値をソートすることができます)、これはおそらくもっと複雑な処理になります。

+0

ありがとうございました! intをリストにマッピングし、すべてが機能します。コード内のエラーではありませんでしたが、タイプIのエラーとその振る舞いが分類されていました。ありがとうShadowRanger。私は多くを学んだ! –