2017-02-24 576 views
1

爲了通過練習學習python,我試圖用python實現並測試出快速排序算法。用負數排序Python列表

實現本身並不困難,那種然而,結果是有點令人費解:

當我一個列表排序,

[ '35', '-1', '-2',' -7' , '-8', '3', '-4', '20', '-6', '53']

結果給我

[ '-1', '-2','-3','-4','-6','-7','-8','20','35','53']

因此, st被排序,但負整數按相反的順序排序。

我懷疑這可能是一個問題,因爲我正在整理從文件中讀入的整數列表,而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。否則,您的替代方案是實現對key函數的支持(它允許您對計算值進行排序),如list.sort/sorted,但這可能更復雜,您現在要處理。

+0

謝謝!我將int映射到列表並且一切正常。所以這不是代碼中的錯誤,而是類型錯誤,我正在排序和它的行爲。謝謝ShadowRanger。我學到了很多! –