To write a proof by mathematical induction that counting sort is a stable sort, you must do three things:
- Choose a base case and show that your claim is true in the base case.
- Assume that the claim is true for all problem instances of size up to and including some size k. This is strong induction but we might as well do it because it's one less thing to worry about.
- Demonstrate how problem instances of the next higher size must preserve the truth of the claim.
Our base cases might as well be empty arrays and arrays of size one. Any sorting algorithm is trivially stable on these.
The induction hypothesis is similarly easy to state: counting sort is stable on all arrays of no more than k elements.
The inductive step is the tricky part. Consider an array of size k+1. This array has a largest, last element (of the elements that are largest by the sorting criteria, there is one that appears last in the array). Consider the array of size k obtained by removing this element from the array of size k+1 and shifting elements appearing to the right of it left to fill the gap. By the induction hypothesis, counting sort is stable on this array of size k. To prove that counting sort is stable on the array of size k+1 elements, we must therefore show only that counting sort cannot place the largest, last element before any elements of the same size. To see this is true, notice that when the output array B is being constructed, j assumes the values n, n-1, …, 1 in descending order, so of all the elements with the same value as our largest, last element, it will reach our element first. Because of this, it is guaranteed to place this element further to the right in B than it will place any other element with the same value since C[A[j]] is decremented, never incremented, in the loop constructing B.
C[A[i]]should beC[A[j]]. And I would use proof by contradiction. Given two elementsxandywhereyfollowsxin the original array. Assume thatxfollowsyin the output array, and prove that leads to a contradiction. - user3386109