Reputation: 818
The bubble-sort algorithm (pseudo-code):
Input: Array A[1...n]
for i <- n,...,2 do
for j <- 2,...,i do
if A[j - 1] >= A[j] then
swap the values of A[j-1] and A[j];
I am not sure but my proof seems to work, but is overly convoluted. Could you help me clean it up?
Loop-invariant: After each iteration i, the i - n + 1 greatest elements of A are in the position they would be were A sorted non-descendingly. In the case that array A contains more than one maximal value, let the greatest element be the one with the smallest index of all the possible maximal values.
Induction-basis (i = n): The inner loop iterates over every element of A. Eventually, j points to the greatest element. This value will be swapped until it reaches position i = n, which is the highest position in array A and hence the final position for the greatest element of A.
Induction-step: (i = m -> i = m - 1 for all m > 3): The inner loop iterates over every element of A. Eventually, j points to the greatest element of the ones not yet sorted. This value will be swapped until it reaches position i = m - 1, which is the highest position of the positions not-yet-sorted in array A and hence the final position for the greatest not-yet-sorted element of A.
After the algorithm was fully executed, the remaining element at position 1 is also in its final position because were it not, the element to its right side would not be in its final position, which is a contradiction. Q.E.D.
Upvotes: 0
Views: 4327
Reputation: 5305
I'd be inclined to recast your proof in the following terms:
Bubble sort A[1..n]:
for i in n..2
for j in 2..i
swap A[j - 1], A[j] if they are not already in order
Loop invariant: let P(i) <=> for all k s.t. i < k <= n. A[k] = max(A[1..k])
Base case: initially i = n and the invariant P(n) is trivially satisfied.
Induction step: assuming the invariant holds for some P(m + 1), show that after the inner loop executes, the invariant holds for P(m).
Upvotes: 3