2017-02-24 10 views
1

연습을 통해 파이썬을 배우려는 시도에서 파이썬을 사용하여 빠른 정렬 알고리즘을 구현하고 테스트하려고합니다.음수가 포함 된 파이썬 정렬 목록

가 구현 자체가 어렵지 않았다, 일종의 그러나 그 결과는 다소 당혹 :

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 

코드입니다. 시간과 도움을 주셔서 감사합니다.

답변

1

숫자가 아닌 문자열을 정렬하므로 숫자 순서가 아닌 알파벳 순서로 정렬됩니다. int() 함수는 문자열을 숫자로 바꿀 수 있습니다.

0

귀하의 전화 번호는 모두 문자열입니다. 입력에서 양수 또는 음수를 예상하는 경우 비교가 이루어지면 int()으로 감싸십시오.

0

문자열이 사전 식으로 정렬되므로 (첫 번째 문자, 첫 번째 일치하는 경우 두 번째, 두 번째 일치하는 경우 세 번째 등) 코드가 올바르게 작동합니다. 당신은 수치 적으로 정렬 할 경우, 가장 쉬운 방법은 list 그래서 사실이다 int 값을 수정하는 것입니다 : 필요한 경우

# 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) 

당신은 나중에 str로 다시 변환 할 수 있습니다. 그렇지 않으면 list.sort/sorted과 같은 key 함수 (값을 계산 된 값으로 정렬 할 수 있음)에 대한 지원을 구현하는 것이 좋습니다. 그러나 지금 다루고 싶은 것은 아마도 더 복잡 할 것입니다.

+0

고마워요! int를 목록에 매핑하면 모든 것이 작동합니다. 그래서 코드에서 에러가 아니었지만, 타입 I의 에러는 정렬되고 그 에러의 행동이었습니다. ShadowRanger 감사합니다. 나는 많이 배웠다! –