Monday, 16 November 2015

Selection Sort in Java

Selection Sort

The selection sort is a combination of searching and sorting.

During each pass, the unsorted element with the smallest (or largest) value is moved to its proper position in the array. The number of times the sort passes through the array is one less than the number of items in the array.

The algorithm divides the input list into two parts:

1.Sublist of items already sorted, which is built up from left to right at the front (left) of the list, and

2. Sublist of items remaining to be sorted that occupy the rest of the list.

Steps:

Initially, the sorted sublist is empty and the unsorted sublist is the entire input list.

1. Find the smallest/largest (depending on sorting order) element in the unsorted sublist.

2. Exchanging (swapping) it with the leftmost unsorted element (putting it in sorted order).

3. Moving the sorted sublist boundaries one element to the right.

4. Repeat steps 3 and 4.

Example:

This is the initial, starting state of the array
Where the initial sorted left sublist is empty.

65 38 22 25 14

14 65 38 22 25 // sorted sublist = {14}

14 22 65 38 25 // sorted sublist = {14, 22}

14 22 25 65 38 // sorted sublist = {14, 22, 25}

14 22 25 38 65 // sorted sublist = {14, 22, 25, 38}

14 22 25 38 65 // sorted sublist = {14, 22, 25, 38, 65}

SelectionSort.java


public class SelectionSort {
      public static void main(String[] args) {
            int[] array = {64, 25, 12, 22, 11};
            SelectionSort.sort(array);
            SelectionSort.printArr(array);
      }
      private static void sort(int array[]) {
            int n = array.length;
            int idx,idxSorted;
            // idxSorted: List sorted till this index
           
            int iMin; // Min element index.

            for (idxSorted = 0; idxSorted < n-1; idxSorted++) {
                /* find the min element in the unsorted array[j .. n-1] */

                /**Min index is the first element of unsorted list(default)*/
                iMin = idxSorted;
               
                for ( idx = idxSorted+1; idx < n; idx++) {
                    /**
                     * Find minimum element index in Unsorted List.
                     * Update the Minimum element index.
                     */
                    if (array[idx] < array[iMin]) {
                        iMin = idx;
                    }
                }
               
                if(iMin != idxSorted) {
                  /** swap(array[j]<-->array[iMin]) */
                  int temp = array[idxSorted];
                  array[idxSorted] = array[iMin];
                  array[iMin] = temp;
                }
            }
      }
     
      private static void printArr(int[] array) {
            StringBuffer sb = new StringBuffer();
            for (int i : array) {
                  sb.append(i).append(" ");
            }
            System.out.println(sb.toString());
      }
}
Output:
11 12 22 25 64

static classes in Java

static classes

A static class is a class declared as a static member of another class.

1. It can access static data members of outer class even including private.

2. Static nested class cannot access non-static (instance) data member or method.

class Outer { 

      private String instanceVar = "instance varibale";

      private static String staticVar = "static varibale";
      static class Inner { 
          void print() {
             System.out.println("Inside the inner class "+staticVar);

             // Cannot make a static reference to the non-static field
             // System.out.println("Inside the inner class "+instanceVar);
          }
      }
}

public class TestStaticInner {
      public static void main(String[] args) { 
            Outer.Inner obj = new Outer.Inner();
            obj.print();
      }
}

When to use nested static class in Java?

The static class is useful when the single resource is shared between all instances and generally we do this for utility classes which are required by all components and which itself doesn't have any state.

JDK usage

Map.Entry is the static inner class.

Java static nested class with static method

If you have the static member inside static nested class, you don't need to create instance of static nested class.

class Outer { 
      private String instanceVar = "instance varibale";
      private static String staticVar = "static varibale";

      static class Inner { 
          static void print() {
             System.out.println("Inside the inner class "+staticVar);
          }
      }
}

public class TestStaticInner {
      public static void main(String[] args) {
           //Method accessed without creating object static nested class
           Outer.Inner.print();
      }
}

Sunday, 15 November 2015

Delete a Node in Binary Search Tree (BST)

