This is the binary search algorithm from Wikipedia. It uses int type indexing. The use of the int type here is necessary because the algorithm sometimes uses the negative index values while searching.
int binary_search(unsigned array[], int length, unsigned needle) {
int l = 0, r = length - 1, m;
while (l <= r) {
m = (l + r) / 2;
if (array[m] < needle)
l = m + 1;
else if (array[m] > needle)
r = m - 1;
else
return m;
}
return -1;
}
How to modify this algorithm to use size_t (unsigned int) instead of int?
What is an optimal solution for this?
size_t binary_search(unsigned array[], size_t length, unsigned needle) {
size_t l = 0, r = length - 1, m;
???
return (size_t) -1;
}
We, beginners, should help each other.:)
Here you are.
As you specified the language tags C and C++ then the demonstration program below can be run in C and C++. That is there are no special features of C++ except using names
bool,falseandtruethat in C can be used if to include header<stdbool.h>Also in C you need to include header<stdio.h>instead of<iostream>The program output is
Pay attention to that in general in C++ you will need to write a template function while in C you will write the function similarly to the implementation of
bsearch.Without using the variable
foundthe function can look as