Commit a68c9a46 authored by Martin Mareš's avatar Martin Mareš
Browse files

Rozděl a panuj

parent 8d6ee5c0
#!/usr/bin/python3
def merge(x, y):
i = j = 0
out = []
while i < len(x) and j < len(y):
if x[i] < y[j]:
out.append(x[i])
i += 1
else:
out.append(y[j])
j += 1
if i < len(x):
out.extend(x[i:])
if j < len(y):
out.extend(y[j:])
return out
def mergesort(x):
if len(x) <= 1:
return x
mid = len(x) // 2
return merge(mergesort(x[:mid]), mergesort(x[mid:]))
#!/usr/bin/python3
def quickselect(x, k):
if len(x) <= 1:
return x[0]
p = x[len(x) // 2]
vlevo = [ a for a in x if a < p ]
stred = [ a for a in x if a == p ]
vpravo = [ a for a in x if a > p ]
a = len(vlevo)
b = len(vlevo) + len(stred)
if k < a:
return quickselect(vlevo, k)
elif k < b:
return p
else:
return quickselect(vpravo, k-b)
#!/usr/bin/python3
def quicksort(x):
if len(x) <= 1:
return x
p = x[len(x) // 2]
vlevo = [ a for a in x if a < p ]
stred = [ a for a in x if a == p ]
vpravo = [ a for a in x if a > p ]
return quicksort(vlevo) + stred + quicksort(vpravo)
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment