these two method can only search the first element you want to find, but if there's 2 or more same elements you want to find, and store them, what should I do? Am I right think that?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
void binarySearch(int array[], int size, int key) {
int low = 0;
int high = size - 1;
int mid;
// how I can create an array to store the result? it's size is what?
while(low <= high) {
mid = (high-low)/2;
if(key == array[mid])
// what should I do??
elseif(key > array[mid])
low = mid + 1;
else
high = mid - 1;
}
}
void binarySearch(int result_array[], int *result_size, int array[], int size, int key) {
int r_size = (*result_size); // On input: You need to know how many items can be stored
(*result_size) = 0; // On output: How many items you actually did store
int low = 0;
int high = size - 1;
int mid;
// how I can create an array to store the result? it's size is what?
while(low <= high) {
mid = (high-low)/2;
if(key == array[mid])
// what should I do??
{
if((*result_size) < r_size)
result_array[*result_size] = array[mid];
++(*result_size);
}
elseif(key > array[mid])
low = mid + 1;
else
high = mid - 1;
}
}