In this code how does this work (java):
/** Move A[A.length-1] to the first position, k, in A such that there
* are no smaller elements after it, moving all elements
* A[k .. A.length-2] over to A[k+1 .. A.length-1]. */
static void moveOver (int A[]) {
moveOver (A, A.length-1);
}
/** Move A[U] to the first position, k<=U, in A such that there
* are no smaller elements after it, moving all elements
* A[k .. U-1] over to A[k+1 .. U]. */
static void moveOver (int A[], int U) {
if (U > 0) {
if (A[U-1] > A[U]) {
/* Swap A[U], A[U-1] */
moveOver (A, U-1);
}
}
}
I got this from a berkeley cs class I am going through online, teaching myself. it is not homework (i wish was but not that fortunate). what I don't understand is the following:
suppose the numbers in A[] are 8, 2, 10, 5, 4, 12. When I use them above I get this in my iterations, tracing it.
- the upper most subscript is U, or in this case 12, U-1 is 4, no swap is done
- U is now 4 (recursive U-1) and the number above it is 5 (the other U-1). they get swapped.
- U is now 4 because four just moved up and 10 is U-1 they get swapped.
My sequence is now 8,2,4,10,5,12.
My question is how do I get the numbers I already passed by? how will I get five, for example, to move up if I never go back to that subscript to test with.
I don't think I am tracing the program correctly and my be getting confused with the recursion. For the sake of this please assume the swap is done correctly.
Thank you.
se