3 ms·
Ok. A fun exercise is to write a topological sort of a graph in both iterative and recursive styles. I've used this as an interview question at least 100 times
by titzer 5y ago
Ok. A fun exercise is to write a topological sort of a graph in both iterative and recursive styles.
I've used this as an interview question at least 100 times, so I've got at least 50 hours of watching people try to program this and with extremely high probability your iterative solution will be ugly and hard to follow and the recursive one very tidy. Of course, you can screw up the recursive one, but it so straightforward it almost writes itself.
- ncmncm 5y agoOn an interview I would, of course, go straight for recursion. In production, and where performance matters, I might try both. A more meaningful interview question would be to present a recursive topo sort and ask for the iterative rendition.
- deleted 5y ago[deleted]
- qsort 5y agoI think in this particular case I'd go for the iterative one -- it's impossible to screw up (at least in the "keep track of the indegree" variant, I don't know if that's what you're thinking) But the point you're making stands: recursion is first and foremost a thinking tool. Code as you think it need not be the same as code as you type it.