Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix clrs-07-01-02 solution bug #36

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions other/clrs/07/01/02.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,4 @@

It returns $r$.

We can modify `PARTITION` by counting the number of comparisons in which $A[j]
= A[r]$ and then subtracting half that number from the pivot index.
We can modify `PARTITION` by moving numbers smaller than the pivot to the leftmost and numbers equal to the pivot after the smaller group. At last we return the count of smaller group plus half of count the equal numbers.
18 changes: 10 additions & 8 deletions other/clrs/07/01/02.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,17 @@ def partition(numbers, start = 0, end = None):
for i in range(start, last):
value = numbers[i]

if value == pivot_value:
repetitions += 1

if value <= pivot_value:
numbers[pivot], numbers[i] = numbers[i], numbers[pivot]
if value < pivot_value:
numbers[pivot+repetitions], numbers[i] = numbers[i], numbers[pivot+repetitions]
numbers[pivot+repetitions], numbers[pivot] = numbers[pivot], numbers[pivot+repetitions]
pivot += 1

numbers[pivot], numbers[last] = numbers[last], numbers[pivot]
return pivot - repetitions // 2
elif value == pivot_value:
numbers[pivot+repetitions], numbers[i] = numbers[i], numbers[pivot+repetitions]
numbers[pivot+repetitions], numbers[pivot] = numbers[pivot], numbers[pivot+repetitions]
repetitions += 1

numbers[pivot+repetitions], numbers[last] = numbers[last], numbers[pivot+repetitions]
return pivot + repetitions // 2

def quicksort(numbers, start = 0, end = None):
end = end if end else len(numbers)
Expand Down
5 changes: 3 additions & 2 deletions other/clrs/07/01/02.test.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@ def test_normal_partition(self):
self.assertEqual(numbers, [3, 5, 8, 7, 4, 2, 6, 11, 21, 13, 19, 12])

def test_partition_with_repetition(self):
self.assertEqual(partition([2, 2, 2, 2, 2, 2]), 3)
self.assertEqual(partition([1, 2, 2, 2, 3, 2]), 3)
self.assertEqual(partition([2, 2, 2, 2, 2, 2]), 2)
self.assertEqual(partition([1, 2, 2, 2, 3, 2]), 2)
self.assertEqual(partition([5, 2, 4, 7, 5, 1, 5, 9, 5, 1, 10, 5]), 6)

def test_quicksort(self):
numbers = [13, 19, 3, 5, 12, 8, 7, 4, 21, 2, 6, 11]
Expand Down