[Solved] Can’t understand binary search function [closed]


Here binary search is being used to find the optimal solution.For binary search you need a range represented by high and low.You know the optimal answer lies within this range.In this particular problem low is represented by the minimum number of folders that a worker will have to look for, which is going to be the maximum number of folders in a cabinet

int lo = *max_element( folders.begin(), folders.end() );

The high would be if only one worker is assigned all folders which would be sum of all values in folders

int hi = accumulate( folders.begin(), folders.end(), 0 );

Now you loop through this range and try to find the optimal answer.

 while ( lo < hi ) {
      int x = lo + (hi-lo)/2;

In each iteration of the loop you check the number of workers required if each worker was given maximum x folders.
You then decide the next range by checking if you were able to satisfy the constraint with x as solution and try to get more optimal solution

if ( required <= workers )
     hi = x;

If x is the solution, then i need required workers which is less than or equal to the workers, so i will try to get more optimal by having a lower value of maximum number of folders assigned to a worker.To do this you change the range to [lo,x]

 else
lo = x+1;

On the contrary if you need more workers than present, you will increase the range to [x+1,hi]

solved Can’t understand binary search function [closed]