Tree sort is a sorting algorithm that is based on Binary Search Tree data structure. It first creates a binary search tree from the elements of the input list or array and then performs an in-order traversal on the created binary search tree to get the elements in sorted order.
Algorithm:
- Step 1: Take the elements input in an array.
- Step 2: Create a Binary search tree by inserting data items from the array into the binary search tree.
- Step 3: Perform in-order traversal on the tree to get the elements in sorted order.
Applications of Tree sort:
- Its most common use is to edit the elements online: after each installation, a set of objects seen so far is available in a structured program.
- If you use a splay tree as a binary search tree, the resulting algorithm (called splaysort) has an additional property that it is an adaptive sort, which means its working time is faster than O (n log n) for virtual inputs.
Below is the implementation for the above approach:
C++
// C++ program to implement Tree Sort
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int key;
struct Node *left, *right;
};
// A utility function to create a new BST Node
struct Node *newNode(int item)
{
struct Node *temp = new Node;
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
// Stores inorder traversal of the BST
// in arr[]
void storeSorted(Node *root, int arr[], int &i)
{
if (root != NULL)
{
storeSorted(root->left, arr, i);
arr[i++] = root->key;
storeSorted(root->right, arr, i);
}
}
/* A utility function to insert a new
Node with given key in BST */
Node* insert(Node* node, int key)
{
/* If the tree is empty, return a new Node */
if (node == NULL) return newNode(key);
/* Otherwise, recur down the tree */
if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);
/* return the (unchanged) Node pointer */
return node;
}
// This function sorts arr[0..n-1] using Tree Sort
void treeSort(int arr[], int n)
{
struct Node *root = NULL;
// Construct the BST
root = insert(root, arr[0]);
for (int i=1; i<n; i++)
root = insert(root, arr[i]);
// Store inorder traversal of the BST
// in arr[]
int i = 0;
storeSorted(root, arr, i);
}
// Driver Program to test above functions
int main()
{
//create input array
int arr[] = {5, 4, 7, 2, 11};
int n = sizeof(arr)/sizeof(arr[0]);
treeSort(arr, n);
for (int i=0; i<n; i++)
cout << arr[i] << " ";
return 0;
}
Java
// Java program to
// implement Tree Sort
class GFG
{
// Class containing left and
// right child of current
// node and key value
class Node
{
int key;
Node left, right;
public Node(int item)
{
key = item;
left = right = null;
}
}
// Root of BST
Node root;
// Constructor
GFG()
{
root = null;
}
// This method mainly
// calls insertRec()
void insert(int key)
{
root = insertRec(root, key);
}
/* A recursive function to
insert a new key in BST */
Node insertRec(Node root, int key)
{
/* If the tree is empty,
return a new node */
if (root == null)
{
root = new Node(key);
return root;
}
/* Otherwise, recur
down the tree */
if (key < root.key)
root.left = insertRec(root.left, key);
else if (key > root.key)
root.right = insertRec(root.right, key);
/* return the root */
return root;
}
// A function to do
// inorder traversal of BST
void inorderRec(Node root)
{
if (root != null)
{
inorderRec(root.left);
System.out.print(root.key + " ");
inorderRec(root.right);
}
}
void treeins(int arr[])
{
for(int i = 0; i < arr.length; i++)
{
insert(arr[i]);
}
}
// Driver Code
public static void main(String[] args)
{
GFG tree = new GFG();
int arr[] = {5, 4, 7, 2, 11};
tree.treeins(arr);
tree.inorderRec(tree.root);
}
}
// This code is contributed
// by Vibin M
Python3
# Python3 program to
# implement Tree Sort
# Class containing left and
# right child of current
# node and key value
class Node:
def __init__(self,item = 0):
self.key = item
self.left,self.right = None,None
# Root of BST
root = Node()
root = None
# This method mainly
# calls insertRec()
def insert(key):
global root
root = insertRec(root, key)
# A recursive function to
# insert a new key in BST
def insertRec(root, key):
# If the tree is empty,
# return a new node
if (root == None):
root = Node(key)
return root
# Otherwise, recur
# down the tree
if (key < root.key):
root.left = insertRec(root.left, key)
elif (key > root.key):
root.right = insertRec(root.right, key)
# return the root
return root
# A function to do
# inorder traversal of BST
def inorderRec(root):
if (root != None):
inorderRec(root.left)
print(root.key ,end = " ")
inorderRec(root.right)
def treeins(arr):
for i in range(len(arr)):
insert(arr[i])
# Driver Code
arr = [5, 4, 7, 2, 11]
treeins(arr)
inorderRec(root)
# This code is contributed by shinjanpatra
C#
// C# program to
// implement Tree Sort
using System;
public class GFG
{
// Class containing left and
// right child of current
// node and key value
public class Node
{
public int key;
public Node left, right;
public Node(int item)
{
key = item;
left = right = null;
}
}
// Root of BST
Node root;
// Constructor
GFG()
{
root = null;
}
// This method mainly
// calls insertRec()
void insert(int key)
{
root = insertRec(root, key);
}
/* A recursive function to
insert a new key in BST */
Node insertRec(Node root, int key)
{
/* If the tree is empty,
return a new node */
if (root == null)
{
root = new Node(key);
return root;
}
/* Otherwise, recur
down the tree */
if (key < root.key)
root.left = insertRec(root.left, key);
else if (key > root.key)
root.right = insertRec(root.right, key);
/* return the root */
return root;
}
// A function to do
// inorder traversal of BST
void inorderRec(Node root)
{
if (root != null)
{
inorderRec(root.left);
Console.Write(root.key + " ");
inorderRec(root.right);
}
}
void treeins(int []arr)
{
for(int i = 0; i < arr.Length; i++)
{
insert(arr[i]);
}
}
// Driver Code
public static void Main(String[] args)
{
GFG tree = new GFG();
int []arr = {5, 4, 7, 2, 11};
tree.treeins(arr);
tree.inorderRec(tree.root);
}
}
// This code is contributed by Rajput-Ji
JavaScript
<script>
// Javascript program to
// implement Tree Sort
// Class containing left and
// right child of current
// node and key value
class Node {
constructor(item) {
this.key = item;
this.left = this.right = null;
}
}
// Root of BST
let root = new Node();
root = null;
// This method mainly
// calls insertRec()
function insert(key) {
root = insertRec(root, key);
}
/* A recursive function to
insert a new key in BST */
function insertRec(root, key) {
/* If the tree is empty,
return a new node */
if (root == null) {
root = new Node(key);
return root;
}
/* Otherwise, recur
down the tree */
if (key < root.key)
root.left = insertRec(root.left, key);
else if (key > root.key)
root.right = insertRec(root.right, key);
/* return the root */
return root;
}
// A function to do
// inorder traversal of BST
function inorderRec(root) {
if (root != null) {
inorderRec(root.left);
document.write(root.key + " ");
inorderRec(root.right);
}
}
function treeins(arr) {
for (let i = 0; i < arr.length; i++) {
insert(arr[i]);
}
}
// Driver Code
let arr = [5, 4, 7, 2, 11];
treeins(arr);
inorderRec(root);
// This code is contributed
// by Saurabh Jaiswal
</script>
Complexity Analysis:
Average Case Time Complexity: O(n log n) Adding one item to a Binary Search tree on average takes O(log n) time. Therefore, adding n items will take O(n log n) time
Worst Case Time Complexity: O(n2). The worst case time complexity of Tree Sort can be improved by using a self-balancing binary search tree like Red Black Tree, AVL Tree. Using self-balancing binary tree Tree Sort will take O(n log n) time to sort the array in worst case.
Auxiliary Space: O(n)
Similar Reads
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to Sorting Techniques Sorting refers to rearrangement of a given array or list of elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of elements in the respective data structure.Why Sorting Algorithms are ImportantSorting algorithms are essential in Comput
15+ min read
Most Common Sorting Algorithms
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
12 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Heap Sort - Data Structures and Algorithms Tutorials Heap sort is a comparison-based sorting technique based on Binary Heap Data Structure. It can be seen as an optimization over selection sort where we first find the max (or min) element and swap it with the last (or first). We repeat the same process for the remaining elements. In Heap Sort, we use
14 min read
Counting Sort - Data Structures and Algorithms Tutorials Counting Sort is a non-comparison-based sorting algorithm. It is particularly efficient when the range of input values is small compared to the number of elements to be sorted. The basic idea behind Counting Sort is to count the frequency of each distinct element in the input array and use that info
7 min read