Skip to content
Snippets Groups Projects
Commit a5cd6939 authored by Brady James Garvin's avatar Brady James Garvin
Browse files

Recorded work from Tuesday.

parent a9db06ee
No related branches found
No related tags found
No related merge requests found
......@@ -112,7 +112,7 @@ Problem: Find the median of an odd-length list in average-case Θ(n) time. Use
```
In: [8, 7, 6, 9, 5], k = 2
Out: 7
Out: 7 (but how?)
/ \
/ \
In: [8, 7], k = 2 In: [6, 9, 5], k = 0
......@@ -131,24 +131,39 @@ Problem: Find the median of an odd-length list in average-case Θ(n) time. Use
```
In: [8, 7, 6, 9, 5], k = 2
In: […], k = 2
In: […], k = 2
Split: […], …, […]
Out: …
*
i
j
In: [8, 7, 6, 5, 9], k = 2
*
i
j (crossed)
i
In: [5, 7, 6, 8, 9], k = 2
Split: [5, 7, 6], 8, [9]
Out: 7
|
|
|
In: […], k = …
In: […], k = …
Split: […], …, […]
Out: …
In: [5, 7, 6], k = 2
*
i
j (crossed)
i
In: [5, 7, 6], k = 2
Split: [], 5, [7, 6]
Out: 7
|
|
|
In: […], k = …
In: […], k = …
Split: […], …, […]
Out: …
In: [7, 6], k = 2 - 1 (because we threw away one element, 5) = 1
*
i
j (crossed)
i
In: [6, 7], k = 1
Split: [6], 7, []
Out: 7
```
## Analysis
......@@ -156,9 +171,9 @@ Problem: Find the median of an odd-length list in average-case Θ(n) time. Use
* Uneven split:
T(n) = T(n - 1) + Θ(n) for n ≫ 0
T(n) = Θ()
T(n) = Θ()
* Even split:
T(n) ≈ T(n/2) + Θ(n) for n ≫ 0
T(n) = Θ()
T(n) = Θ(n)
......@@ -31,5 +31,15 @@ export function kthSmallest(sequence, k) {
k >= 0 && k < sequence.length,
'Tried to find the kth smallest element when k is out of bounds.',
);
return sequence[0]; // TODO: stub
if (sequence.length < 2) {
return sequence[0];
}
const [left, pivot, right] = partition(sequence);
if (k === left.length) {
return pivot;
}
if (k < left.length) {
return kthSmallest(left, k);
}
return kthSmallest(right, k - 1 - left.length);
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment