skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

  • Home
 
  • RSS
  • Twitter
Showing posts with label Data Structure. Show all posts
Showing posts with label Data Structure. Show all posts
Wednesday, August 13, 2014

Create an Adjacency matrix Graph and perform Add and Remove operation

Posted by Happy Coder at 3:07 PM – 0 comments
 

import java.util.ArrayList;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Stack;

/**
 * Implementation of a directed unweighted Graph using Adjacency Matrix
 * 
 * Complexity: addEdge, removeEdge, hasEdge O(1) / outEdges, inEdges O(n) /
 * Space O(n^2)
 */
public class AdjMatrixGraph {
 int size;
 private boolean[][] matrix;
 public static final byte WHITE = 1;
 public static final byte GREY = 2;

 public AdjMatrixGraph(int size) {
  this.size = size;
  this.matrix = new boolean[size][size];
 }

 public void addEdge(int nodeA, int nodeB) {
  matrix[nodeA][nodeB] = true;
 }

 public void removeEdge(int nodeA, int nodeB) {
  matrix[nodeA][nodeB] = false;
 }

 public boolean hasEdge(int nodeA, int nodeB) {
  return matrix[nodeA][nodeB];
 }

 public List<Integer> outEdges(int i) {
  List<Integer> edges = new ArrayList<Integer>();
  for (int j = 0; j < size; j++) {
   if (matrix[i][j]) {
    edges.add(j);
   }
  }
  return edges;
 }

 public List<Integer> inEdges(int i) {
  List<Integer> edges = new ArrayList<Integer>();
  for (int j = 0; j < size; j++) {
   if (matrix[j][i]) {
    edges.add(j);
   }
  }
  return edges;
 }

 public int nVertices() {
  return size;
 }

 public void breadthFirstSearch(int root) {
  boolean[] seen = new boolean[nVertices()];
  Queue<Integer> q = new LinkedList<Integer>();
  q.add(root);
  seen[root] = true;
  while (!q.isEmpty()) {
   int i = q.remove();
   for (Integer j : outEdges(i)) {
    if (!seen[j]) {
     q.add(j);
     seen[j] = true;
    }
   }
  }
 }

 public void depthFirstSearch(int r) {
  byte[] c = new byte[nVertices()];
  Stack<Integer> s = new Stack<Integer>();
  s.push(r);
  while (!s.isEmpty()) {
   int i = s.pop();
   if (c[i] == WHITE) {
    c[i] = GREY;
    for (int j : outEdges(i))
     s.push(j);
   }
  }
 }

 public static void main(String[] args) {
  AdjMatrixGraph graph = new AdjMatrixGraph(10);

  graph.addEdge(1, 3);
  graph.addEdge(2, 4);
  graph.addEdge(6, 8);
  graph.addEdge(3, 2);

  System.out.println("Edge from 6 to 8 is : " + graph.hasEdge(6, 8));
  System.out.println("Edge from 2 to 4 is : " + graph.hasEdge(2, 4));
  System.out.println("Edge from 3 to 2 is : " + graph.hasEdge(3, 2));
  System.out.println("Edge from 1 to 3 is : " + graph.hasEdge(1, 3));

  graph.removeEdge(6, 8);
  System.out.println("Edge from 6 to 8 is : " + graph.hasEdge(6, 8));

 }
}

Output of this Program:
Edge from 6 to 8 is : true
Edge from 2 to 4 is : true
Edge from 3 to 2 is : true
Edge from 1 to 3 is : true
Edge from 6 to 8 is : false

Try this by Yourself : http://ideone.com/ZZm7rW
[ Read More ]
Read more...
Monday, April 22, 2013

Implementation of a basic generic tree, with labels of type T - Data Structure

Posted by Admin at 12:39 PM – 0 comments
 


// This implements a basic generic tree, with labels of type T,
// pointer to the parent node, and a singly linked list of children nodes.

class Tree<T>  {
    private T label;
    private Tree<T> parent;
    private Tree<T> nextSibling; // next node on the list of parents's 
                                 //  children
    private Tree<T> firstChild;  // first in the linked list of children

                                 
//  Getters and setters
    public T getLabel() { return label; }  
    public void setLabel(T v) { label = v; }
    public Tree<T> getParent() { return parent;}
    public Tree<T> getNextSibling() { return nextSibling;}
    public Tree<T> getFirstChild() { return firstChild;}

// Add C to the front of the children of this
    public void addChild(Tree<T> c) {
         c.parent = this;
         if (firstChild == null) 
           firstChild = c;
         else {
             c.nextSibling = firstChild;
             firstChild = c;
            }
    }

// Check if the node is a leaf
    public boolean Leaf() { return firstChild==null; }

// `Convert the tree into a string. The structure is indicated by
// square brackets. Uses a preorder listing.
    public String toString() {
       String S = "[ " + label.toString();
       Tree<T> N = firstChild;
       while (N != null) {
          S = S + " " + N.toString();
          N = N.nextSibling;
        }
       return S+" ]";
     }

