Skip to content
Open
60 changes: 60 additions & 0 deletions q_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
from merge_sort import timed_func


def q_sort(sequence):
if len(sequence) <= 1:
# Return a sequence of one sorted item, or stop if no input
return sequence
if len(sequence) == 2:
# Return a sequence of two sorted items
if sequence[1] > sequence[0]:
return sequence
else:
return sequence[::-1]
pivot = get_pivot(sequence)
left = []
right = []
center = []
for index, item in enumerate(sequence):
if item < pivot:
left.append(item)
elif item > pivot:
right.append(item)
else:
center.append(item)
return q_sort(left) + center + q_sort(right)


def get_pivot(sequence):
first = sequence[0]
last = sequence[-1]
mid_index = len(sequence) // 2
middle = sequence[mid_index]

if last > first > middle or middle > first > last:
return first
if last > middle > first or first > middle > last:
return middle
return last



@timed_func
def timed_q_sort(sequence):
return q_sort(sequence)


def same_maker(how_many):
moAr = []
for each in range(how_many):
moAr.append(1)
return moAr


if __name__ == '__main__':
inputs = [range(500), range(1000)]
inputs.append(same_maker(500))
inputs.append(same_maker(997))

for inp in inputs:
timed_q_sort(inp)
59 changes: 59 additions & 0 deletions test_q_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
from q_sort import get_pivot, q_sort


def test_get_pivot_f():
a = [2, 1, 3]
assert get_pivot(a) == 2
b = [2, 3, 1]
assert get_pivot(b) == 2


def test_get_pivot_l():
a = [1, 3, 2]
assert get_pivot(a) == 2
b = [3, 1, 2]
assert get_pivot(b) == 2


def test_get_pivot_m():
a = [1, 5, 5, 2, 1, 1, 3]
assert get_pivot(a) == 2
b = [3, 2, 1]
assert get_pivot(b) == 2


def test_q_one():
a = [4, 3, 2, 5, 7, 1, 6]
a = q_sort(a)
assert a == sorted(a)



def test_q_two():
a = [5, 5, 5, 5, 5, 5, 5, 5, 5]
a = q_sort(a)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

since your sort is not an in-place operation, you could short-circuit this:

a = [4,2,3,1]
b = q_sort(a)
assert b == sorted(a)

assert a == sorted(a)


def test_q_mixed():
a = [1, 2, 5, 4, 4, 6, 7, 9, 8, 10, 10]
a = q_sort(a)
assert a == sorted(a)


def test_q_mixed_duplicate_last_values_greater():
a = [1, 2, 10, 10, 10]
a = q_sort(a)
assert a == sorted(a)


def test_q_mixed_duplicate_last_values_lesser():
a = [1, 2, 5, 0, 0]
a = q_sort(a)
assert a == sorted(a)


def test_q_mixed():
a = [1, 2, 5, 4, 4, 6, 7, 9, 8, 0, 0]
a = q_sort(a)
assert a == [0, 0, 1, 2, 4, 4, 5, 6, 7, 8, 9]
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

given the tests you have, I feel assuaged that you aren't accidentally dropping any values while you are picking the pivot.