Docsity

Recursing - Biological and Cognitive Sciences - Lecture Notes, Study notes of Biogenetics and Computers

Partial preview of the text

Download Recursing - Biological and Cognitive Sciences - Lecture Notes and more Study notes Biogenetics and Computers in PDF only on Docsity!

Divide a big problem into two or more smaller

problems.

Solve the smaller problems.

Combine the results into one larger problem.

Very often, a computer algorithm requires some form of

divide-and-conquer

Divide-and-conquer

Docsity.com

Recursive definition => recursive algorithm

If an array has one element, its maximum is that element,

split the array in half, and

compute the maximum for each half, and

take the maximum of those two.

else

Recursive definition of maximum element:

Example: Finding the maximum

Docsity.com

sub maxer { my $thing = shift; my $length = @$thing; if ($length == 1) { # one thing is its own max! return $thing->[0]; } else { # split into two arrays! my $size = @$thing; my $mid = int($size/2); my $bot = [@$thing[0..$mid-1]]; my $top = [@$thing[$mid..$size-1]]; my $sbot = &maxer($bot); my $stop = &maxer($top); if ($sbot<$stop) { return $stop; } else { return $sbot; } } } Pasted from Finding the maximum Docsity.com

At each step, the array gets 1/2 as large.

But we have to do the thing for both halves.

We're going to do O(n) comparisons at each level.

There are O(log n) levels

Thus the algorithm is O(n log n) in time.

Runtime for maxer

Docsity.com

one root 0 or more children each child is the root of a tree. N-ary tree:

A recursive structure

Docsity.com

A key idea: if a structure is recursive, then so is the

algorithm that works on it.

Algorithms on recursive structures

Docsity.com

$company->{foo}->{bar} is the children of bar, that must be a child of foo. Docsity.com