17 September, 2014

Traversing multi dimensional array in Java


An array in Java is a type of container which contains a specified number of indexed elements, which can be thought of a single line segment. e.g. an array of int would be represented as
int[] integerArray;
 A multidimensional array is one, in which we can traverse through them to more than one way. for instance we can think of a 2-D array like a graph plot (x and y axis) similarly, a 3-D array would be like a 3-D Graph (x-y-z axis)

A 2-D array could be represented in Java as
int[][] twoDArray

In Java a 2-D array is an array of arrays. Because of this implementation, the performance of a program would vary, depending upon the way we are traversing through the array.


Consider the following program

package com.mk.twodarray;

public class CheckLoop {
private static final int ARR_SIZE=9999;
    public static void main(String[] args) {
        rowFirst();
        colFirst();
    }

    private static void rowFirst() {
        long currTime=System.currentTimeMillis();
        int arr[][]=new int[ARR_SIZE][ARR_SIZE];
        for(int i=0;i<ARR_SIZE;i++){
            for (int j=0;j<ARR_SIZE;j++){
                arr[i][j]=i+j;
            }
        }
        System.out.println("Total time in row:"+(System.currentTimeMillis()-currTime));
    }

    private static void colFirst() {
        long currTime=System.currentTimeMillis();
        int arr[][]=new int[ARR_SIZE][ARR_SIZE];
        for(int i=0;i<ARR_SIZE;i++){
            for (int j=0;j<ARR_SIZE;j++){
                arr[j][i]=i+j;
            }
        }
        System.out.println("Total time in col:"+(System.currentTimeMillis()-currTime));
    }

}