-3

I tried to reverse array with recursion method but somehow my code didn't show the right output.

    static void Main(string[] args)
    {
        int[] arr = { 10, 20, 15, 40, 70, 60, 50, 80, 90, 25 };
        ReverseArray(arr, arr.Length);

        string output = PrintArray(arr);
        Console.WriteLine(output);
    }

    static void ReverseArray(int[] V, int N)
    {
        int start = V.Length - N;
        
        if (N > 1)
        {
            int temp = V[start]; 
            V[start] = V[N - 1];
            V[N - 1] = temp;
            ReverseArray(V, N - 1);
        } 
    }

    static string PrintArray(int[] arr)
    {
        string temp = "";

        foreach (int angka in arr)
        {
            temp += angka.ToString() + " ";
        }

        return temp;
    }

I want the output showing this : (25,90,80,50,60,70,40,15,20,10)

But my output is like this :

enter image description here

What's wrong with my code ?

5
  • 4
    This question is ideal for debugger practice. Use the debugger, step through the code and observe what happens to the array contents. Commented Mar 30, 2021 at 6:59
  • Hint #1: when you get to the last element and swap it with the first, haven't those elements already been swapped once? Hint #2: why you are writing this recursively anyway? It would work just as well with a simple loop. In any case, see duplicate for the same basic problem and a number of alternative solutions. Commented Mar 30, 2021 at 7:02
  • Why do it in a recursive way? Wouldn't it be easier for your mind to just have a loop? At least for my mind it is. This would also avoid passing the length to the function (which IMHO violates the principle of least astonishment). Commented Mar 30, 2021 at 7:02
  • @ThomasWeller This could make sens if one only wants to reverse only the first N elements. But it would certainly help if an overload without the length is added which calls ReverseArray(V, V.Length) Commented Mar 30, 2021 at 7:04
  • 1
    Also note that recursion will put quite a size limit on your array. The default stack size is 1 MB, so you can only have below 128k items in your array. Commented Mar 30, 2021 at 7:08

2 Answers 2

3

You're reversing the array, but after you get past the midpoint you keep reversing. That means you're flipping values that have already been flipped.

Changing if (N > 1) to if (N > V.Length / 2) will fix the problem.

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

Comments

1

Hi use below logic it will work.

void reverse(int[] arr, int low, int high)
{
    if (low < high)
    {
        int temp = arr[low];
        arr[low] = arr[high];
        arr[high] = temp;
 
        reverse(arr, low + 1, high - 1);
    }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.