带有负数的Python排序列表

时间:2017-02-24 03:44:40

标签: python python-2.7 sorting quicksort negative-number

在尝试通过练习学习python时,我正在尝试使用python实现并测试快速排序算法。

实施本身并不困难,但这种结果有点令人费解:

当我对列表进行排序时

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

结果给了我

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

因此列表已排序,但负整数按相反顺序排序。

我怀疑这可能是一个问题,因为我正在排序从文件读入的int列表,而int的类型实际上不是int而是其他东西(字符串,也许。)我怎么可能要解决这个问题吗?

这里是quicksort实现的代码

#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 个答案:

答案 0 :(得分:1)

您的代码行为正常,因为字符串按字典顺序排序(按第一个字符排序,如果第一个匹配则排第二,如果第二个匹配则排第三,等等)。如果您想以数字方式排序,最简单的方法是修复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,但这可能更复杂你现在想要处理。