Java – Recursion to find the 2 smallest nums in array

So I have this problem of finding the 2 smallest numbers in array but I have to use recursion (the recursion part is a part of this exercise). I start thinking how to do it and ‘the plan’ that I trying to do is like this, first of all find the smallest in the array, then mark where I found it and then to split the array in to 2 groups and search in this 2 group an eventuality take the minimum from them..

this is the code that I got this far:

public static int MinRecu2(int[] a) {
    if (a.length == 1)
        return a[0];
    int min = a[0];
    int min2;
    int mark = 0;

    // Find first min
    for (int i = 1; i < a.length; i++) {
        if (a[i] < min) {
            min = a[i];
            mark = i;

    int [] help1= new int [mark+1];
    int [] help2= new int [a.length-mark];
    help1=Arrays.copyOfRange(a, 0, mark);
    help2=Arrays.copyOfRange(a, mark+1, a.length-1);

    // Find second min
    min2 = Math.min(MinRecu2(help1), MinRecu2(help2));

    return min;

I know the code not working and that the ‘recursion’ I was trying to do is bad, but that how I was trying to make my thinking to code


This is an approach to your question.

public static int[] twoSmallest(int[] arr, int s, int e) {
    int[] list;
    if (e - s <= 3) { // maybe 2 or 3
        list = new int[e - s];
        for (int i = s; i < e; i++)
            list[i - s] = arr[i];
    } else {
        int[] left = twoSmallest(arr, s, (s + e) / 2);
        int[] right = twoSmallest(arr, (s + e) / 2, e);
        list = new int[4];
        list[0] = left[0];
        list[1] = left[1];
        list[2] = right[0];
        list[3] = right[1];
    return new int[] {list[0], list[1]};

This function means find two smallest numbers in arr in [s, e). You can call like this:

int[] result = twoSmallest(arr, 0, arr.length);