     public void displayPreorder() {
         displayPreorder1(0); }

     public void displayPreorder1(int Indent) {
         for (int I = 0; I < Indent; I++) System.out.print(" ");
         System.out.println(label.toString());
         Tree<T> N = firstChild;
         while (N != null) { 
            N.displayPreorder1(Indent+3);
            N = N.nextSibling;
           }
         }

     public void displayPostorder() {
         displayPostorder1(0); }

     public void displayPostorder1(int Indent) {
         Tree<T> N = firstChild;
         while (N != null) { 
            N.displayPostorder1(Indent+3);
            N = N.nextSibling;
           }
         for (int I = 0; I < Indent; I++) System.out.print(" ");
         System.out.println(label.toString());
         }
}

[ Read More ]
Read more...

Stack implemented as array - Data Structure

Posted by Admin at 12:36 PM – 0 comments
 


// Stack implemented as array
public class ArrayStack<T> {
     private T[] stack;
     private int numElements = 0; // points to slot after top element

     public ArrayStack(T[] s) { stack = s; }  

     public boolean emptyStack() { 
         return numElements == 0; }
   
     public T  top() {
         return stack[numElements-1];
       }

     public void push(T x) {
         stack[numElements] = x;
         numElements++;
       }
  
     public T pop() {
         numElements--;
         return stack[numElements];
      }

    public static void main(String[] args) {
       ArrayStack<Integer> s = new ArrayStack<Integer>(new Integer[100]);
       s.push(2);
       s.push(3);
       s.push(5);
       System.out.println(s.top());
       System.out.println(s.pop());
       System.out.println(s.pop());
       s.push(15);
       s.push(22);
       System.out.println(s.pop());
   }
}

[ Read More ]
Read more...

Singly linked list with header - Data Structure

Posted by Admin at 12:34 PM – 0 comments
 




class OrderedList  {
   private int value;
   private OrderedList next;

// Note: No setValue() method or setNext() methods are provided, 
// since those could require reordering the list.
  
   public int getValue() {
       return value; }

   public OrderedList getNext() {
       return next; }

// If X is in the list, returns the previous node.
// If X is not in the list, returns the node for the greatest element less 
// than  X.

   public OrderedList searchBefore(int x) { // Locate node containing X
       OrderedList n = this;
       while (true) {
          if (n.next==null) return n;
          if (n.next.value >= x) return n;
          n = n.next;
         } 
      }

// Is element x in the list. Note the use of the left to right evaluation of 
// && (if the condition n.net != null is false, then the conjunction returns
// false without evaluating n.next.value=x.

   public boolean inList(int x) {
       OrderedList n = searchBefore(x);
       return n.next != null && n.next.value == x; }

// Adds x to the ordered list, if it is not already there.
   public void add(int x) {
       OrderedList n = searchBefore(x);
       if (n.next == null || n.next.value != x) {
           OrderedList newNode = new OrderedList();
           newNode.value = x;
           newNode.next = n.next;
           n.next = newNode;
         }
     }
       
// Deletes X from the ordered list, if it is there.

   public void delete(int x) {
       OrderedList n = searchBefore(x);
       if (n.next != null && n.next.value == x)
          n.next = n.next.next;
      }



   public String toString() {
          OrderedList a = next;
          String s = "[";
          while (a != null) {
             s = s + a.value + " ";
             a = a.next;
           }
         return s+ "]";
         }

   public static void main(String[] args) {
      OrderedList l = new OrderedList();
      l.add(31);
      l.add(41);
      l.add(59);
      l.add(26);
      l.add(53);
      l.add(58);
      l.add(37);
      l.delete(53);
      System.out.println(l.toString());
}
}



[ Read More ]
Read more...

Ordered array of ints with no repetition - Data Structure

Posted by Admin at 12:32 PM – 0 comments
 



public class OrderedArray {

   private int numElements = 0;
   private int[] elements;

// Constructor..Note: the caller has to provide the array of elements.
// This is because Java generics do not allow a call "elements = new T[100]".
//
   public OrderedArray(int[] elts) {
        elements = elts; }

   public int getNumElements() { return numElements; } 

   public int nth(int n) { // return the Nth element
       if (n < numElements) return elements[n]; else return -1; }
  
   public int first() { return nth(0); } 
   public int  last() { return nth(numElements-1); } 

//  search(X) returns the index where X is, if X is in the list.
//  Otherwise, it returns the index of the smallest number greater than X
   public int search(int x) {
       if (numElements==0) return 0;
       if (x <= first()) return 0;
       if (x > last()) return numElements;
       if (x == last()) return numElements-1;
       return search1(x,0,numElements-1); 
     }

// X is strictly between L and U.
   public int search1(int x,int l,int u) {
        if (u==l+1) return u;
        else {
           int m = (l+u)/2;
           if (x==elements[m]) return m;
           else if (x < elements[m]) return  search1(x,l,m);
           else return search1(x,m,u);
        }
     }

   public boolean inList(int x) {
       return (elements[search(x)]==x); }

   public void add(int x) {
      int i = search(x);
      if (elements[i] != x)  {
        for (int j = numElements; j>i; j--)
           elements[j]=elements[j-1];
        elements[i]=x;
        numElements++;
       }
     }

   public void delete(int x) {
      int i = search(x);
      if (elements[i] == x) {
        for (int j=i+1; j < numElements; j++)
          elements[j-1] = elements[j];
        numElements--;
      }
    }


   public String toString() {
      String s = "[";
      for (int i=0; i < numElements; i++)
         s = s + " " + elements[i];
      return s+"]";
   }

   public static void main(String[] args) {
      OrderedArray l = new OrderedArray(new int[100]);
      l.add(31);
      l.add(41);
      l.add(59);
      l.add(26);
      l.add(53);
      l.add(58);
      l.add(37);
      l.delete(53);
      System.out.println(l.toString());
      System.out.println(l.search(2));
      System.out.println(l.search(26));
      System.out.println(l.search(53));
      System.out.println(l.search(54));
      System.out.println(l.search(195));
}
}


[ Read More ]
Read more...
Older Posts
Subscribe to: Posts ( Atom )

List of Java Programs

  • Java Program to check Greater between the Two Number
  • Java Program to find that given number is Palindrome or not
  • Java Program to Demonstrate the Use of Pre and Post Operator
  • Java Program to Reverse the Given Number
  • Java Program to Print Number in the Given Data Type
  • Program to Demonstrate Skipping using Continue
  • Program to find whether entered character is a vowel or Consonant
  • Java Program to Calculate the Sum of Digits of Given Number
  • How to swap two numbers using only two variables
  • Checking the Given Number is Armstrong or Not
  • Average an Array of Values
  • Display ASCII Code Instead of Character
  • Comparison of Two Variable using If
  • Printing Table In java using While Loop
  • Generate Random Number Using Math.Random Function
  • To Find roots of Quadratic Equation
  • Performing Arithmetic Opration on Two Variable
  • Concatenation of Two String in Java
  • Command Line Argument in JAVA
  • Java Hello World Program
  • Calculate Circle Perimeter | Java Program
  • Calculate the Area of Circle | Java Program
  • To Find Whether Given Year is a Leap Year or not
  • Popular
  • Recent
  • Archives

Total Pageviews

Sparkline

Followers

Popular Posts of This Week

  • Count the PDF Pages using Java
    To get number of pages in the PDF import java.io.*; import com.lowagie.text.pdf.PdfReader; public class PDFSize { //static String P...
  • To Sort an Interger Array using Shell Sort
    To Sort an Interger Array using Shell Sort class ShellSort { public static int[] shellSort(int[] array) { int N = array.length; ...
  • Send outlook meeting request using Java Mail API
    This Program is useful to send meeting request to the users using Java mail API.We need to include mail.jar in the classpath. import ja...
  • Java Program to Print Number in the Given Data Type
    Here is Java Program to print number given in the data types public class second{ public static void main(String[] args){ int n; ...
  • Power of Java Reflection API
     Reflection API is part of core java. This is the most powerful API that java has ever  produced. Reflection is the powerful technique a...
  • program to retrieve Method names of a class
    import java.lang.reflect.*; public class Refl6 { public static void main(String args[]) throws Exception { Class c=Class.forN...
  • Function to Check Given Date is Older Than 900 days
    The code snippet will results in a boolean using which we can identify that given date is older than 900 days or not. /** * @param arg...
  • Implementation of a basic generic tree, with labels of type T - Data Structure
    // This implements a basic generic tree, with labels of type T, // pointer to the parent node, and a singly linked list of children nodes...
  • Sending mail through java API
    if the SMTP host is connecting, then only we can send the mails. And more over API jars are necessary public void sendEmailCommPaymentD...
  • Barcodes Encoding Decoding Java Example
    General Overview of BarCodes and using them to encode and decode BitMatrix bitMatrix = null;// initialize bitMatrix = new PDF417Writer()....
Powered by Blogger.

Archives

  • ▼  2014 ( 4 )
    • ▼  August ( 4 )
      • Java program to create a Binary Heap and Perform v...
      • Create an Adjacency matrix Graph and perform Add a...
      • To Sort an Interger Array using Shell Sort
      • Sort an Integer array with Bucket Sort
  • ►  2013 ( 6 )
    • ►  August ( 1 )
    • ►  April ( 5 )
  • ►  2012 ( 673 )
    • ►  November ( 9 )
    • ►  October ( 223 )
    • ►  September ( 272 )
    • ►  August ( 2 )
    • ►  June ( 1 )
    • ►  February ( 67 )
    • ►  January ( 99 )
 

Our Blogs

  • Linux Tutorial
  • C Programming Tutorial

Labels

  • Agile Methodology ( 1 )
  • Algorithm ( 3 )
  • AntiSamy ( 1 )
  • Arithmetic Operation ( 1 )
  • Array Example ( 9 )
  • ArrayList Examples ( 11 )
  • Average an Array of Values ( 1 )
  • Barcode Example ( 1 )
  • Basic Java Programs ( 34 )
  • Bing API Example ( 2 )
  • BitSet Example ( 1 )
  • Boolean Example ( 1 )
  • Bouncy Castle API ( 1 )
  • Break Statement ( 2 )
  • BufferedReader Example ( 2 )
  • Calendar Example ( 1 )
  • Chart Generation Example ( 1 )
  • Command Line Argument ( 1 )
  • Comparator Example ( 1 )
  • Concatenation of String ( 1 )
  • Continue Statement ( 1 )
  • Control Structure ( 1 )
  • Copy File Example ( 1 )
  • CRC Example ( 1 )
  • CSV Example ( 6 )
  • Data Structure ( 5 )
  • Date Example ( 2 )
  • Directory Example ( 1 )
  • Do - While Loop Example ( 1 )
  • Domino Database ( 1 )
  • Email Example ( 8 )
  • Encryption Example ( 3 )
  • Excel Example ( 15 )
  • Factorial Example ( 1 )
  • File Upload Example ( 1 )
  • Find Roots of Quadratic Equation ( 1 )
  • FTP Example ( 2 )
  • Graph Examples ( 1 )
  • Greater between Two Numbers ( 1 )
  • GSON Library ( 1 )
  • HashMap Example ( 1 )
  • HashSet Example ( 1 )
  • Hello World Program ( 1 )
  • If Condition ( 2 )
  • Inner Class Example ( 1 )
  • iText Example ( 3 )
  • JAR File ( 1 )
  • JAVA Applet ( 1 )
  • Java Applications ( 1 )
  • Java AWT Example ( 9 )
  • Java Certification ( 1 )
  • Java Class Examples ( 15 )
  • Java Collection Example ( 1 )
  • Java Command Example ( 4 )
  • Java Constructor Examples ( 1 )
  • Java Currency Example ( 1 )
  • Java Database Example ( 3 )
  • Java Date and Time Example ( 3 )
  • Java DateFormat Example ( 3 )
  • Java Examples ( 2 )
  • Java Exception Example ( 5 )
  • Java File Example ( 22 )
  • Java GUI Example ( 1 )
  • Java Image Examle ( 3 )
  • Java Inheritance Example ( 3 )
  • Java Input Output Example ( 1 )
  • Java IO Example ( 3 )
  • Java Jar Example ( 1 )
  • Java JSON Example ( 3 )
  • Java Mail Examples ( 4 )
  • Java Map Example ( 5 )
  • Java MapReduce Example ( 2 )
  • Java MultiThreading Example ( 7 )
  • Java Network Example ( 9 )
  • Java Package ( 1 )
  • Java Programs ( 1 )
  • Java RMI ( 1 )
  • Java Robot Class Examples ( 2 )
  • Java Runtime Example ( 1 )
  • Java Swing Example ( 9 )
  • Java Util Example ( 1 )
  • Java Vector Example ( 4 )
  • Java Voice Example ( 1 )
  • Java Webservice Example ( 1 )
  • Java XML Example ( 3 )
  • Java Zip Class Examples ( 2 )
  • JDBC ( 9 )
  • JDK Version Comparison ( 1 )
  • JFrame Example ( 3 )
  • JOptionPane Dialog Example ( 1 )
  • JPanel Example ( 1 )
  • JSP Example ( 2 )
  • JSTL Example ( 1 )
  • jUnit Example ( 2 )
  • LinkedList Example ( 2 )
  • List Example ( 1 )
  • Long Variable ( 1 )
  • Lottery Nubmer ( 1 )
  • MD5 Hashing Example ( 3 )
  • Memory Management Example ( 1 )
  • Method Override ( 1 )
  • MIDI Sound ( 8 )
  • Module Operator Example ( 2 )
  • Multiplication Table ( 1 )
  • Observer Interface Example ( 1 )
  • Operator Example ( 5 )
  • Pagination ( 1 )
  • Palindrome Number ( 1 )
  • Pass By Reference Example ( 1 )
  • Pass By Value Example ( 1 )
  • PDF File Example ( 3 )
  • PDF Generation Example ( 4 )
  • Pre and Post Operator ( 2 )
  • Prime Number ( 3 )
  • Progress Bar Example ( 1 )
  • Property List Example ( 2 )
  • Random Function ( 7 )
  • Recursion Example ( 2 )
  • Regex Example ( 2 )
  • Remote Host Example ( 2 )
  • Robot Class ( 4 )
  • Searching Example ( 3 )
  • Slideshow ( 1 )
  • Sorting Example ( 7 )
  • SpringLayout Example ( 1 )
  • Stack Example ( 4 )
  • Static Variable ( 1 )
  • StreamTokenizer Example ( 2 )
  • String Example ( 19 )
  • Struts2 Example ( 1 )
  • Sum of Digits ( 1 )
  • Swap Two Numbers ( 1 )
  • Switch Case ( 3 )
  • Tapestry Components ( 1 )
  • Thumbnail Example ( 2 )
  • TimerTask Example ( 2 )
  • To Calculate Volume ( 1 )
  • To Check Armstrong Number ( 1 )
  • Tree Example ( 1 )
  • TreeMap Example ( 1 )
  • TreeSet Example ( 1 )
  • Two Dimensional Array Example ( 1 )
  • UUID ( 1 )
  • Validation Example ( 2 )
  • Variable Casting ( 1 )
  • While Loop ( 1 )
  • XML Parsing ( 7 )
  • XSS Attacks ( 1 )
  • Zip File ( 15 )

Popular Posts

  • Creating Dynamic Macro Enabled Excel by Java
    We can create a dynamic macro enabled excel by java: We need to create a excel sheet template with macro on server. we can copy the...
  • Java program to create a Binary Heap and Perform various operation
    A binary heap (min-heap) is a complete binary tree with elements from a partially ordered set, such that the element at every node is less ...
  • To Sort an Interger Array using Shell Sort
    To Sort an Interger Array using Shell Sort class ShellSort { public static int[] shellSort(int[] array) { int N = array.length; ...
  • Implementation of a basic generic tree, with labels of type T - Data Structure
    // This implements a basic generic tree, with labels of type T, // pointer to the parent node, and a singly linked list of children nodes...
  • Create an Adjacency matrix Graph and perform Add and Remove operation
    import java.util.ArrayList; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import...
  • Printing Table In java using While Loop
    Here is a Java Program to Print the Table public class Table { public static void main(String[] args) { int no = Integer.p...
  • Merge-Sort Algorithm implementation in JAVA
    Merge-Sort Function void MergeSort(int low, int high) // a[low : high] is a global array to be sorted. // Small(P) is true if there...
  • Sort an Integer array with Bucket Sort
    Here is a java program to Sort an Integer array with Bucket Sort class BucketSort { public int[] bucketSort(int[] array) { /...
  • Stack implemented as array - Data Structure
    // Stack implemented as array public class ArrayStack<T> { private T[] stack; private int numElements = 0; // points to s...
  • Java Program to Generate the Lottery Number between 1 to 49
     A lottery requires that you select six different numbers from the integers 1 to 49. Write a program to do this for you and generate five s...
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger