简体   繁体   English

Quicksort Python排序麻烦

[英]Quicksort Python sorting trouble

def quicksort(mas):
    if mas:
        mid = mas[0]
        menshe = [i for i in mas[1:] if i < mid]
        bolshe = [i for i in mas[1:] if i >= mid]
        return quicksort(menshe) + [mid] + quicksort(bolshe)
    else: 
        return mas

n = int(input())
mas = input().split()
print(*quicksort(mas))

It fails on some tests, for example 例如,它在一些测试中失败了

input:
3
8 21 22
output:
21 22 8

how to improve the code? 如何改进代码?

Your quicksort implementation seems to be correct, but you forgot to convert your input to integers. 您的quicksort实现似乎是正确的,但您忘记将输入转换为整数。 You are sorting strings. 你正在排序字符串。

As a side note: don't forget that pivot selection strategy is very important in quicksort algorithm. 作为旁注:不要忘记枢轴选择策略在快速排序算法中非常重要。 Your "first element as a pivot" scheme is similar to Lomuto partition scheme that easily degrades to O(n^2) for ordered or almost ordered sequences. 您的“第一个元素作为枢轴”方案类似于Lomuto分区方案 ,对于有序或几乎有序的序列,它很容易降级为O(n^2)

Your code may very well work. 你的代码可能很好用。 I've yet to test it. 我还没有测试它。 (but now that I have it seems correct) (但现在我觉得它似乎正确)

Your mistake is that you discard your first input. 你的错误是丢弃了你的第一个输入。 So, you should use your own code like this: 所以,您应该使用自己的代码,如下所示:

mas = input().split()
print(*quicksort(mas))

You only need one input. 你只需要一个输入。

Also, you are sorting strings, not necessarily numbers, so you may want to do this: 此外,您正在排序字符串,不一定是数字,所以您可能想要这样做:

mas = input().split()
print(*quicksort([int(item) for item in mas]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM