Search code examples
algorithmsortingdata-structures

array vs binary search in different circumstances


I've been looking around binary search tree vs array and was curious if my assumptions were correct. So I will explain what I understand and you correct me if you think so. Let's also assume that we want to create a data structure that can:

Question : Though, the only difference is, with array, insert is more time consuming - i.e O(n) > O(log(n)). Other than that, specific element is found in the same time and biggest/smallest even in O(1). Is sorted array's insert time the reason why we decide to use binary search tree ? does O(n) really make that difference for us so that we switch to use binary search tree with O(log(n)) ?


Solution

  • Question 1: I'm wondering if my time complexities are written correctly. Thoughts ?

    In the tree representation, nothing prevents you from storing pointers to the min and max elements, so it can be O(1) depending on the implementation.

    Question 2: It turns out that I like the 2nd(sorted array) and 3rd(binary search) options the most.

    The bigger your dataset the bigger difference it makes, but O(log(N)) is usually way closer to 1 than to N:

    • When N is 1: N = 1 vs log(N) = 1
    • When N is 10: N = 10 vs log(N) = 4
    • When N is 1_000: N = 1000 vs log(N) = 10
    • When N is 1_000_000: N = 1000000 vs log(N) = 20
    • When N is 1_000_000_000: N = 10000000000 vs log(N) = 30