Friday, May 27, 2016

Array Operations

This example is a good start to have a basic discussion on data structures and algorithm design.  Understanding array operations and its limitations must be established first in order to understand other concepts in data structures.

public class ArrayOperations{

private static final int SIZE=10,ROW=2,COLUMN=3;
private static String array1[][]={{"00 ","01 ","02 "},{"10 ","11 ","12 "}};
private static String array2[]=new String[SIZE];
private static int next=0;


public static void main(String[] args){
    //fill();
    //insert("First");
    //insert("Second");
    //insert("Third");
    //delete("Student10");
    //System.out.println(fetch("Student3"));
    //update('d',"Student3");
    majorOrder('c');
    majorOrder('r');
    System.out.println();
}

private static void fill(){
    for(int i=0;i<SIZE;i++){
        array2[i]=new String("Student"+(i+1));
        next++;
    }
}

private static void delete(String key){   //slow O(n) due to sequential search
   if(next!=0){
    int i=0;
    while(array2[i].equals(key)){
        i++;
    }
   
    for(int j=i;j<next-1;j++){
        array2[j]=array2[j+1];
    }
    next--;
    array2[next]=null; 
   }
}

private static void majorOrder(char order){       //slow O(n^2) due to sequential search
    int total=0;
    if(order=='c'){
        for(int i=0;i<ROW;i++){
            for(int j=0;j<COLUMN;j++){
               total++;
               if(array1[i][j].equals("02 ")) 
                    System.out.println("It took "+total+" operations to find it");
            }
        }
    }
    else if(order=='r'){
        for(int j=0;j<COLUMN;j++){
            for(int i=0;i<ROW;i++){
               total++;
               if(array1[i][j].equals("02 ")) 
                    System.out.println("It took "+total+" operations to find it");
            }
        }
    }
    else
        System.out.println("Wrong major order type, only \'r\' or \'c\' are allowed");
}

private static void insert(String str){
    array2[next++]=new String(str);
}

private static String fetch(String key){  //slow O(n) due to sequential search
    int i=0;
    while(!array2[i].equals(key)){
        i++;
    }
    return new String(array2[i]); //return deepcopy object
}

private static void update(char oper, String str){

    if(oper=='i'){
        insert(str);
    }
    else if(oper=='d'){
        delete(str);
    }
    else
        System.out.println("Wrong operation was specified, use \'i\' or \'d\' for insert or delete operation");
}
}

No comments:

Post a Comment