简体   繁体   中英

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. 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.

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]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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