Linear search arrays [closed]
开发者_C百科
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this questionHow do I print multiple searches from a linear search in C?
for (i=0; i < index; i++)
if (array[i] == target)
return i;
Is it possible to return more then one value, say, if the array has multiple elements that equals the target?
You could go to the trouble of allocating a dynamic array within the function but that's probably something better left to the caller to manage.
I would change the function from something like:
int findVal (int *array, int size, int val) {
for (int i = 0; i < size; i++)
if (array[i] == val)
return i;
return -1;
}
to one that allowed you to specify a starting point (or, more precisely, one less than the starting point):
int findVal (int *array, int size, int last, int val) {
for (int i = last + 1; i < size; i++)
if (array[i] == val)
return i;
return -1;
}
then let your client call it with:
int index = findVal (myarray, sizeof(myarray)/sizeof(*myarray), -1, myval);
while (index != -1) {
// Do something with index.
index = findVal (myarray, sizeof(myarray)/sizeof(*myarray), index, myval);
}
If your client wants it in an array, they can put it in an array. But, if they just want to do something ephemeral (like just print the index then forget about it), it makes little sense to waste an array for that.
Instead of returning matching elements, you could print out their index values (allowing multiple values to be printed) or insert them into an array and then return that.
精彩评论