Skip to content

Instantly share code, notes, and snippets.

@getify
Last active December 6, 2017 14:07
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save getify/139d95d1b0f87659033292effb3f0bc7 to your computer and use it in GitHub Desktop.
Save getify/139d95d1b0f87659033292effb3f0bc7 to your computer and use it in GitHub Desktop.
comparing single recursion vs binary recursion
function reverseStr(str) {
if (str.length <= 1) return str;
var firstChar = str[0];
var restStr = str.substr(1);
return (restStr.length > 1 ? reverseStr(restStr) : restStr) +
firstChar;
}
console.log( reverseStr("") == "" ); // true
console.log( reverseStr("a") == "a" ); // true
console.log( reverseStr("ab") == "ba" ); // true
console.log( reverseStr("abc") == "cba" ); // true
console.log( reverseStr("abcd") == "dcba" ); // true
console.log( reverseStr("abcde") == "edcba" ); // true
console.log( reverseStr("abcdefghijklmnopqrstuvwxyz") == "zyxwvutsrqponmlkjihgfedcba" ); // true
function reverseStr(str) {
if (str.length <= 1) return str;
var mid = Math.floor(str.length / 2);
var firstHalf = str.substr(0,mid);
var secondHalf = str.substr(mid);
return (secondHalf.length > 1 ? reverseStr(secondHalf) : secondHalf) +
(firstHalf.length > 1 ? reverseStr(firstHalf) : firstHalf);
}
console.log( reverseStr("") == "" ); // true
console.log( reverseStr("a") == "a" ); // true
console.log( reverseStr("ab") == "ba" ); // true
console.log( reverseStr("abc") == "cba" ); // true
console.log( reverseStr("abcd") == "dcba" ); // true
console.log( reverseStr("abcde") == "edcba" ); // true
console.log( reverseStr("abcdefghijklmnopqrstuvwxyz") == "zyxwvutsrqponmlkjihgfedcba" ); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment