Reputation: 49
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?
Upvotes: 3
Views: 163
Reputation: 9117
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.
Upvotes: 3
Reputation: 39354
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]))
Upvotes: 1