0

I have a programming exam in a few days so I'm doing some exercises just to practice. However, I've been stuck with this problem and I started to doubt if it's possible to do it. Write a recursive method called arrayReverse which takes in an array of integers and returns said array in reversed sorted order. So an example would be:

input: [1,2,3]    
output:[3,2,1]

I wasn't able to solve it. My intuition was to take the last element of the array, put it at the beginning, i,e: index[0] and then recursively call the rest of the array but then taking the new last element and put it on index[1]. Unfortunately, the implementation was harder than I thought but I (for the sake of trying) edited the question in a way that it accepts 2 arrays and this was my code:

import java.util.Arrays;

class Test {

  int[] arrayReverse(int[] m, int[] mReverse) {
    if (m.length == 1) {
        mReverse[mReverse.length - 1] = m[0];
        return mReverse;
    } else {
        int lastNum = m[m.length - 1];
        mReverse[mReverse.length - m.length] = lastNum;
        int[] arrayMinusOne = cropArray(m);
        return arrayReverse(arrayMinusOne, mReverse);
    }
}

int[] cropArray(int[] m) {
    int[] mCropped = new int[m.length - 1];
    for (int i = 0; i < m.length - 1; i++) {
        mCropped[i] = m[i];
    }
    return mCropped;
}

}
  void demo() {

    int[] helpTest4 = new int[]{1, 2, 3};
    int[] emptyArray = new int[helpTest4.length];

    int[] test4 = arrayReverse(helpTest4, emptyArray);
    System.out.println(Arrays.toString(test4));


}

public static void main(String[] args) {
    new Test().demo();
}
}

It works perfectly but I'm not satisfied with the result because of two reasons:

  1. I wasn't able to do it completely recursive. I used a for loop in cropArray.
  2. I couldn't do it on one array.

How can this be done?

