why databases use trees to find data ??
because on disk, the cost of search is the number pages being read, not the number of comparisons. once the page is in memory, comparing keys inside it is very fast. but getting the page there is way slower than that.
starting with the most basic idea: binary search.
it works, but every steps reads a new page, so every step is a slow random read. a file of 10,000 pages needs about 14 of them in the worst case. and each read is mostly wasted: you read a whole page of keys, use one for the comparison, and throw the rest away.
now what happens if we play smart and use the rest.
to decide which page to open, you only need the first key of each page. write those down with their page numbers in a small separate file. that's an "index", way smaller than the data. it's sorted too, so index it again, and keep going until the top fits in one page.
what you've built is a tree (check the diagram).
at each page the search compares against every key in it to choose among all its children at once. one page read divides the search by the "fanout" (children per node), not by 2 (in case of binary tree).
to work out a real tree's height:
→ fanout = page size / (key size + pointer size)
→ height = how many times you multiply by the fanout to reach the key count
→ nodes are at least half full, so the worst case adds at most one level
the top part of the tree consists of exponentially lesser number of nodes, so it stays cached in memory.
challenge: as more keys come and go, the tree needs to keep it balanced, which is one of the most complex challenges.
takeaway: HIGH FANOUT, and LOW HEIGHT. that's why b-trees exist.
