Monday, February 4, 2019

Tree Sort in Java Using Binary Search Tree

In this post we’ll see how to write Tree sort program in Java. Tree sort is a sorting algorithm that uses the Binary Search tree data structure for sorting.

Binary Search tree

Binary tree is a tree structure where each node has a maximum of two children. A kind of binary tree used for Tree sorting is known as a Binary Search Tree (BST).

In Binary search tree for each node the node’s left child must have a value less than its parent node and the node’s right child must have a value greater than (or equal) its parent. If we consider the root node of the binary search tree the left subtree must have nodes with values less than the root node and the right subtree must have nodes with values greater than the root node.

binary search tree for tree sort

How does Tree sort work

To write a Tree sort program steps are as following.

  1. From the input array create a Binary search tree structure.
  2. Traverse the Binary search tree to get the elements in sorted order.
    • By doing an in-order traversal, which means starting from the left subtree, then the root node and then visit the right subtree, you can get the elements sorted in ascending order.
    • If you traverse in reverse order i.e. first visit the right subtree, then the root node and then the left subtree you can get the elements sorted in descending order.

Tree Sort Java program

To write a Java program for Tree sort you need-

  1. A node class representing each node in the binary search tree.
  2. A method to insert nodes in Binary search tree. Logic for inserting a new node to the Binary search tree goes as given below.
    • If new node’s value is less than the current node move to the left.
    • If new node’s value is greater than the current node move to the right.
    • When current node is null that means leaf node is reached. New node should be inserted in that position.
  3. A method to traverse the tree to get the elements in order.
class Node{
    int value;
    Node left;
    Node right;
    Node(int value){
        this.value = value;
        left = null;
        right = null;        
    }
}

class Tree{
    Node node;
    Tree(int value){
        node = new Node(value);
    }
    public Node insert(Node node, int value){
        if(node == null){
            return new Node(value);
        }
        // Move to the left if passed value is 
        // less than the current node
        if(value < node.value){
            node.left = insert(node.left, value);
        }
        // Move to the right if passed value is 
        // greater than the current node
        else if(value > node.value){
            node.right = insert(node.right, value);
        }
        return node;
    }
    
    // For traversing in order
    public void inOrder(Node node){
        if(node != null){
            inOrder(node.left);
            System.out.print(node.value + " ");
            inOrder(node.right);
        }
    }
    
    public void inOrderDesc(Node node){
        if(node != null){
            inOrderDesc(node.right);
            System.out.print(node.value + " ");
            inOrderDesc(node.left);
        }
    }
}

public class TreeSort {    
    public static void main(String[] args) {
        int[] arr = {50, 30, 70, 15, 7, 62, 22, 35, 87, 22, 31};
        System.out.println("Original array- "+Arrays.toString(arr));
        Tree tree = new Tree(arr[0]);
        for(int num : arr){
            tree.insert(tree.node, num);
        }
        System.out.println("Sorted Array (Ascending)- ");
        tree.inOrder(tree.node);
        System.out.println();
        System.out.println("Sorted Array (Descending)- ");
        tree.inOrderDesc(tree.node);
    }
}

Output

Original array- [50, 30, 70, 15, 7, 62, 22, 35, 87, 22, 31]
Sorted Array (Ascending)- 
7 15 22 30 31 35 50 62 70 87 
Sorted Array (Descending)- 
87 70 62 50 35 31 30 22 15 7 

Performance of tree sort

Average case time complexity of tree sort is O(nlogn), as insertion of an element in the Binary search tree takes O(logn) time so for n elements it is O(nlogn).

Space complexity of tree sort is O(n) as we need to create n nodes for n elements.

Recommendations for learning

  1. Java Programming Masterclass Course
  2. Java In-Depth: Become a Complete Java Engineer!
  3. Spring Framework Master Class Course
  4. Complete Python Bootcamp Course
  5. Python for Data Science and Machine Learning

That's all for this topic Tree Sort in Java Using Binary Search Tree. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Heap Sort Program in Java
  2. Selection Sort Program in Java
  3. Radix Sort Program in Java
  4. Find All Permutations of a Given String - Java Program
  5. Converting Numbers to Words - Java Program

You may also like-

  1. Connection Pooling Using C3P0 in Java
  2. Producer-Consumer Java Program Using ArrayBlockingQueue
  3. How to Create PDF in Java Using OpenPDF
  4. How to Write Excel File in Java Using Apache POI
  5. Heap Memory Allocation in Java
  6. Transient Keyword in Java With Examples
  7. Difference Between equals() Method And equality Operator == in Java
  8. Java Collections Interview Questions And Answers