halfer
  • 19,824
  • 17
  • 99
  • 186
  • 1
    Is original array sorted? – tsolakp Jan 17 '18 at 19:38
  • the only way to do it with a single integer array parameter is if the given array is sorted correct? – RAZ_Muh_Taz Jan 17 '18 at 19:40
  • [What does your step debugger tell you?](http://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) –  Jan 17 '18 at 19:42
  • 1
    @tsolakp No it's not –  Jan 17 '18 at 19:48
  • 1
    @JarrodRoberson I don't even have a problem with my code. I'm just looking to improve it. –  Jan 17 '18 at 19:49
  • Then it seems like you need to research on recursive merge sort algorithm. – tsolakp Jan 17 '18 at 19:53
  • have you tested your algorithm on a bigger array? @AbdulMalekAltawekji – RAZ_Muh_Taz Jan 17 '18 at 19:54
  • 1
    Yes it worked. Did you find a mistake? –  Jan 17 '18 at 19:58
  • @AbdulMalekAltawekji Do you require recursive function to have only array as parameter or initial index and array size can also be parameters of the recursive function? Do you have any restriction for the parameters. – Anurag Sharma Jan 17 '18 at 20:04
  • 1
    @AnuragSharma The first scenario. –  Jan 17 '18 at 20:05
  • @AbdulMalekAltawekji Since this question is unfortunately closed for answers, let me explain to you that YES, it can be done easily. Hint: If you had a **stack**, would you be able to reverse the array? Then, realise that in fact, you _have_ a stack: The internal calling stack where the local variables and parameters are stored each time you invoke some method. You just have to code a method which stores locally one element from the array (with increasing position), invokes recursively, and then stores it in the target position. – Little Santi Jan 17 '18 at 20:18
  • @AbdulMalekAltawekji: Added another option you wanted – Anurag Sharma Jan 17 '18 at 21:02
  • 1
    Then that is off-topic as well, as code reviews are off-topic here. https://codereview.stackexchange.com exists for a reason –  Jan 18 '18 at 00:43
  • @LittleSanti: the question is now re-opened, if you wish to add an answer. – halfer Jan 18 '18 at 11:39

5 Answers5

1

Option1: Using only one parameter (array) in the recursive function

import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;

public class MyClass {
     public static void main(String[] args) {

        int[] arr = {1,2,3,4,5};
        int[] reversed = reverseArray(arr);
        System.out.println(Arrays.toString(reversed));
    }

    public static int[] reverseArray(int[] arr)
    {
        if (arr.length == 0)
            return arr;

        // remove first element   
        int first = arr[0];
        int[] list = Arrays.copyOfRange(arr, 1, arr.length);

        //Calling Function Recursively get reversed array
        int[] returnArr = reverseArray(list);

        //Add original first to the last of the arrayToReturn
        returnArr = Arrays.copyOf(returnArr, returnArr.length + 1);
        returnArr[returnArr.length - 1] = first;

        return  returnArr;
    }
}

Option2:

void reverseArray(int[] x){
   reverse(x, 0, x.length -1);
}

void reverse(int[] x, int i, int j){
    if(i<j){//Swap ith with jth element where i and j are equidistant from ends
       int tmp = x[i];
       x[i] = x[j];
       x[j] = tmp;
       reverse(x, ++i, --j);//Recursive
    }   
}

Test:

int[] s = new int[]{1,2,3,4,5};
reverseArray(s);
System.out.println(Arrays.toString(s));//"5,4,3,2,1"

Recursive, O(n), no temporary Array needed.

Anurag Sharma
  • 2,409
  • 2
  • 16
  • 34
  • Unfortunately reverseArray is not recursive, reverse is. The OP is asking for a single method that takes a single array as its parameter that is recursive and reverses the array. Your recursive method takes a int[], int and another int. Doesn't satisfy the requirements – RAZ_Muh_Taz Jan 17 '18 at 19:45
  • @RAZ_Muh_Taz: Added another option. Thanks for pointing that out. – Anurag Sharma Jan 17 '18 at 21:05
0

Please try the code below:

import java.util.*;
public class HelloWorld{
     public static void main(String []args){
         Scanner sc  = new Scanner(System.in);
        
        int n = sc.nextInt();
        int arr[]= new int[n];
        for(int i=0;i<n;i++)
        {
            arr[i] = sc.nextInt();
        }
        Printsum(arr,0);
     }
     
     public static void Printsum(int arr[], int idx)
     {
         if(idx == arr.length)
         return ;
         
         Printsum(arr,idx+1);
         System.out.println(arr[idx]);
     }
}
Feathercrown
  • 2,547
  • 1
  • 16
  • 30
-1

I don't think this is a particularly good question - there is obviously a direct and clear way to do it without recursion; so the question does little to demonstrate any useful knowledge of recursion.

That said I believe the algorithm they were seeking uses the facts that:

a) reversing a 1 length array is trivial

b) you can reverse an n length array by appending the first element to the reverse the the last n-1 elements.

So code for this solution will look much simpler that what you currently have.

Elemental
  • 7,365
  • 2
  • 28
  • 33
-1

Ruby:

def reverse(a)
  if a.empty?
    return []
  else
    return [a.last] + reverse(a[0..-2]) 
  end
end

a = [1, 2, 3]

reverse(a)
Victor Ribeiro
  • 577
  • 7
  • 20
-1

Taking the request literally, I have come out with a solution which only needs ONE recursive function with just ONE input/output parameter:

public static void arrayReverse(int[] input)
{
    if (input.length > 0)
    {
        // Store locally the fist element:
        int firstElement=input[0];

        // Creates a sub-array and reverses it:
        int[] input2=new int[input.length - 1];
        System.arraycopy(input, 1, input2, 0, input2.length);
        arrayReverse(input2);

        // Copies back the reversed array into the current array:
        System.arraycopy(input2, 0, input, 0, input2.length);

        // Puts the stored fist element in the last position:
        input[input.length - 1]=firstElement;
    }
}

This solution is based upon a stack structure, for which it takes advantage of the machine calling stack at runtime, where the local values are stored while the function is executing.

  • The base case of this recursion is, of corse, the empty array.
  • In the generic case, the function stores locally the first element, then re-invokes itself recursively to reverse the rest of the array, and last, puts back the first element in the last position.
Little Santi
  • 8,563
  • 2
  • 18
  • 46