@@ -211,7 +211,7 @@ Are-There-Two-Elements-That-Have-Sum-As-Specified(set, sum)
211
211
return false
212
212
```
213
213
214
- ##Problem 2-1
214
+ ##Problem 2-1 Merge-Sort + Insertion-Sort
215
215
* Time complexity for sorting n/k sublists with insertion sort:
216
216
``` cpp
217
217
(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)
238
238
Hence the largest value is k = lg(n)
239
239
```
240
240
* 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