Arjun Abhynav
Arjun Abhynav

Reputation: 543

Modified Binary Search Tree for Sorting?

I have to sort an array. Apart from the already existing types of sorting that exists, I was wondering if an algorithm like this would work out, and what its complexity might be.

I have an array to be sorted. I create a Binary Search Tree.

So if I insert all the elements of the array into the BST, and then assign them back to the array one by one when doing a in-order traversal of the tree, I will achieve a sorted result. (Though consuming more space complexity because of the tree nodes. Not in-place sorting.)

int i=0;

void sort_by_inorder(node *n)
{
    if(n==NULL)
    {
        return;
    }
    sort_by_inorder(n->leftchild);
    array[i++]=n->data;
    sort_by_inorder(n->rightchild);
}

I know a BST does not allow duplicate insertions, so maybe we could consider modifying the BST insertion algorithm into <= for the left sub-tree, or maybe >= for the right sub-tree.

Will this be a good implementation (workable)? What would be the complexity?

Traversal complexity is on an average O(n). And insertion is just O(log n). So this should, according to me, turn out to be an efficient algorithm.

Thanks.

Upvotes: 1

Views: 957

Answers (1)

Dino
Dino

Reputation: 1586

In a general binary search tree, the insertion time is actually O(n) in the worst case. You need a balanced tree for the operations to be O(log(n)).

So in a general BST, your approach allows you to sort in O(n^2).

Upvotes: 0

Related Questions