HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Reversing an array recursively

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
arrayreversingrecursively

Problem

Implementation:

void ReverseArray(T[] a)
{
    ReverseArray(a,0,a.Length-1);
}

void ReverseArray(T[] a,int lo,int hi)
{
    if(lo >= hi) return;

    // swap
    var temp = a[lo];
    a[lo] = a[hi];
    a[hi] = temp;

    ReverseArray(a,lo+1,hi-1);
}


Usage:

int[] arr = {1,2,3,4,5,6,7,8};
ReverseArray(arr); // reverses the array


How can I improve this?

Solution

You can improve it by making it a loop instead of a recursive call. There is no need for the recursion, and it limits you in ways that a loop would not (for example, you are limited by your stack size with recursion).

Additionally, the loop implementation is simpler, and probably a bunch faster too.

If you do stick with the recursive call, you should make the recursive method private too.

The loop could be as simple as:

void ReverseArray(T[] a)
{
    for (int lo = 0, hi = a.Length - 1; lo < hi; lo++, hi--)
    {
        var temp = a[lo];
        a[lo] = a[hi];
        a[hi] = temp;            
    }
}


Normally I would take issue with the short variable names, but, in this context, with the generic array data type, a is not too bad of a name.

The only style issue I have other than the a, is that you need space around the operators in your conditions and assignments. The code:

ReverseArray(a,0,a.Length-1);
....
ReverseArray(a,lo+1,hi-1);


should be:

ReverseArray(a, 0, a.Length - 1);
....
ReverseArray(a, lo + 1, hi - 1);


Note, that if the recursive call is required as part of an exercise, then it is implemented correctly/functionally, and I can't see any problems other than the limited size of the array (I would guess about 40,000 elements is too many to handle).

Code Snippets

void ReverseArray<T>(T[] a)
{
    for (int lo = 0, hi = a.Length - 1; lo < hi; lo++, hi--)
    {
        var temp = a[lo];
        a[lo] = a[hi];
        a[hi] = temp;            
    }
}
ReverseArray(a,0,a.Length-1);
....
ReverseArray(a,lo+1,hi-1);
ReverseArray(a, 0, a.Length - 1);
....
ReverseArray(a, lo + 1, hi - 1);

Context

StackExchange Code Review Q#66773, answer score: 10

Revisions (0)

No revisions yet.