Reputation: 3
int f(int a[], int size) {
if (size == 1)
return arr[0];
size--;
return f((arr + (arr[0] > a[size])), size);
}
I'm attempting to return the index of the minimum. The code above returns the VALUE of the minimum, but I'm having trouble returning the index, can anyone help? Also, I'm only allowed to pass 2 parameters to the function, the array and the size of the array.
Upvotes: 0
Views: 609
Reputation: 3319
See code below (modified to use 2 parameters only):
int f(int a[], int size) {
if (size <= 1)
return 0;
int i = f(a, --size);
return a[size] < a[i] ? size : i;
}
Upvotes: 1
Reputation: 10913
Something like this will probably work:
size_t f(int a[], size_t low_index, size_t high_index) {
if (low_index == high_index) {
return low_index;
}
if (arr[low_index] > arr[high_index]) {
low_index++;
} else {
high_index--;
}
return f(a, low_index, high_index);
}
You'd call it with f(a, 0, size-1)
.
That said, I'm not sure why you want to do this recursively when it seems easier to do it in a for loop:
size_t f(int a[], size_t size) {
size_t min_index = 0;
int min_value = a[0];
for (size_t i = 1; i < size; ++i) {
if (a[i] < min_value) {
min_value = a[i];
min_index = i;
}
}
return min_index;
}
Upvotes: 1