練習で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
ためのコードです。あなたの時間と助けに感謝します。
ありがとうございました! intをリストにマッピングし、すべてが機能します。コード内のエラーではありませんでしたが、タイプIのエラーとその振る舞いが分類されていました。ありがとうShadowRanger。私は多くを学んだ! –