-1

I have a sorted array, and a number, how many maximum comparisons should I do to find if the number is contained in the array ?

Suppose we have a million of numbers in the array.

serge
  • 13,940
  • 35
  • 121
  • 205

2 Answers2

1

To complete the answer from @aponeme, the maximum number of comparisons is equal to

2*upper(log2(n))

The reason is that the size of the array you examine is equal to

n, n/2, n/4, ...n/(2^steps). 

Then the maximum number of steps is such that

 n/(2^nsteps) = 1, i.e. nsteps = log2(n) 
Damien
  • 4,809
  • 4
  • 15
  • 20
  • finally, for the concrete scenario with a n = million, the maximum number of comparisions would be log2(1000000) = 20 – serge Oct 08 '20 at 22:02
0

With divide and Conquer or Binary search (pseudo - code):

  1. Split the array in half
  2. If number is bigger than max of first half work with the second half else work with first half
  3. Repeat step 1 - 2 with the remaining half

Worst case scenario: Need to divide into two arrays each of length 1 => O(logN)

apomene
  • 14,282
  • 9
  • 46
  • 72
  • I understand the algorithm, but the question is how much max comparisions should I perform – serge Sep 17 '20 at 13:49
  • You need to add the base case when you find the element, and the worst case when the elements don't appear in the list – Ayoub Omari Sep 17 '20 at 13:50
  • sorry, I am not expert in this. I have one million items 2, 4, ... 1 999 998, 2 000 000, i need to check if the element 1000 001 is in the list. How much comparations should I do, and why? – serge Sep 17 '20 at 13:55
  • @Siege refer to Damien last comment, I think it suffies – apomene Sep 17 '20 at 13:57
  • @apomene, please mention that answer in yours, in order I be able to mark it as answered – serge Sep 17 '20 at 13:59
  • @Serge your question is a little bit confusing. There is no such a thing you "should do". It's up to you, prior to the algorithm design, to fix your time complexity requirements. Also we only talk about Big-O notation to estimate the performance of the algorithm, there is no fixed number – Ayoub Omari Sep 17 '20 at 14:00
  • @quade: is 20 the answer, how is not a fixed number? – serge Sep 17 '20 at 14:26