public class Bottles2 {
final int N = 15;
void bottles(int n) {
if (n < 10) System.out.print(" " + n +
" bottle");
else System.out.print(n + " bottle");
if (n != 1) System.out.print("s");
System.out.println(" of beer on the wall.");
}
void f(int n) {
while (n > 0) {
bottles(n);
n--;
}
}
void f0(int n) { // 15 down to 1
if (n > 0) {
bottles(n);
f0(n - 1);
}
}
void f1(int n) { // 1 up to 15
if (n > 0) {
f1(n - 1);
bottles(n);
}
}
void bottlestest() {
f(N); System.out.println("Set 'em up!");
f0(N); System.out.println("Set 'em up!");
f1(N);
}
public static void main(String[] args) {
Bottles2 b = new Bottles2();
b.bottlestest();
}
}
| #include |
int partition(int[] A, int p, int r) {
int x = A[r];
int i = p - 1;
for (int j = p; j < r; j++) {
if (A[j] <= x) {
i++;
exchange(A,i, j);
}
}
exchange(A, i+1, r);
return i + 1;
} | Partition(A, p, r) |
| p r
| 0 1 2 3 4 5 6 |
-----------------|------------------------------|-------------------------
before loop start| 8 2 7 9 4 3 |6 | j=, i: -1
i | |
| |
end of 0th iter | 8 2 7 9 4 3 |6 | j=0,i=-1 x=6 (pivot)
i | j |
| |
end of 1st iter | 2 | 8 7 9 4 3 |6 | j=1,i=0, exchange(i,j)
| i j |
| |
end of 2nd iter | 2 | 8 | 7 9 4 3 |6 | j=2,i=0
| i j |
| |
end of 3rd iter | 2 | 8 7 | 9 4 3 |6 | j=3,i=0
| i j |
| |
end of 4th iter | 2 4 | 7 9 | 8 3 |6 | j=4,i=1, exchange(i,j)
| i j |
| |
end of 5th iter | 2 4 3 | 9 8 | 7 |6 | j=5,i=2, exchange(i,j)
| i j |
| |
final exchange | 2 4 3 | 6 | 8 7 9 | j=, i=2, exchange(i+1,r)
| i |
return i+1 = 3 = pivot location
|