sorted array vs binary tree

Status
Not open for further replies.

erikengh

Ars Tribunus Militum
2,280
Both a sorted array and a binary tree can let you look up an element in log(N) time. However I would expect a sorted array to be faster in practice because of the constant factor. However inserting and removing elements should be faster. So when do you use sorted arrays and when do you used binary trees? Do you have any rules of thumb?

I guess that for small number of elements. Say 10-20, a sorted array will be all around faster?
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
Not if my elements are measured in megabytes.

Which in turn depends whether your language in question is putting them inline or via indirection (or your language lets you do either and which you choose)

which is a nit picky way of adding to exactly what DrPizza just said. It depends what you're doing.

Implement whichever one is easier to get correct first, then benchmark in the context of your needs.
since binary search on a sorted array is likely to be preimplemented as part of the standard library it is probable that using that route is the fastest to get up and running with.

If you really want to go with one over the other before perf testing then the only solid piece of advice I would give is that:
The difference between the array and tree based approach is likely to be nasty for arrays only when the memory copy cost of inserts/deletes become significant. Given that you can take a relatively simple 'guess' before hand on the basis of the array fitting in cache and the proportion of edits compared to reads.
This is very much a premature optimisation in many cases though
 
* binary tree has O(log(n)) lookups, inserts, and removals
* sorted array has O(log(n)) lookups and O(n) inserts and removals
* sorted array probably has lower coefficient for lookups, although we don't have enough info to be sure or by how much
* for sufficiently small input sizes, the difference in coefficients outweighs the difference in asymptotic complexity
* as DrPizza said, it's whether 10-20 elements is sufficiently small depends on the size of each element
 
Status
Not open for further replies.