Search code examples
javaalgorithmbig-opseudocode

What is the Big-O of this pseudo code? I need a proper explain also


This is the pseudo code that i want to calculate time complexity ,i think it is a binary search algorithm but i fail when calculating the complexity because it is reducing logarithamic.

   USE variables half-array,found,middle element
   SET half-array=initial array;
   SET found=True;

 Boolean SearchArray(half-array)

   find middle element in half-array;
   Compare search key with middle element;
   IF middle element==search key THEN
           SET found=True;
   ELSE
        IF search key< middle element THEN
          SET half-array=lower half of initial array;
        ELSE
          SET half-array=upper half of initial array;


 SearchArray(half-array)

Solution

  • It looks like you are running this method recursively, and with each iteration you are reducing the number of elements being searched by half. This is going to be a logarithmic reduction, i.e. O(log n).

    Since you are reducing your elements by half each time, you need to determine how many executions will be needed to reduce it to a single element, which this previous answer provides a proof or if you are a more visual person, you can use the following diagram from this response:

    enter image description here