Skip to content

Commit fa722e4

Browse files
committed
add p2.2.b
1 parent fbb7218 commit fa722e4

File tree

1 file changed

+39
-1
lines changed

1 file changed

+39
-1
lines changed

ch02/README.md

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -211,7 +211,7 @@ Are-There-Two-Elements-That-Have-Sum-As-Specified(set, sum)
211211
return false
212212
```
213213

214-
##Problem 2-1
214+
##Problem 2-1 Merge-Sort + Insertion-Sort
215215
* Time complexity for sorting n/k sublists with insertion sort:
216216
```cpp
217217
(n/k) x theta(k^2) = theta(nk)
@@ -238,3 +238,41 @@ T(n) = theta(n x lg(n) + n x lg(n / lg(n))), if k = lg(n)
238238
Hence the largest value is k = lg(n)
239239
```
240240
* The desired value can be found by testing values from range [1, lg(n)].
241+
242+
##Problem 2-1 Bubble-Sort
243+
* One more thing need to prove is that no item in A has been deleted nor item added into A'.In another word, A' must be a permutation of A.
244+
* Loop invariant and its proof for lines 2-4
245+
```cpp
246+
Loop invariant:
247+
Prior to each iteration of the for loop, A[j] = min(s) , where set s = { x | x <- A[j, A.length] } .
248+
249+
Proof
250+
I:
251+
Prior to the first iteration
252+
-> j = A.length
253+
-> s = { x | x <- A[A.length, A.length] }
254+
-> A[A.length] is the only element in s
255+
-> I holds.
256+
257+
M:
258+
Let loop invariant holds before j = k
259+
-> A[k] = min(s), where s = { x | x <- A[k, A.length] } -- equation 1
260+
261+
The semantics of lines 3 and 4
262+
-> swap A[k] and A[k-1], if A[k] < A[k - 1]
263+
-> decrement k to k - 1
264+
265+
Applying equation 1
266+
-> j becomes k - 1
267+
-> A[k - 1] = min(s), where s = { x | x <- A[k - 1, A.length] }
268+
-> loop invariant holds before next iteration
269+
-> M holds.
270+
271+
T:
272+
Termination condition is j = i
273+
-> A[i] = min(s), where s = { x | x <- A[i, A.length] }
274+
-> this property is useful and exactly expected
275+
-> T holds.
276+
277+
I and M and T -> loop invariant holds
278+
```

0 commit comments

Comments
 (0)