Homework-1/qsort.py

38 lines
783 B
Python
Raw Permalink Normal View History

2019-09-26 23:30:53 -07:00
def qsort(xs):
if xs == []: return []
pivot = xs[0]
left = [x for x in xs if x < pivot]
right = [x for x in xs[1:] if x >= pivot]
return [qsort(left)] + [pivot] + [qsort(right)]
def _sorted(tree, acc):
if tree == []: return
_sorted(tree[0], acc)
acc.append(tree[1])
_sorted(tree[2], acc)
2019-09-26 23:30:53 -07:00
def sorted(tree):
acc = []
_sorted(tree, acc)
return acc
2019-09-26 23:30:53 -07:00
def search(tree, x):
return _search(tree, x) != []
2019-09-26 23:30:53 -07:00
def insert(tree, x):
node = _search(tree, x)
2019-09-26 23:30:53 -07:00
if node == []:
node.append([])
node.append(x)
node.append([])
def _search(tree, i):
2019-09-26 23:30:53 -07:00
if tree == []: return tree
pivot = tree[1]
if pivot == i: return tree
elif i < pivot: return _search(tree[0], i)
else: return _search(tree[2], i)