Algorithms hw2
0: bool swapped 1: repeat 2: swapped = false 3: i = 0 4: while i < n-1: 5: if A[i] > A[i+1]: 6: swap(A,i,i+1) 7: swapped = true 8: i = i + 1 9: until !swapped
(a) 证明 outer loop terminates:
一共有n^2对pair (a b),每次只swap 符合a > b的pair,因此一共swap的总数不会超过n^2,因此…,因此最后会terminate。
(b)写出一个inner loop的loop invariant:
if(!swapped), then A[0]~A[i] is sorted.
这个L.I.比“A[i] is the largest element among the first i elements”,因为它利用了swapped,而swapped是这个算法相对于两个for循环的普通冒泡算法的优势所在。

浙公网安备 33010602011771号