Bubblesort(A)
int i, j;
for i from 1 to n
{
for j from n-1 downto i
{
if (A[j] > A[j+1])
swap(A[j], A[j+1])
}
}
Could we prove the correctness of the above algorithm, using induction?
If so, could you give me some hints how we could do this?
EDIT: At the base case, we check the case $i=1$, right? $$$$
For $i=1 $ we compare pairwise the elements $ (A[n], A[n-1]) $, $(A[n-1],A[n-2]) , \dots, (A[2],A[1])$ and if $A[i]>A[i+1], i \in \{ 1, \dots, n-1 \}$ then we swap their values, right?
So what can we say for the base case?
Also, what do we have to suppose at the induction hypothesis?
Your algorithm has a typo. The inner loop should start $j := i + 1$ and go to $n$. Notice that after iteration $i$ of the outer loop, the largest $i$ elements are sorted correctly at the end of the list. Prove this fact, which I will call $(*)$.
We also have termination, by finiteness of both loops (and no modification of $i, j$ other than incrementation).
You can then use induction on $(*)$ to argue that if the largest elements are sorted correctly at indices $n-i, ..., n-1$, then the next iteration of the loop will correctly place the $n-1-i$ largest element at index $n - 1 - i$, preserving order.
Edit:
Claim: On the ith iteration of the outer loop, the largest $i$ elements will be sorted correctly (at the end of the array).
Proof: By induction on $n \in \mathbb{N}$. Consider the base case of $n = 1$. Let $x$ be the largest element in the array. By the algorithm, if $x$ is unique, $x$ is swapped on each iteration after being discovered initially. It is then placed at the end. If $x$ is not unique, then there exists a second copy of it and no swap will occur. However, the second copy will then be swapped. This process continues, so the last occurrence of $x$ will be moved to the end of the array. The theorem thus holds at $i = 1$.
I assume the theorem holds true up to an arbitrary integer $k$ such that $1 < k < n$ and prove true for the $k+1$ case. Let $y$ be the $k+1$ largest element in the array. We consider the reduced case of examining the first $n - k - 1$ elements. By the inductive hypothesis, $y$ will be correctly placed at the end of this sub-array. As $y$ is no bigger than the $k$th largest element, $y$ will not be moved further down into the array. The $k+1$ case thus holds.
And so the claim holds true by the principle of mathematical induction.