python正负数排序_带负数的Python排序列表

为了通过练习来学习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而是其他类型(可能是string)的问题。我可以做些什么来解决这个问题?

下面是快速排序实现的代码#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

如有任何帮助,我们将不胜感激。谢谢大家的时间和帮助。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值