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

fixed quicksort partition and secondsmallest function #9

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
6 changes: 4 additions & 2 deletions prose/10b_divide_and_conquer.md
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,8 @@ def partition(L, left, right):
j -= 1
if i < j:
L[i], L[j] = L[j], L[i]
L[pivot], L[i] = L[i], L[pivot]
return i
if L[pivot] <= L[i]:
L[pivot], L[i] = L[i], L[pivot]
pivot = i
return pivot
```
10 changes: 6 additions & 4 deletions prose/11_selection.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@ If our goal is to find the second largest item in a list, we could do this in li
def secondsmallest(L):
a, b = None, None
for item in L:
if a is None or item <= b:
if a is None or item <= a:
a, b = item, a
elif b is None or item <= a:
elif b is None or item <= b:
b = item
return b
```
Expand Down Expand Up @@ -77,8 +77,10 @@ def partition(L, left, right):
j -= 1
if i < j:
L[i], L[j] = L[j], L[i]
L[pivot], L[i] = L[i], L[pivot]
return i
if L[pivot] <= L[i]:
L[pivot], L[i] = L[i], L[pivot]
pivot = i
return pivot
```

Just as with `quicksort`, we use a randomized pivot so that we can expect to eliminate a constant fraction of the list with each new step. Unlike `quicksort`, we will not make a recursive call on both sides. As a result, we'll see that the average running time is only $O(n)$. That means we can do selection faster than we can sort, which makes sense, but it is *not obvious* how to do it.
Expand Down