연습을 통해 파이썬을 배우려는 시도에서 파이썬을 사용하여 빠른 정렬 알고리즘을 구현하고 테스트하려고합니다.음수가 포함 된 파이썬 정렬 목록
가 구현 자체가 어렵지 않았다, 일종의 그러나 그 결과는 다소 당혹 :
I가리스트
[ '35', '-1'정렬되면 '-2', ' -7 ','-8 ','-3 ','-4 ','20 ','-4 ','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 감사합니다. 나는 많이 배웠다! –