3

I'm having a problem trying to write a body for a function that recursively reverse an array, but only has one parameter.

function ReverseArray(arr) {

  var i = 0;
  var j = arr.length - 1;

  if (i < j) {
    var temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
    return ReverseArray(arr);
  }

  return arr;
}   

I realize this won't work because the variables will be re-initialized when the function calls itself.

I'm just looking for some ideas at this point, because i'm stuck.

7
  • Create a temporary array with the same length and fill this up while looping through your original array. After the loop set your original array to the new array. Commented Nov 10, 2014 at 4:36
  • stackoverflow.com/questions/5164039/javascript-recursion Commented Nov 10, 2014 at 4:38
  • Where does the 1 argument limitation come from? Commented Nov 10, 2014 at 4:53
  • @zerkms Homework, probably. This question has been asked multiple times. Commented Nov 10, 2014 at 4:54
  • 1
    @zerkms: A while back I asked this on Meta. Commented Nov 10, 2014 at 13:51

8 Answers 8

2

First, for other people who might be looking to reverse an array for a real problem rather than homework, use Array.reverse, don't waste you time trying to implement it yourself.

If you absolutely must, then the trick here would be to pass a smaller array (minus the first and last elements by using slice) when you recurse and rebuild the final array as you unwind using concat. For example:

function ReverseArray(arr) {
  if (arr.length < 2) {
    return arr;
  } else {
    var first = arr[0];
    var last = arr[arr.length - 1];
    return [last].concat(ReverseArray(arr.slice(1, length - 1))).concat([first]);
  }

}

alert(ReverseArray([1,2,3,4,5]));

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

3 Comments

With one argument it's really ugly. And looks completely useless for education (+1)
Btw, try ReverseArray([1])
You're overcomplicating it. Else case could be var first = arr.pop(); return [first].concat(ReverseArray(arr));
1

There is an Array.reverse method.

Anyways... for testing/learning purposes:

["a","b","c"].map(function(v,i,a) {return a[a.length-i-1]})

v is value, i is iteration, and a is array.

1st iteration:

v="a"; i=0;

2nd iteration:

v="b"; i=1;

3rd iteration:

v="c"; i=2;

All iterations:

a=["a","b","c"]; v=a[i];

Comments

0

Why do you want to write your own reverse method? Why not just use the reverse method on the array?

function ReverseArray(arr) {
    arr = arr.reverse();
}

UPDATE

The above method obviously does not make a lot of sense anymore since you can just call the reverse method wherever you want.

2 Comments

Why to even wrap it then? And obviously OP learns some FP (or similar) practices
OP is asking for a recursive solution
0

I think the following solution is the simplest recursive implementation:

var a = [1,2,3,4,5];
alert(ReverseArray(a));

function ReverseArray(arr) {
    if(arr.length < 2) {
        return arr;
    } else {
        return [arr.pop()].concat(ReverseArray(arr));
    }
}

Comments

0

I'm using shift, pop, unshift, and push to avoid making partial copies of the array. Probably a tad bit faster than copying of part of the array using slice on each recursive call, but don't expect it to outperform a non-recursive solution or the built-in reverse method:

function recReverse(list){
  if(list.length>=2){
    var lo=list.shift();
    var hi=list.pop();
    list=recReverse(list);
    list.unshift(hi);
    list.push(lo);
  }
  return list;
}

and fiddle

Comments

-1

what you need to do is this

function reverse(x, i, j) {
    if (i < j) {//Swap
        var tmp = x[i];
        x[i] = x[j];
        x[j] = tmp;
        reverse(x, ++i, --j);//Recursive
    }
}

function reverseIt(x) {
    console.log(x);
    reverse(x, 0, x.length - 1);
    console.log(x);
}


var q = [1, 2, 3, 4, 5, 6, 7, 8, 9];
reverseIt(q);

2 Comments

then try local storing tempvalues in local storage
"storing tempvalues in local storage" --- you are missing the whole point
-1
function reverseArray(origArray)
{
    if (origArray.length > 1) {
        var element = origArray[0];
        var newArray = reverseArray(origArray.slice(1));
        newArray[newArray.length] = element;
        return newArray;
    } else {
        return origArray;
    } 
}

2 Comments

[] is a valid array actually
Where does element come from in that origArray.length == 1 case? And what do you need that case for at all?
-1

Say you have an array [1 2 3 4 5]

Simply store the last number somewhere, and feed 1-4 into the function again (resulting in 5-1234)

When there is only one number in the fed in array, return that number as a single array member.

When the array is returned back, append the returned array to the temporary number into a new array.

This should do 4-123, then 3-12, then 2-1, which will all feed back up, resulting in 5-4-3-2-1

Condensed version:

var input_array = [1,2,3,4,5]

function rev(input) {
  if (input.length == 1) { return input; }
  if (input.length == 0) { return []; }
  return [input[input.length-1]].concat(rev(input.splice(0, input.length-1)));
}

rev(input_array);

Spread out version:

var input_array = [1,2,3,4,5]

function rev(input) {
  if (input.length == 1) { return input; }
  if (input.length == 0) { return []; }
  var last = [input[input.length-1]];
  var newarr = rev(input.splice(0, input.length-1));
  var answer = last.concat(newarr);
  return answer;
}

rev(input_array);

3 Comments

No, you don't want to return a number, but an array. Also, "when there is only one number" is not the base case.
Yeah, that was what I meant. Editted to reflect that. Return it as [1], not as 1. Actually, it could still work with that, if you check if its the type on return, but checking length would be smarter than checking type.
Your function is still failing on the empty array.

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.