I'm trying to use recursion to find the minimum integer in an array.
This is my code:
int minArray(int* array, int size){
if (size == 0){
return array[0];
}
int min = array[0];
if (min > minArray(array+1,size-1)){
min = minArray(array+1,size-1);
}
return min;
}
What is wrong with it? If i call the function on {1,2,3,4,5}, it will return 0.
The condition is wrong. An array of zero elements has no elements, so accessing array[0]
of it is illegal.
Also calling the function twice in this function should be avoided.
Try this:
int minArray(int* array, int size){
if (size == 1){
return array[0];
}
int min = array[0];
int candidate = minArray(array+1,size-1);
if (min > candidate){
min = candidate;
}
return min;
}
This solution is similar to the one of @MikeCat. I added the iterative version just for comparison purposes.
int min( int str[], int size)
{
if (1==size) // base case
return str[0];
else {
int minor=min(&str[1],size-1); // each time the function is called its receives an array with an element less than the previous call.
return str[0]<=minor ? str[0] : minor;
}
}
// iterative approach. I have added the minor´s position indicator.
int mini(int str[], int size, int* position)
{
int minor=str[0];
for (int i=1;i<size;i++)
if (str[i]<minor) {
minor=str[i];
*position=i;
}
return minor;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.