In: Computer Science
In a database, items that are stored aren't usually sorted. This means that if you're looking for "Machine Gun Kelly" and you're currently at "Kanye West", it's not guaranteed that "Machine Gun Kelly" will follow "Kanye West". Thus, the search time in a non-indexed database is linear in the size of the input because in the worst case, you will have to scan for each and every entry to find "Machine Gun Kelly".
But, if we switch to a red-black tree or 2-4 tree
implementation, i.e we index the database, we can achieve
logarithmic time complexity ()
in terms of n (size of the input). The worst-case height of a
red-black tree is
which means that the search would take logarithmic time. The tree
traversal is a very efficient operation in an indexed DB, because
it works near-instantly, even if the size of n is very large. A
tree of n = 10,000 nodes will have a depth of 26.5757132836 (= 27
approx) in case of a RB tree. Whereas, if it is stored as a skewed
Binary Search Tree, it will have a depth of 10,000 (which is huge).
You can yourself notice the speedup when we shift to a RB tree
implementation (because it is height-balanced).
If you liked this answer, please give a thumbs-up rating. Feel free to comment if you need any explanations/clarifications regarding the same. Thanks for asking :)