Sample of turning recursive function into non-recursive

This is sample of turning one recursive function into its non-recursive form, note this is a matter of traversal of binary-tree in post-order. 

Interestingly you will find in javascript, the recursive form runs costing less time than the non-recursive one, it means that either my implementation should be optimized or the js engine is really doing better in handling the function invoking/returning stack operation than simulating them by js code.


<body>
<script>
function f_recursive(n){
	var u1, u2, f;

	if (n < 2)
		f = n + 1;
	else {
		u1 = f_recursive(parseInt(n/2));
		u2 = f_recursive(parseInt(n/4));
		f = u1 * u2;
	} 

	return f;

}
var t1, t2;
t1= +new Date();
console.log("f_recursive", f_recursive(200));
console.log("time cost by recursive:", (t2 = +new Date(), t2 - t1));


function f_nonrecursive(n) {
	var stack = [];
	stack.push({ N: n, flag: 0, u1: undefined, u2: undefined, ret: undefined});
	//var cur;
	while (stack.length != 0){
		var cur = stack.pop() ; //stack[stack.length-1];
		if (cur.flag == 0) { //not visit the lchild yet;
			if (cur.N >= 2){
				stack.push((cur.flag = 1, cur)); //push the old one, change it flag to 1;
				stack.push({ N: parseInt(cur.N/2), flag: 0, u1: undefined, u2: undefined, ret: undefined })
			} else {
				cur.ret = cur.N + 1;
				if (stack.length != 0){
					stack[stack.length - 1].flag == 1 && 
					(stack[stack.length -1].u1 = cur.ret, 1) ||
					(stack[stack.length - 1].flag == 2 && (stack[stack.length -1].u2 = cur.ret) )
				}
			}
			continue;
		}

		if (cur.flag == 1){
			if (cur.N >= 2){
				stack.push((cur.flag = 2, cur));
				stack.push({ N: parseInt(cur.N/4), flag: 0, u1: cur.u1, u2: undefined, ret: undefined });
			} else {
				console.log("this should NOT displayed;")
			}

			continue;
		}

		if (cur.flag == 2) {
			if (cur.N >= 2){
				cur.ret = cur.u1 * cur.u2;
				if (stack.length != 0){
					stack[stack.length - 1].flag == 1 && 
					(stack[stack.length -1].u1 = cur.ret, 1) ||
					(stack[stack.length - 1].flag == 2 && (stack[stack.length -1].u2 = cur.ret)) 
				}
			} else {
				cur.ret = cur.N + 1;
			}

			continue;
		}

	}

	console.log(cur.ret);

}
var t3, t4;
t3 = +new Date();
console.log("f_nonrecursive(200)", f_nonrecursive(200));
console.log("time cost by non-recursive: ",(t4 = +new Date(), t4 - t3));
</script>

</body>

output:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值