javascript - swapping pairs in arrays recursively -


trying swap pairs in array recursively, managed iteratively. how implement swap part recursively? think have of correct! if there odd number, last 1 stays same. don't want have helper swap function if possible.

pairswap = function(arr) {       var newarray = []       (var = 0; < arr.length; += 2) {         var current = arr[i];         var next = arr[i + 1]         if (next !== undefined) {           newarray.push(next)         }         if (current !== undefined) {           newarray.push(current)         };       };       return newarray;     }      console.log(pairswap([1, 2, 3, 4, 5]))     pairswaprecursive = function(arr) {        if (arr.length < 2) {         return arr;       } else {         //swap first , second:         return (swap ? ) + pairswaprecursive(arr.slice(2))        }       }      console.log(pairswaprecursive([1, 2, 3, 4, 5])) //should return [2, 1, 4, 3, 5]  //something similar in java:      // public string swappairs(string s) {     //      if (s.length() < 2)     //           return s;     //      else     //           return swap(s.charat(0), s.charat(1)) + swappairs(s.substring(2));     // } 

i don't want have helper swap function if possible.

and don't need - return second , first element , you're done:

var pairswaprecursive = function(arr) {     if (arr.length < 2) {         return arr;     }      return [arr[1], arr[0]].concat(pairswaprecursive(arr.slice(2))); }; 

so other recursive algorithm it:

  1. does little chunk of work. in case - return array 2 first elements swapped.
  2. invokes rest

jsfiddle: http://jsfiddle.net/am8rz1jx/


Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -