Skip to content

Commit 997a49c

Browse files
committed
Merge branch 'v2' of https://github.com/Mooophy/CLRS into v2
2 parents 93b701d + 111e598 commit 997a49c

File tree

1 file changed

+59
-5
lines changed

1 file changed

+59
-5
lines changed

ch02/README.md

Lines changed: 59 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -315,11 +315,65 @@ I.M.T -> LI holds.
315315
* Time complexity : theta(n)
316316
* pseudocode
317317
```python
318-
Naive-Polynomial-Evaluation(arr_of_terms, x)
319-
y = 0;
320-
for term in arr_of_terms
318+
Naive-Polynomial-Evaluation(arr, x)
319+
y = 0
320+
for i = 0 to arr.length - 1
321321
X = 1
322-
for i = 1 to term.k
322+
for k = i downto 1
323323
X *= x
324-
y += term.ak * X
324+
y += X * arr[i]
325+
return y
326+
```
327+
328+
* LI and proof
329+
```cpp
330+
(To avoid Greek letter Sigma, here is using sum(head, tail)() function instead)
331+
L.I.:
332+
At the start of each iteration of the for loop of lines 2–3,
333+
y = sum(k = 0, k = n - (i + 1)) (a(k + i + 1) * x ^ k)
334+
335+
I.:
336+
Prior to the first iteration,
337+
y = sum(k = 0, k = -1) (a(k + i + 1) * x ^ k)
338+
upper limit is lower than lower limit, this equation is meaningless, y = 0
339+
Hence, I holds.
340+
341+
M.:
342+
Suppose L.I. holds before i = i
343+
y = sum(k = 0, k = n - (i + 1)) (a(k + i + 1) * x ^ k)
344+
345+
by line 2 - 3, LHS becomes:
346+
y = a(i) + x * y
347+
= a(i) + x * ( a(i + 1) + a(i + 2) * x + ... + a(n) * x^(n - i - 1)
348+
= a(i) + a(i + 1) * x + a(i + 2) * x^2 + ... + a(n) * x^(n - i)
349+
350+
when i = i - 1 RHS becomes
351+
sum(k = 0, k = n - i) (a(k + i) * x ^ k)
352+
= a(i) + a(i + 1) * x + a(i + 2) * x^2 + ... + a(n) * x^(n - i)
353+
354+
LHS = RHS, hence M holds for next iteration.
355+
356+
T.:
357+
The termination condition is i = -1
358+
y = sum(k = 0, k = n - (-1 + 1)) (a(k - 1 + 1) * x ^ k)
359+
= sum(k = 0, k = n) (a(k) * x ^ k)
360+
Hence, T holds.
361+
362+
L.I. holds.
363+
```
364+
365+
* As shown above, this code fragment correctly evaluates a polynomial.
366+
367+
##Problem 2-4 Inversions
368+
* Five inversions:
369+
```cpp
370+
{2,1}, {3,1}, {8,1}, {6,1}, {8,6}
371+
```
372+
* set {n, n-1, n-2, ...,2, 1}, i.e. numbers in descending order has most inversions.
373+
```
374+
number of inversions = n(n - 1)/2
375+
```
376+
* As shown below, the expression `A[i] > key` in line 5 Insertion-Sort is in essence checking for an inversion. So a function can be made to describe the relationship between the running time and number of inversions:
377+
```cpp
378+
T(n) = theta(number_of_inversions + n)
325379
```

0 commit comments

Comments
 (0)