This repository has been archived on 2021-10-31. You can view files and clone it, but cannot push or open issues or pull requests.
DSA/partition.py

41 lines
792 B
Python
Raw Normal View History

2019-03-21 14:53:57 +00:00
#!/usr/bin/env python3
2019-04-23 11:37:26 +00:00
# vim: set ts=2 sw=2 et tw=80:
2019-03-21 14:53:57 +00:00
import sys
import random
2019-04-23 11:37:26 +00:00
2019-03-21 14:53:57 +00:00
def partition(A, begin, end):
2019-04-23 11:37:26 +00:00
v_i = random.randrange(begin, end)
v = A[v_i]
A[v_i], A[end - 1] = A[end - 1], A[v_i]
i = begin
j = end - 2
while j >= i:
if A[j] > v:
j = j - 1
elif A[i] <= v:
i = i + 1
else:
A[i], A[j] = A[j], A[i]
j = j - 1
i = i + 1
A[i], A[end - 1] = A[end - 1], A[i]
return i
2019-03-21 14:53:57 +00:00
def quicksort(A, begin, end):
2019-04-23 11:37:26 +00:00
if begin < end - 1:
i = partition(A, begin, end)
print(A[begin:i], A[i], A[i + 1:end])
quicksort(A, begin, i)
quicksort(A, i + 1, end)
print(A[begin:i], A[i], A[i + 1:end])
2019-03-21 14:53:57 +00:00
2019-04-23 11:37:26 +00:00
if __name__ == "__main__":
args = [int(x) for x in sys.argv[1:]]
print(args)
quicksort(args, 0, len(args))
print(args)