0

i'm so lost. I need to find the second smallest integer in an array recursively. I've started to write the method but I know its wrong and don't know where to go from here.

public static int findSecondSmallest(int [] array)
{
    int secSmall = array[0], min = array[0];
    if(array.length >= 1)
    {
        findSecondSmallest(array);
        if(secSmall > min)
            secSmall = array[0+1];
    }

    return secSmall;
}
2
  • 2
    You should keep track of what index you are at in the array, the smallest, and the second smallest values. Pass these as parameters to the recursive function. Commented Sep 28, 2014 at 23:35
  • Think about the minimum complexity to implement this function. How quickly does the algorithm grow? You may not want the optimal complexity function. Commented Sep 28, 2014 at 23:37

3 Answers 3

2

What you could do is to keep track of the smallest one and the second smallest one as you traverse the array from beginning to end. Update them both if you run into something smaller than the second smallest or something bigger than the smallest but less than the second smallest. Hope the following code makes sense:

public class Driver {
    public static int MAX_VAL = 1000000;
    public static void main(String[] args) {
        int[] arr = {2,5,3,6,2,7,43,2,56,2,-1, 1, 5};
        int[] smalls = new int[2];
        int sm = find(arr, 0, smalls);
        System.out.println(sm);
    }

    public static int find(int[] arr, int index, int [] smalls) {
        if(index == 0) {
            smalls[0] = arr[index];
            smalls[1] = Integer.MAX_VALUE;
            find(arr, index+1, smalls);
        } else if(index < arr.length){
            if(arr[index] < smalls[0]){
                smalls[1] = smalls[0];
                smalls[0] = arr[index];
            } else if(smalls[1] > arr[index]) {
                    smalls[1] = arr[index];
            }
            find(arr,index + 1, smalls);
        }
        return smalls[1];
    }
}

Here, index stands for the index of the last element in your 'partial array'. Every recursive step, you examine the first index + 1 elements of your array. Note: small[0] is the SMALLEST element of the partial array and small[1] is the second smallest of the partial array.

For a good treatment of recursion, I recommend you pick up Prolog. This language has no loops and you will rely heavily on recursion.

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

5 Comments

Wow, recommanding Prolog just because he wants a recursive solution is a bit weird. There are other highly recursive languages much better than Prolog, such as Haskell, Scala, Ocaml (all functional languages...).
That might be true, but Prolog is the only one I know (therefore recommending) :)
This feels a little like a recursively-written-out version of the iterative solution. The solutions are basically the same so it's difficult to avoid this, but I think the fact that the array smalls is the same object between recursive calls makes this solution seem distinctly non-functional in style. I'm sorry to be splitting hairs, but I think the question must be looking for an example of good recursive style, which for me this isn't.
@gandaliter : I upvoted both answers, but you are right in your observation.
We could easily modify it so that the array smalls is instantiated everytime, and return the array instead (which is what you did). But since the user was hoping to return an int, I went out of the way to make it that way. Admittedly, it's not functional-style, but Java allows us to do this, why restrict ourselves? And I did recommend a logic programming language (maybe not the best as Dici pointed out) but it might make up to my apparent ignorance :)
1

This is very easy to do iteratively, so a recursive solution is already a bit contrived, and there are several ways to do it. For example you could write a function which recurses on two halves of the array and gives the second smallest of the four numbers returned. I'll assume you want to split off the first element and recurse on the rest of the array.

The recursive function will return both the smallest and the second smallest in an IntPair, the definition of which I omit, so you will need a wrapper function to extract the second smallest from this pair.

public static int findSecondSmallest(int[] array) {
    return findSecondSmallestAndSmallest(0, array).getSecond();
}

private static IntPair recurseSecondSmallest(int index, int[] array) {
    if (array.length - index == 2) {
        if (array[index] < array[index+1])
            return new IntPair(array[index], array[index+1]);
        else return new IntPair(array[index+1], array[index]);
    }
    IntPair recursiveResult = recurseSecondSmallest(index+1, array);
    if (array[index] < recursiveResult.getFirst())
        return new IntPair(array[index], recursiveResult.getFirst());
    else if (array[index] < recursiveResult.getSecond())
        return new IntPair(recursiveResult.getSecond(), array[index]);
    else return recursiveResult;
}

Comments

0

The trick is smarter pseudocode. This may not be the most efficient algorithm but its stupid smart. also in any case, recursive is not the way to go for such a problem.

secondsmallest(Array of size n)

  if n == 2
     if array[0] < array[1]
         return array[1]
     else return array[2]

 if n not equal 2 then

    remove largest element from the array
    return secondsmallest(newArray of size n-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.