| 04/05/2011 6:48 pm |
 Administrator Cool Senior Member

Regist.: 04/04/2011 Topics: 14 Posts: 15
 OFFLINE | Hello there, you've finally made it to the section you've been waiting for.Note that the codes below are the solution problem above.
The java codes
import java.io.*;
public class Reverse {
// Reverse the content of array b starting
// at index low up to but not including high
private static void invert(int[] b, int low, int high) {
for (int j = low, k = high -1; j < k; j++, k--) {
int temp = b[j];
b[j] = b[k];
b[k] = temp;
}
}
// Print the content of array b k elements
// per line
private static void printnk(int[] b, int k) {
for (int j = 0; j < b.length; j++) {
System.out.print(" " + b[j]);
if ((j % k == (k-1)) || (j == b.length - 1)) {
System.out.println("");
}
}
}
// Rotate the elements of b k elements to the right
private static void rotate(int[] b, int k) {
invert(b, 0, b.length);
invert(b, 0, k);
invert(b, k, b.length);
}
public static void main(String[] args) {
int[] a = {1,2,3,4,5,6,7,8,9,0};
rotate(a, 3);
printnk(a, 10);
}
}
It would be best you understand what each line of code does by referring to the textbook. |
|
|