Skip to content

Commit 701ec84

Browse files
committed
quicksort: fix invariant
1 parent aacda90 commit 701ec84

File tree

1 file changed

+10
-6
lines changed

1 file changed

+10
-6
lines changed

quicksort.py

+10-6
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import random
2+
from collections import Counter
23

34
random.seed(42)
45

@@ -15,11 +16,9 @@ def quicksort(arr, start, end):
1516
"""
1617
just by last element
1718
"""
18-
original = arr[:] # for shallow copy
19+
# original = arr[:] # for shallow copy
20+
invariant = Counter(arr)
1921
if start >= end:
20-
# assert on sorting invariant:
21-
# all elements have to match before and after, only position changes
22-
assert set(original) == set(arr), "dang we lost someone"
2322
return arr
2423
pivot = arr[end]
2524
n = end
@@ -34,7 +33,7 @@ def quicksort(arr, start, end):
3433
print(f"{start=}, {end=}")
3534
print(arr)
3635
print("pivot is:", pivot)
37-
36+
3837
for j in range(start, end):
3938
if arr[j] < pivot:
4039
i += 1
@@ -46,6 +45,11 @@ def quicksort(arr, start, end):
4645
arr[end] = arr[i+1]
4746
arr[i+1] = pivot
4847

48+
# assert on sorting invariant:
49+
# all elements have to match before and after, only position changes
50+
modified = Counter(arr)
51+
assert all([invariant[key] == modified[key] for key in invariant.keys()]), "dang we lost someone"
52+
4953
quicksort(arr, start, i)
5054
quicksort(arr, i+2, end)
5155
return arr
@@ -56,8 +60,8 @@ def quicksort(arr, start, end):
5660
print(f"Total number of operations: {n_operations}")
5761

5862
# testing suite
59-
recursion_depth = 0
6063
n_operations = 0
6164
for i in range(100):
65+
recursion_depth = 0
6266
quicksort(random_array(100, 0, 100), 0, 99)
6367
print(f"Average number of operations: {n_operations/100}")

0 commit comments

Comments
 (0)