# Analogy between Binary Search Tree and Quicksort Algorithm

September 20, 2013 Leave a comment

Binary Search Tree(BST) and Quicksort Algorithm(QA) are similar in nature in all the factors. They have same time complexities and same number of comparisons at every insertion. If one finds the quicksort logic difficult to understand and remember then he can always remember BST and memorize QA logic. We will now see how QA algorithm can be seen as simple BST by looking at both the concepts individually.

**Binary Search Tree(BST)**

Binary Search Tree(BST) property is that every inserted node in the BST would be inserted to the left of its parent node if its less than the parent node value and inserted to the right of its parent node if its more.

Binary Search Tree (constructed from random input array)

Binary Search Tree (constructed from sorted input array)

**Complexity of BST: **Randomized input would lead to complete BST in which case the BST insertion would take O(logn) time complexity. And if the input is sorted in some order(ascending or descending) then its going to be the length of the array, i.e, O(n)

So for n inserts it would be O(nlogn) or O(n^2)

**Quicksort Algorithm**

Now we will look at quick sort logic

Plain Quicksort Algorithm

Quicksort algorithm with BST embedded

**Complexity of Quicksort Algorithm:** Randomized input would lead to O(logn) time complexity as seen in above diagram. And if the input is sorted in some order then its going to be length of the array, i.e, O(n)

So for n inserts it would be O(nlogn) or O(n^2)

## Recent Comments