Member Avatar for lianaconda
lianaconda

Hi. The assignment is to implement a function using recursion. I can't use any loops whatsoever. The function takes in an array of doubles and the array size, and is supposed to return the position of the smallest element in the array. I've already written some code out for the function, but I don't get the answers I would like. I've worked out the algorithm to where I think it should do the right thing, but it doesn't. Can anyone help? Thanks!!

// Return the subscript of the smallest element in the array.  If
// more than one element has the same smallest value, return the
// smallest index of such an element.  If the array is empty,
// return -1.
int indexOfMin(const double a[], int n)
{
	int place;
	int turn;
	const double* p = a + n - 1;

	if (n <= 1)
		return 0;
	if (*a <= *p)
	{
		place = 0;
		return indexOfMin(a, n-1) + 1; 	}
	else if (*a > *p)
	{
		place = n - 1;
		return indexOfMin(a+1, n-1);
	}
}

I don't know how to get the return statements to work as I want them to. The program is going through the array correctly, but I guess maybe my algorithm has some problems too. Recursively, i'm trying to reduce the array starting from the outside in, and whichever side is smaller, I pass that side into the function again to compare it to the value next in line. Maybe this isn't the best way to implement this function, but I tried a couple other ways and they didn't seem to work either. Maybe I'm just missing something simple, or I'm completely off. Let me know!! Thank you!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.