[This page is auto-generated; please prefer to read the article’s PDF Form.]
R. Sedgewick in [1] has attributed this algorithm to C. T. Fike [2]. Following is an implementation of this algorithm:
It is based on the idea that if each recursive call fike(s + 1) keeps the subarray a[s + 1 : N − 1] intact upon return, we can pick each element of B correctly (without skipping or repeating any) one by one from indices s,s + 1,s + 2,…,N − 1.
Now, to ensure this, it enforces upon method fike(s) the specification that it must keep the input subarray a[s : N − 1] intact, for each s. For s = N − 1, this specification is trivially met. For any other s, it is implemented by reversing the swap done before the recursive call fike(s + 1), once that call returns. So, if fike(s + 1) meets the specification, each iteration of fike(s) will also leave the subarray intact. This leads to the complete fike(s) meeting the specification. The correctness of this algorithm is thus established by Mathematical Induction.
An optimization is possible in above method. Note that all iterations (except the first) do two swaps which involve the element initially at a[s]. We can exploit this fact and save some writes by assigning elements as below. The 6 writes of two swaps are now replaced by the 3 writes in an iteration:
Copyright © 2021 Nitin Verma. All rights reserved.