EN VI

Algorithm - array vs binary search in different circumstances?

2024-03-16 03:30:06
How to Algorithm - 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:

  1. give us biggest/smallest element from the set
  2. find if the specific element exists in the set.

Here're my time complexities.

// If you go with array and:
//   not sort it per each insert: then 
//      -- lookup:
//           biggest/smallest - O(n)
//           specific element - O(n)
//      -- insert O(1)
//   sort it per each insert: then
//      -- lookup: 
//           biggest/smallest - O(1)
//           specific element - O(log(n)) (using binary search)
//      -- insert: O(n)
// If you go with binary search tree:
//           biggest/smallest - O(log(n))
//           specific element - O(log(n))
//      -- insert log(n)

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

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

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
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login