How I can get the number of iterations of binary search?
This is my code:
int main()
{
int target = 11;
int N = 10;
std::vector<int> index;
int num;
for (int i = 0; i < N; i++) {
index.push_back(i);
}
int counter = 0;
unsigned int M, L = (unsigned int)-1, R = N;
M = (R - L) / 2; // Assume N is not zero
do {
int value;
M = M + L;
value = index[M];
if (value < target) L = M; else R = M;
M = (R - L) / 2;
counter++;
} while (M); // M is the size of the current interval
std::cout << R << '\n';
std::cout << "counter: " << counter << '\n';
system("pause");
return 0;
}
I want to know the number of iterations depending on N
.
I know how this algorithm works but I want the number of iterations
represented mathematically.