0

I have some pseudo code for a recursive algorithm that finds the smallest number in an array.

Here is the algorithm.

Min(A[0..n - 1])
If n = 1 return A[0]
else
{ 
  temp <-- Min(A[0..n - 2])
  if temp <= A[n - 1]
     return temp
  else return A[n - 1]
}

One part I don't understand about this pseudo code is the line "temp <-- Min(A[0..n - 2])". Specifically why is it "n - 2" in the recursive call instead of "n - 1"?

My other question is how I would implement that line in code. I am using Java.

Thanks in advance for any help.

2
  • Each time you recurse to need to be one closer to the end of recursion. (which is when you have only one element) Commented Feb 26, 2012 at 21:08
  • Thanks for the responses. How would I implement this pseudo code? Not clear on how I would handle that line in code. Commented Feb 27, 2012 at 2:38

3 Answers 3

5

Because you array is indexed from 0 to n-1, inclusive. You need to recurse on a sub-array that's one element smaller, hence n-2.

Sign up to request clarification or add additional context in comments.

Comments

1

for your 1st question:

since you are using a recursive algorithm, in order to solve the problem, you first have to solve the same problem with a smaller size. In this pseudocode, for finding the minimum of an array with the length of n, first the minimum of the same array with the size of n-1 is found and then the minimum is compared with nth element. Your array is indexed from 0 to n-1 (which will make it's length = n) so for recursive call, you have to call the array from index 0 to n-2 (n-1 elements).

for your 2nd question: This is how I would implement the code in Java:

public class Minimum {
   public Minimum(int[] A) {
    findMin(A, 0, A.length-1);
}

public int findMin(int [] A, int start, int end){
    if (start== end-1)
        return A[0];
    else{
        int temp=findMin(A, start, end-1 );
        if (temp<=A[end]) 
            return  temp;
        else 
            return A[end];
    }
}

}

1 Comment

This is the line you asked about -> int temp=findMin(A, start, end-1 );
0

My other question is how I would implement that line in code.

If you are using an array.

// create an array with one less element.
A a2 = new A[a.length-1];
// copy the elements
System.arrayCopy(a,0,a2,0,a2.length);

If you are using a List

List<A> a2 = a.subList(0, a.length-1);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.