2017-02-24 578 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。我学到了很多! –