Deletion in BST:

1) Node to be deleted is leaf:
  Simply remove from the tree.
              80                                    80
           /     \         delete(50)     /   \
          60      100       --------->   60     100
         /  \    /  \                          \      /  \
       50   70  90   110                    70   90   110

2) Node to be deleted has only one child:
  Swap the child to the node and delete the new child.

              80                                     80
           /     \         delete(60)      /   \
          60      100       --------->     70     100
            \    /  \                                 /  \
            70  90   110                           90   110

3) Node to be deleted has both children:
 A. Find inorder successor of the node.
 B. Copy contents of the inorder successor to the node and delete the inorder successor.   
     (Inorder predecessor can also be used).

              80                                     90
           /     \         delete(80)      /   \
          70      100       --------->     70    100
                  /   \                                      \
                90   110                                     110

Note: Inorder successor is needed only when right child is not empty.
Inorder successor can be obtained as the minimum value in right sub tree of the node.

Binary Search Tree implementation in Java

Binary Tree:
A binary tree is a tree data structure in which each node has at most two children, which are referred to as the left child and the right child.

Binary Search Tree:
BST is a type of Binary tree in which left Nodes smaller than parent and right Nodes are greater than parent.

Operations
Complexity
Insert
O(lgn)

Contains
O(lgn)

Delete
O(lgn)

Display
O(n).


contains(int n):

     public boolean contains(intid) {
           Node current = root;
           while(current!=null) {
                if(current.data==id) {
                     return true;
                } elseif(current.data>id) {
                     current = current.left;
                } else{
                     current = current.right;
                }
           }
           return false;
     }

insert(int n):

       public void insert(int element) {
           Node newNode = newNode(element);
           /** No element in the BST. */
           if(root==null) {
                root = newNode;
                return;
           }
           Node current = root;
           Node parent = null;
           while(true) {
                parent = current;
                /** find the leaf Node where element will be insert.*/
                if(element<current.data) {                
                     current = current.left;
                     /** Insert the element at the leaf. */
                     if(current==null) {
                           parent.left = newNode;
                           return;
                     }
                } else{
                     current = current.right;
                     /** Insert the element at the leaf. */
                     if(current==null) {
                           parent.right = newNode;
                           return;
                     }
                }
           }
     }

Deletion in BST:

1) Node to be deleted is leaf:
  Simply remove from the tree.
              80                                    80
           /     \         delete(50)     /   \
          60      100       --------->   60     100
         /  \    /  \                          \      /  \
       50   70  90   110                    70   90   110

2) Node to be deleted has only one child:
  Swap the child to the node and delete the new child.

              80                                     80
           /     \         delete(60)      /   \
          60      100       --------->     70     100
            \    /  \                                 /  \
            70  90   110                           90   110

3) Node to be deleted has both children:
 A. Find inorder successor of the node.
 B. Copy contents of the inorder successor to the node and delete the inorder successor.   
     (Inorder predecessor can also be used).

              80                                     90
           /     \         delete(80)      /   \
          70      100       --------->     70    100
                  /   \                                      \
                90   110                                     110

Note: Inorder successor is needed only when right child is not empty.
Inorder successor can be obtained as the minimum value in right sub tree of the node.


Binary search tree Implementation:

class Node {
     intdata;
     Node left;
     Node right;    
     public Node(int data) {
           this.data = data;
           left = null;
           right = null;
     }
    
     public String toString() {
           return "left :" + left +" right:"+right;
     }
}

/**
 * Binary search tree implementation.
 */
public class BST {

     public Node root;

     public BST() {
           this.root = null;
     }

     public boolean contains(intid) {
           Node current = root;
           while(current!=null){
                if(current.data==id) {
                     return true;
                } elseif(current.data>id) {
                     current = current.left;
                } else{
                     current = current.right;
                }
           }
           return false;
     }

     /**
      * Functions to delete data.
      **/
     public boolean delete(int id) {
           Node parent = root;
           Node current = root;
           boolean isLeftChild = false;
           while(current.data!=id){
                parent = current;
                if(current.data>id) {
                     isLeftChild = true;
                     current = current.left;
                } else{
                     isLeftChild = false;
                     current = current.right;
                }

                if(current==null) {
                     return false;
                }
           }

           /**
            * Case 1: if node to be deleted has no children
            */
           if(current.left==null&& current.right==null) {
                if(current==root) {
                     root = null;
                }
                if(isLeftChild ==true) {
                     parent.left = null;
                } else{
                     parent.right = null;
                }
           }

           /**
            * Case 2 : if node to be deleted has only one child
            */
           elseif(current.right==null) {
                if(current==root) {
                     root = current.left;
                } elseif(isLeftChild) {
                     parent.left = current.left;
                } else{
                     parent.right = current.left;
                }
           } elseif(current.left==null) {
                if(current==root) {
                     root = current.right;
                } elseif(isLeftChild) {
                     parent.left = current.right;
                } else{
                     parent.right = current.right;
                }
           }
           /**
            * Node to be deleted has two children.
            * Find inorder successor of the node.
            * Copy contents of the inorder successor to the node and
            * delete the inorder successor.
            * Note that inorder predecessor can also be used.
            **/

           elseif(current.left!=null && current.right!=null) {

                //To found the minimum element in the right sub tree.
                Node successor = getSuccessor(current);
                if(current==root) {
                     root = successor;
                } elseif(isLeftChild) {
                     parent.left = successor;
                } else{
                     parent.right = successor;
                }              
                successor.left = current.left;
           }         
           return true;        
     }

     private Node getSuccessor(Node deleleNode) {
           Node successsor = null;
           Node successsor_P = null;
           Node current = deleleNode.right;
           while(current!=null) {
                successsor_P = successsor;
                successsor = current;
                current = current.left;
           }
          
           /**
            * Check if successor has the right child,
            *      It cannot have left child for sure
            * If it does have the right child,
            *      add it to the left of successor_P.
            */
           if(successsor != deleleNode.right) {
                successsor_P.left = successsor.right;
                successsor.right = deleleNode.right;
           }
           return successsor;
     }

     public void insert(int element) {
           Node newNode = newNode(element);
           /** No element in the BST. */
           if(root==null) {
                root = newNode;
                return;
           }
           Node current = root;
           Node parent = null;
           while(true) {
                parent = current;
                /** find the leaf Node where element will be insert.*/
                if(element<current.data) {                
                     current = current.left;
                     /** Insert the element at the leaf. */
                     if(current==null) {
                           parent.left = newNode;
                           return;
                     }
                } else{
                     current = current.right;
                     /** Insert the element at the leaf. */
                     if(current==null) {
                           parent.right = newNode;
                           return;
                     }
                }
           }
     }

     /**
      * print all the elements in the In-Order.
      */
     public void display(Node root) {
           if(root!=null) {
                display(root.left);
                System.out.print(" " + root.data);
                display(root.right);
           }
     }
}

Test Binary search tree Implementation:



public class TestBST {
     public static void main(String arg[]) {
           BST bst = newBST();
           bst.insert(80);bst.insert(60);
           bst.insert(50);bst.insert(70);
           bst.insert(100);bst.insert(90);
           bst.insert(110);

           System.out.println("Original Tree : ");
           bst.display(bst.root);

           System.out.println("\n1)Node to be deleted is leaf:" +
                                              bst.delete(50));
           bst.display(bst.root);
          
           System.out.println("\n2)Node to be deleted has only
                                one child:" + bst.delete(60));
           bst.display(bst.root);
          
           System.out.println("\n3) Node to be deleted has both
                                children" + bst.delete(80));
           bst.display(bst.root);
     }
}

Output:
      Original Tree :
      50 60 70 80 90 100 110
      
      1) Node to be deleted is leaf:true
      60 70 80 90 100 110
    
      2) Node to be deleted has only one child:true
      70 80 90 100 110
    
      3) Node to be deleted has both childrentrue
      70 90 100 110
Related Posts Plugin for WordPress, Blogger...