skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Wednesday, August 13, 2014

Java program to create a Binary Heap and Perform various operation

Posted by Happy Coder at 3:27 PM – 0 comments
 
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 than (or equal to) the the element at it's left and right child.

This Binary Heap is a min-heap implemented with one-based array (root is element 1; children of element n are elements 2n and 2n+1) for simplicity.

Complexity: Space O(n), findMin O(1), insert O(logn), deleteMin O(logn), buildHeap O(n);

class BinaryHeap {

 private int nodes[];
 private int size;
 private int capacity;
 

 public BinaryHeap(int capacity) {
  this.size = 0;
  this.capacity = capacity;
  this.nodes = new int[capacity + 1];
 }

 public int size() {
  return size;
 }

 public int findMin() {
  if (size <= 0) {
   throw new RuntimeException("Empty Heap is empty.");
  }
  return nodes[1];
 }

 public void insert(int e) {
  if (size >= capacity) {
   throw new RuntimeException("Heap overflow.");
  }

  size++;
  nodes[size] = e;
  percolateUp();
 }

 public int deleteMin() {
  if (size <= 0) {
   throw new RuntimeException("Empty Heap is empty.");
  }
  int min = findMin();
  nodes[1] = nodes[size];
  size--;
  percolateDown();
  return min;
 }

 private void percolateDown() {
  int index = 1;
  while (true) {
   int child = index * 2;
   if (child > size)
    break;
   if (child + 1 <= size) {
    // if there are two children -> take the smallest or
    // if they are equal take the left one
    child = findMin(child, child + 1);
   }
   if (nodes[index] <= nodes[child])
    break;
   swap(index, child);
   index = child;
  }
 }

 private void percolateUp() {
  int index = size();
  while (index > 1) {
   int parent = index / 2;
   if (nodes[index] >= nodes[parent])
    break;
   swap(index, parent);
   index = parent;
  }
 }

 private void swap(int i, int j) {
  int temp = nodes[i];
  nodes[i] = nodes[j];
  nodes[j] = temp;
 }

 private int findMin(int leftChild, int rightChild) {
  if (nodes[leftChild] <= nodes[rightChild]) {
   return leftChild;
  } else {
   return rightChild;
  }
 }
 
 public static void main(String[] args) {
  BinaryHeap bh = new BinaryHeap(10);
  bh.insert(7);
  bh.insert(5);
  bh.insert(9);
  bh.insert(6);
  bh.insert(4);
  bh.insert(8);
  bh.insert(10);
  bh.insert(1);
  bh.insert(3);
  bh.insert(2);
  
  System.out.println("Size of Binary Heap is : " + bh.size());

  System.out.println("Delete min from Binary Heap : " + bh.deleteMin());
  System.out.println("Size of Binary Heap is : " + bh.size());

  System.out.println("Delete min from Binary Heap : " + bh.deleteMin());
  System.out.println("Size of Binary Heap is : " + bh.size());
 }
 
}

Output of this Program
Size of Binary Heap is : 10
Delete min from Binary Heap : 1
Size of Binary Heap is : 9
Delete min from Binary Heap : 2
Size of Binary Heap is : 8

Try this by Yourself : http://ideone.com/FnSiPv
[ Read More ]
Read more...

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, August 11, 2014

To Sort an Interger Array using Shell Sort

Posted by Happy Coder at 4:37 PM – 0 comments
 
To Sort an Interger Array using Shell Sort

class ShellSort {

    public static int[] shellSort(int[] array) {
  int N = array.length;
  
  // determine the initial h value
  int h = 1;
     while (h < N / 3) 
      h = 3 * h + 1; // 1, 4, 13, 40, 121, 364, 1093, ...
     
     while (h >= 1) {
      // h-sort the array
      for (int i = h; i < array.length; i++) {
       // do insertion sort for h-sized array
       for (int j = i; j >= h && array[j] < array[j - h]; j -= h)
        swap(array, j, j - h);
      }
      
      h = h / 3; // reverse the h-size
     }
     
     return array;
 }
 
 /*
  * swaps data elements between 2 indexes of an array
  */
 private static void swap(int[] array, int i, int j) {
  int temp = array[i];
  array[i] = array[j];
  array[j] = temp;
 } 
    
    public static void  main(String args[]){
     ShellSort sSort = new ShellSort();
     int[] array = { 77, 99, 44, 55, 22, 88, 11, 0, 66, 33 };
     int[] sortedArray = sSort.shellSort(array);
     for (int i = 0; i < array.length; i++)
         System.out.println(sortedArray[i]);
     
    }
}

Output of the Program : 
0
11
22
33
44
55
66
77
88
99

Try it by yourself here : http://ideone.com/veRv5P
[ Read More ]
Read more...

Sort an Integer array with Bucket Sort

Posted by Happy Coder at 4:29 PM – 0 comments
 
Here is a java program to Sort an Integer array with Bucket Sort

class BucketSort {

    public int[] bucketSort(int[] array) {
        // create an array the size of the largest value + 1
        int[] bucket = new int[100];   

        // for every value in array, increment its corresponding bucket
        for (int i = 0; i < array.length; i++)
            bucket[array[i]]++;

        int outPos = 0;
        for (int i = 0; i < bucket.length; i++) { 
         if (bucket[i] > 0)
             array[outPos++] = i;
        }
        
        return array;
    }
    
    public static void  main(String args[]){
     BucketSort bSort = new BucketSort();
     int[] array = { 77, 99, 44, 55, 22, 88, 11, 0, 66, 33 };
     int[] sortedArray = bSort.bucketSort(array);
     for (int i = 0; i < array.length; i++)
         System.out.println(sortedArray[i]);
     
    }
}

Output of the Program :
0
11
22
33
44
55
66

Try By Yourself Here : http://ideone.com/OpHXmH
[ Read More ]
Read more...
Thursday, August 15, 2013

Merge-Sort Algorithm implementation in JAVA

Posted by Admin at 10:10 AM – 0 comments
 
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 is only one element to
   // sort. In this case the list is already sorted.
   {
       if (low < high) { // If there are more than one element
              // Divide P into subproblems.
              // Find where to split the set.
              int mid = (low + high)/2;
              // Solve the subproblems.
              MergeSort(low, mid);
              MergeSort(mid + 1, high);
              // Combine the solutions.
              Merge(low, mid, high);
       }
   }

   void Merge(int low, int mid, int high)
   // a[low:high] is a global array containing two sorted
   // subsets in a[low:mid] and in a[mid+1:high]. The goal
   // is to merge these two sets into a single set residing
   // in a[low:high]. b[] is an auxiliary global array.
   {
       int h = low, i = low, j = mid+1, k;
       while ((h <= mid) && (j <= high)) {
          if (a[h] <= a[j]) { b[i] = a[h]; h++; }
          else { b[i] = a[j]; j++; } i++;
       }
       if (h > mid) for (k=j; k<=high; k++) {
                       b[i] = a[k]; i++;
                    }
       else for (k=h; k<=mid; k++) {
               b[i] = a[k]; i++;
            }
       for (k=low; k<=high; k++) a[k] = b[k];
   }


Merge Sort Java Code :
import java.util.*;

public class MergeSort {
 public int a[] = new int[50];

 public void merge_sort(int low, int high) {
  int mid;
  if (low < high) {
   mid = (low + high) / 2;
   merge_sort(low, mid);
   merge_sort(mid + 1, high);
   merge(low, mid, high);
  }
 }

 public void merge(int low, int mid, int high) {
  int h, i, j, k;
  int b[] = new int[50];
  h = low;
  i = low;
  j = mid + 1;

  while ((h <= mid) && (j <= high)) {
   if (a[h] <= a[j]) {
    b[i] = a[h];
    h++;
   } else {
    b[i] = a[j];
    j++;
   }
   i++;
  }
  if (h > mid) {
   for (k = j; k <= high; k++) {
    b[i] = a[k];
    i++;
   }
  } else {
   for (k = h; k <= mid; k++) {
    b[i] = a[k];
    i++;
   }
  }
  for (k = low; k <= high; k++)
   a[k] = b[k];
 }

 public MergeSort() {
  int num, i;

  System.out.println("             MERGE SORT PROGRAM            ");

  System.out.println();
  System.out.println();
  System.out
    .println("Please Enter THE No. OF ELEMENTS you want to sort[THEN PRESS ENTER]:");
  num = new Scanner(System.in).nextInt();
  System.out.println();
  System.out.println("Now, Please Enter the (" + num
    + ") nos. [THEN PRESS ENTER]:");
  for (i = 1; i <= num; i++) {
   a[i] = new Scanner(System.in).nextInt();
  }
  merge_sort(1, num);
  System.out.println();
  System.out.println("So, the sorted list (using MERGE SORT) will be :");
  System.out.println();
  System.out.println();

  for (i = 1; i <= num; i++)
   System.out.print(a[i] + "    ");

 }

 public static void main(String[] args) {
  new MergeSort();
 }
}
[ 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...
Older Posts
Subscribe to: Posts ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger