473,386 Members | 1,734 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

example program

Hi all,

can any one give a example program where recursive version is faster
than iterative version ?
Jun 27 '08 #1
20 1610
aa*****@gmail.com wrote:
Hi all,

can any one give a example program where recursive version is faster
than iterative version ?
For trivial programs there may or may not be examples where recursion is
faster.

But recursion is a natural fit for many kinds of programming which would be
a pain to implement with iterative methods.

Especially with making arrangements to save/restore complex data which may
well end up slower than just using recursion. But even if recursion was
slower, the difference would be minimal in a real application, while keeping
the code much cleaner.

--
Bartc
Jun 27 '08 #2
Bartc said:
aa*****@gmail.com wrote:
>Hi all,

can any one give a example program where recursive version is faster
than iterative version ?

For trivial programs there may or may not be examples where recursion is
faster.
There is, however, no shortage of examples where recursion is /slower/.
But recursion is a natural fit for many kinds of programming which would
be a pain to implement with iterative methods.
Right. We don't recurse for speed, but for clarity (where it /is/ clearer)
- and even then only if the cost in terms of speed loss is more than
adequately compensated by the gain in clarity.

To take a famous example, the following code:

unsigned long factorial(unsigned long n)
{
return n < 2 ? 1 : (n * factorial(n - 1));
}

is horribly inefficient compared to its iterative version (and more so,
compared to the Stirling Approximation). In a production environment, it
would be inappropriate. But in a teaching environment, it might well be
considered a reasonable way to /illustrate/ recursion, given suitable
"don't do factorials this way in Real Life" caveats.

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Jun 27 '08 #3
On Mon, 2 Jun 2008 03:29:17 -0700 (PDT), aa*****@gmail.com wrote:
>Hi all,

can any one give a example program where recursive version is faster
than iterative version ?
Primary concern: You need two versions of the program. How do you
confirm they are truly equivalent and that each is really coded for
highest efficiency?

Secondary concerns: On which hardware? Using which operating system?
Using which compiler? With what options? Which measure of speed, CPU
time or wall clock?

Are you getting the hint that there is no general answer?
Remove del for email
Jun 27 '08 #4
Recursive programs can be faster than the iterative versions when the
only changes you have introduced in the iterative version is saving
and restoring states. The system is of course faster in performing
push and pop as it simply means issuing 1 or 2 machine instructions.
In case of factorials, the stack frame is completely unnecessary. So
the iterative version is magnitudes faster than the recursive one.

Towers of Hanoi is faster in recursive version than the iterative one.
I am not sure about the quick sort. I will have to profile it but
surely the recursive version is more clear than the iterative one.
Jun 27 '08 #5
aa*****@gmail.com wrote:
Hi all,

can any one give a example program where recursive version is faster
than iterative version ?
Iterative mergesorts that I've seen for arrays,
tend to split less evenly than the recursive versions do.

When I race array sorting functions,
I can't get any speed from the iterative mergesorts.

I still haven't figured out how to mergesort a linked list iteratively.

--
pete
Jun 27 '08 #6
pete wrote:
aa*****@gmail.com wrote:
>Hi all,

can any one give a example program where recursive version is faster
than iterative version ?

Iterative mergesorts that I've seen for arrays,
tend to split less evenly than the recursive versions do.

When I race array sorting functions,
I can't get any speed from the iterative mergesorts.

I still haven't figured out how to mergesort a linked list iteratively.
See the thread "Mergesort algorithm for linked lists"
from January 2007 in this newsgroup.

--
Eric Sosman
es*****@ieee-dot-org.invalid
Jun 27 '08 #7
can any one give a example program where recursive version is faster
than iterative version ?
Try doing a BFS (Breadth First Search) or DFS of a dense graph
recursively
and iteratively (using lists) you will see a lot of difference.

Thanks,
Vamsi Kundet.
Jun 27 '08 #8
pete wrote:
aa*****@gmail.com wrote:
>>
can any one give a example program where recursive version is
faster than iterative version ?

Iterative mergesorts that I've seen for arrays, tend to split
less evenly than the recursive versions do. When I race array
sorting functions, I can't get any speed from the iterative
mergesorts. I still haven't figured out how to mergesort a
linked list iteratively.
I posted a complete linked list mergesort here one or two weeks
ago.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.

** Posted from http://www.teranews.com **
Jun 27 '08 #9
<aa*****@gmail.comwrote in message
news:b3**********************************@i36g2000 prf.googlegroups.com...
Hi all,

can any one give a example program where recursive version is faster
than iterative version ?
IMVHO, it's not really a matter of whether recursion is faster than
iteration, but which one is "safer" in practice... Recursion has a
side-effect of blowing the stack on some platforms when the depth exceeds
the stack size of the calling thread. This does not happen for iteration;
here is an example:

http://groups.google.com/group/comp....ee8351e006ff16

IMO, using iteration is safer than recursion when traversing a tree. On some
platforms, passing a "large enough" tree to a recursive traversal function
can result in a seg-fault.

Jun 27 '08 #10
On Jun 2, 4:43 am, Richard Heathfield <r...@see.sig.invalidwrote:
Bartc said:
aark...@gmail.com wrote:
Hi all,
can any one give a example program where recursive version is faster
than iterative version ?
For trivial programs there may or may not be examples where recursion is
faster.

There is, however, no shortage of examples where recursion is /slower/.
That is because a lot of real world programming revolved around the
idiom that 4 billion is the same as infinity.
But recursion is a natural fit for many kinds of programming which would
be a pain to implement with iterative methods.

Right. We don't recurse for speed, but for clarity (where it /is/ clearer)
- and even then only if the cost in terms of speed loss is more than
adequately compensated by the gain in clarity.

To take a famous example, the following code:

unsigned long factorial(unsigned long n)
{
return n < 2 ? 1 : (n * factorial(n - 1));

}

is horribly inefficient compared to its iterative version (and more so,
compared to the Stirling Approximation). In a production environment, it
would be inappropriate.
The above is bad because it pushes onto the stack once for each value
of n. But its a straw man against recursion in general.

If we were using arbitrary precision numbers, then matters would be
quite different. So if we assume that multiplier is somewhere between
O(bits**2) and O(bits) where bits is the larger of the two operands,
what *is* the fastest way to do factorial?

Hint:

(551!)**2 ~~ 1000!
(5405!)**2 ~~ 10000!
(53193!)**2 ~~ 100000!

etc.

If we break the factorial down into multiplying sequence halves, then
we have a *recursive* solution that it probably not too bad.

--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/
Jun 27 '08 #11
Paul Hsieh said:
On Jun 2, 4:43 am, Richard Heathfield <r...@see.sig.invalidwrote:
<snip>
>We don't recurse for speed, but for clarity (where it /is/
clearer) - and even then only if the cost in terms of speed loss is more
than adequately compensated by the gain in clarity.

To take a famous example, the following code:

unsigned long factorial(unsigned long n)
{
return n < 2 ? 1 : (n * factorial(n - 1));

}

is horribly inefficient compared to its iterative version (and more so,
compared to the Stirling Approximation). In a production environment, it
would be inappropriate.

The above is bad because it pushes onto the stack once for each value
of n.
It's only bad if your objective is efficiency. If the objective is to
explain recursion, there's nothing wrong with it at all. The part you
snipped made it clear that this was in fact my point: "But in a teaching
environment, it might well be considered a reasonable way to /illustrate/
recursion, given suitable "don't do factorials this way in Real Life"
caveats."
But its a straw man against recursion in general.
But it wasn't intended to be an argument against recursion in general! It
was an illustration that even in situations such as factorial calculation,
where recursion is generally considered (by the clueful) to be bad, there
can still be times where it's useful to do it anyway. There are plenty of
examples where recursion is *not* generally considered (by the clueful) to
be bad.

In fact, your reply to my article seems to be based on a complete
misunderstanding of what I actually wrote.
If we were using arbitrary precision numbers, then matters would be
quite different. So if we assume that multiplier is somewhere between
O(bits**2) and O(bits) where bits is the larger of the two operands,
what *is* the fastest way to do factorial?
Still the Stirling Approximation.

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Jun 27 '08 #12
"Paul Hsieh" <we******@gmail.comwrote in message
news:4c**********************************@w5g2000p rd.googlegroups.com...
On Jun 3, 4:49 am, "Chris Thomasson" <cris...@comcast.netwrote:
[...]
>Did your solution use something similar to the following technique:

http://groups.google.com/group/comp....ee8351e006ff16

I basically add an auxiliary pointer per-node and use that as a link in a
traversal queue. I believe that is easier than explicitly threading the
tree.

No, mine did not augment or write to the tree at all. It uses O(1)
space:

http://www.azillionmonkeys.com/qed/treeO1.c

In any event, the recursive solution is *faster* than this which is
what the OP was looking for. I just happen to be able to demonstrate
that "this" even existed.
Nice. I need to really take a look at your code.

[...]

Jun 27 '08 #13
Eric Sosman wrote:
pete wrote:
>aa*****@gmail.com wrote:
>>Hi all,

can any one give a example program where recursive version is faster
than iterative version ?

Iterative mergesorts that I've seen for arrays,
tend to split less evenly than the recursive versions do.

When I race array sorting functions,
I can't get any speed from the iterative mergesorts.

I still haven't figured out how to mergesort a linked list iteratively.

See the thread "Mergesort algorithm for linked lists"
from January 2007 in this newsgroup.
Thanks.
I recall taking a look and not liking it.
I'll have to take another look
and make a record of what I don't like,
if that turns out to still be the case.

--
pete
Jun 27 '08 #14
CBFalconer wrote:
pete wrote:
>aa*****@gmail.com wrote:
>>can any one give a example program where recursive version is
faster than iterative version ?
Iterative mergesorts that I've seen for arrays, tend to split
less evenly than the recursive versions do. When I race array
sorting functions, I can't get any speed from the iterative
mergesorts. I still haven't figured out how to mergesort a
linked list iteratively.

I posted a complete linked list mergesort here one or two weeks
ago.
Under what situations, if any,
would you be more inclined to use an iterative mergesort
than a recursive mergesort, on a list?

--
pete
Jun 27 '08 #15
pete wrote:
CBFalconer wrote:
>pete wrote:
>>aa*****@gmail.com wrote:

can any one give a example program where recursive version is
faster than iterative version ?

Iterative mergesorts that I've seen for arrays, tend to split
less evenly than the recursive versions do. When I race array
sorting functions, I can't get any speed from the iterative
mergesorts. I still haven't figured out how to mergesort a
linked list iteratively.

I posted a complete linked list mergesort here one or two weeks
ago.

Under what situations, if any, would you be more inclined to use
an iterative mergesort than a recursive mergesort, on a list?
If you read the code, you will see that some routines are
iterative, in that they follow the list, and others are recursive.

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.

** Posted from http://www.teranews.com **
Jun 27 '08 #16
So basically if we try simply to convert a recursive solution to
iterative by manually creating a stack frame and simulating function
calls, the resulting code is both ugly and slow. But if obvious
optimizations can be done for the stack frame, and in some cases it is
even completely eliminated ( factorial ), then the iterative code is
more efficient. As per my understanding, there are various algorithms
in which recursive solutions are faster - towers of hanoi, BFS, DFS to
name a few.

The recursive solution for X is faster than iterative does not
necessarily mean it is faster. It may mean that an optimized iterative
algorithm is yet to be written. A bit off the topic, but many a times
tail recursion (where applicable) significantly increases the
execution speed. I think the choice between recursive and iterative
approach is highly situation dependent and there is no right answer.
Jun 27 '08 #17
On Wed, 04 Jun 2008 03:27:23 -0400, CBFalconer
<cb********@yahoo.comwrote:
>pete wrote:
>CBFalconer wrote:
>>pete wrote:
aa*****@gmail.com wrote:

can any one give a example program where recursive version is
faster than iterative version ?

Iterative mergesorts that I've seen for arrays, tend to split
less evenly than the recursive versions do. When I race array
sorting functions, I can't get any speed from the iterative
mergesorts. I still haven't figured out how to mergesort a
linked list iteratively.

I posted a complete linked list mergesort here one or two weeks
ago.

Under what situations, if any, would you be more inclined to use
an iterative mergesort than a recursive mergesort, on a list?

If you read the code, you will see that some routines are
iterative, in that they follow the list, and others are recursive.
Your reply is non-responsive. He asked about when you would use
an iterative mergesort on a list. Your code was for a recursive
mergesort. Recursive mergesort implicitly requires a stack;
iteratative mergesort does not.
Richard Harter, cr*@tiac.net
http://home.tiac.net/~cri, http://www.varinoma.com
Save the Earth now!!
It's the only planet with chocolate.
Jun 27 '08 #18
Richard Harter wrote:
CBFalconer <cb********@yahoo.comwrote:
>pete wrote:
>>CBFalconer wrote:
pete wrote:
aa*****@gmail.com wrote:
>
>can any one give a example program where recursive version is
>faster than iterative version ?
>
Iterative mergesorts that I've seen for arrays, tend to split
less evenly than the recursive versions do. When I race array
sorting functions, I can't get any speed from the iterative
mergesorts. I still haven't figured out how to mergesort a
linked list iteratively.

I posted a complete linked list mergesort here one or two weeks
ago.

Under what situations, if any, would you be more inclined to use
an iterative mergesort than a recursive mergesort, on a list?

If you read the code, you will see that some routines are
iterative, in that they follow the list, and others are recursive.

Your reply is non-responsive. He asked about when you would use
an iterative mergesort on a list. Your code was for a recursive
mergesort. Recursive mergesort implicitly requires a stack;
iteratative mergesort does not.
If, instead of making silly comments, you read the code, you could
note that the routines revlist, mergelists, splitlist are all
iterative, and that only mergesort (which controls the others) is
actually recursive. The question did not involve a stack. The
following is the ONLY recursive component:

/* ================================================== */
/* Recursively sort a linked list. The sort is stable */
/* This is an O(NlogN) process for all lists. */
nodeptr mergesort(nodeptr root,
int (*cmp)(void *, void*)) /* compare */
{
nodeptr p;

if (root and root->next) { /* 2 up items in list */
p = splitlist(root); /* alters list root */
root = mergelists(mergesort(root, cmp),
mergesort( p, cmp),
cmp);
}
/* else the unit or empty list is already sorted */

return root;
} /* mergesort */

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.
** Posted from http://www.teranews.com **
Jun 27 '08 #19
On Thu, 05 Jun 2008 09:48:30 -0400, CBFalconer
<cb********@yahoo.comwrote:
>Richard Harter wrote:
>CBFalconer <cb********@yahoo.comwrote:
>>pete wrote:
CBFalconer wrote:
pete wrote:
>aa*****@gmail.com wrote:
>>
>>can any one give a example program where recursive version is
>>faster than iterative version ?
>>
>Iterative mergesorts that I've seen for arrays, tend to split
>less evenly than the recursive versions do. When I race array
>sorting functions, I can't get any speed from the iterative
>mergesorts. I still haven't figured out how to mergesort a
>linked list iteratively.
>
I posted a complete linked list mergesort here one or two weeks
ago.

Under what situations, if any, would you be more inclined to use
an iterative mergesort than a recursive mergesort, on a list?

If you read the code, you will see that some routines are
iterative, in that they follow the list, and others are recursive.

Your reply is non-responsive. He asked about when you would use
an iterative mergesort on a list. Your code was for a recursive
mergesort. Recursive mergesort implicitly requires a stack;
iteratative mergesort does not.

If, instead of making silly comments, you read the code, you could
note that the routines revlist, mergelists, splitlist are all
iterative, and that only mergesort (which controls the others) is
actually recursive. The question did not involve a stack. The
following is the ONLY recursive component:

/* ================================================== */
/* Recursively sort a linked list. The sort is stable */
/* This is an O(NlogN) process for all lists. */
nodeptr mergesort(nodeptr root,
int (*cmp)(void *, void*)) /* compare */
{
nodeptr p;

if (root and root->next) { /* 2 up items in list */
p = splitlist(root); /* alters list root */
root = mergelists(mergesort(root, cmp),
mergesort( p, cmp),
cmp);
}
/* else the unit or empty list is already sorted */

return root;
} /* mergesort */
Exactly. The algorithm you use is a recursive mergesort. The OP
was asking when you would use an iterative mergesort, i.e., one
that does use not use recursion. The fact that a lot of your
code uses iteration rather than iteration is irrelevant.


Richard Harter, cr*@tiac.net
http://home.tiac.net/~cri, http://www.varinoma.com
Save the Earth now!!
It's the only planet with chocolate.
Jun 27 '08 #20
On Thu, 05 Jun 2008 15:32:41 GMT, cr*@tiac.net (Richard Harter)
wrote:

>Exactly. The algorithm you use is a recursive mergesort. The OP
was asking when you would use an iterative mergesort, i.e., one
that does use not use recursion. The fact that a lot of your
code uses iteration rather than iteration is irrelevant.
Er, that should be "iteration rather than recursion".

Richard Harter, cr*@tiac.net
http://home.tiac.net/~cri, http://www.varinoma.com
Save the Earth now!!
It's the only planet with chocolate.
Jun 27 '08 #21

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Hung Jung Lu | last post by:
Hi, I have been looking into AOP (Aspect-Oriented Programming) for sometime, now. I frankly don't like the syntax of any of the approaches I have seen so far. I am kind playing around with some...
7
by: Michael Foord | last post by:
#!/usr/bin/python -u # 15-09-04 # v1.0.0 # auth_example.py # A simple script manually demonstrating basic authentication. # Copyright Michael Foord # Free to use, modify and relicense. #...
10
by: Bart Goeman | last post by:
Hi, I have a question about how to put redundant information in data structures, initialized at compile time. This is often necessary for performance reasons and can't be done at run time (data...
13
by: KV | last post by:
I'm new to OO Design, and I'm fixing to start writing my very first C# program. Given the complexity of OO programming, I would like to run something by this group and get general input. My...
26
by: Martin Jørgensen | last post by:
Hi, I don't understand these errors I get: g++ Persort.cpp Persort.cpp: In function 'int main()': Persort.cpp:43: error: name lookup of 'j' changed for new ISO 'for' scoping Persort.cpp:37:...
3
by: Ron Jackson | last post by:
I am using Python 2.5 on Windows XP. I have installed Pyserial and win32all extensions. When I try to run the example program scan.py (included below), or any other program using pyserial, as...
1
by: =?Utf-8?B?SmltIFdhbHNo?= | last post by:
I have an VC++ MFC Win32 application that isn't working correctly when I build it with VS2005. The problem seems to be in some ADO ActiveX controls that came with VS6 and are now out of support....
1
by: Eric_Dexter | last post by:
I compiled the comand line example and I am getting an error when I try to use the program when the program is cleaning up (I don't know that it would prevent the program from running though I will...
17
by: Thompson Reed | last post by:
Can someone give me an example C program with at least 20 lines of source code. That is the requirement and a line of code is a semicolon according to the rules. I have a job interview on Friday...
0
by: Stephen Thomas | last post by:
Hi there I wonder if any one has encountered this problem or can suggest what is wrong. I am trying the a procedure from the msn site but get the following message: Error 1 The type or...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.