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

Recorded work from Thursday.

parent d36ec3a2
Branches solution
No related tags found
No related merge requests found
......@@ -48,19 +48,19 @@ Problem: Sort a list in Θ(n log n) time.
```
In: [8, 7, 6, 9, 5]
Out: [, , , , ]
Out: [5, 6, 7, 8, 9]
/ \
/ \
In: […] In: []
Out: […] Out: []
In: [8, 7] In: [6, 9, 5]
Out: [7, 8] Out: [5, 6, 9]
/ \ / \
/ \ / \
In: [] In: [] In: [] In: []
Out: [] Out: [] Out: [] Out: []
In: [8] In: [7] In: [6] In: [9, 5]
Out: [8] Out: [7] Out: [6] Out: [5, 9]
/ \
/ \
In: [] In: []
Out: [] Out: []
In: [9] In: [5]
Out: [9] Out: [5]
```
## Analysis
......@@ -69,14 +69,14 @@ Out: […] Out: […] Out: […] Out: […]
T(n) = T(⌊n/2⌋) + T(⌈n/2⌉) + Θ(n) for n ≫ 0
T(n) ≈ 2T(n/2) + Θ(n) for n ≫ 0
T(n) = Θ()
T(n) = Θ(n log n)
* Uneven split:
T(n) = T(n - 1) + T(1) + Θ(n) for n ≫ 0
T(n) = T(n - 1) + Θ(1) + Θ(n) for n ≫ 0
T(n) = T(n - 1) + Θ(n) for n ≫ 0
T(n) = Θ()
T(n) = Θ()
--------------------------------------------------------------------------------
......@@ -96,11 +96,11 @@ Problem: Find the median of an odd-length list in average-case Θ(n) time. Use
```
In: [8, 7, 6, 9, 5]
Out:
Out: 7 (but how?)
/ \
/ \
In: […] In: []
Out: Out:
In: [8, 7] In: [6, 9, 5]
Out: 7.5 Out: 6
```
* Option A: We are missing information from the recursive calls. Add output(s) so that they can return that information.
......@@ -108,15 +108,15 @@ Problem: Find the median of an odd-length list in average-case Θ(n) time. Use
## Design (second attempt)
* More generally, we want , so we add an input `k`:
* More generally, we want `k`th element if the list were sorted, so we add an input `k`:
```
In: [8, 7, 6, 9, 5], k = 2
Out:
Out: 7
/ \
/ \
In: [], k = 2 In: [], k = 0
Out: Out:
In: [8, 7], k = 2 In: [6, 9, 5], k = 0
Out: ??? Out: 5
```
## Partitioning
......
function merge(left, right) {
return []; // TODO: stub
const merged = [];
let i = 0;
let j = 0;
while (i < left.length || j < right.length) {
if (i < left.length && (j === right.length || left[i] < right[j])) {
merged.push(left[i]);
++i;
} else {
merged.push(right[j]);
++j;
}
}
return merged;
}
export function sort(list) {
return list; // TODO: stub
if (list.length <= 1) {
return list;
}
const middleIndex = Math.floor(list.length / 2);
const left = sort(list.slice(0, middleIndex));
const right = sort(list.slice(middleIndex, list.length));
return merge(left, right);
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment