Unilag Csc Forum > Programming
JAVA - Program that rotates elements in an array
Page 1 / 1
JAVA - Program that rotates elements in an array
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.
Quote   
04/05/2011 6:49 pm

Administrator
Cool Senior Member


Regist.: 04/04/2011
Topics: 14
Posts: 15
OFFLINE

Forum's a very good platform for helping ourselves. Please post your topics and comments

Endevour to check out our page Unilag Csc Page
http://www.facebook.com/pages/Unilag-Csc-Page/199688396730767 and like it.

Also join our new group Unilag Csc Group http://www.facebook.com/home.php?sk=group_173783495983164&ap=1 strictly computer scientists and aspirants too.
Quote   
Page 1 / 1
Login with Facebook to post
Preview