Algorithms - Introduction
Algorithms - Introduction
Analysis of Algorithms
What Is an Algorithm?
• An algorithm is a sequence of unambiguous instructions for solving a
problem, i.e., for obtaining a required output for any legitimate input
in a finite amount of time.
OR
• Informally, an algorithm is any well-defined computational procedure
that takes some value, or set of values, as input and produces some
value, or set of values, as output. An algorithm is thus a sequence of
computational steps that transform the input into the output.
What Is an Algorithm?
What Is an Algorithm?
• Algorithms are essential to computer science, but they are not only
part of computer science.
Euclid’s Algorithm for finding GCD
• Problem: Find gcd(m,n), the greatest common divisor of two
nonnegative, not both zero integers m and n
Examples: gcd(60,24) = 12, gcd(60,0) = 60, gcd(0,0) = ?
• Euclid’s algorithm is based on repeated application of equality
gcd(m,n) = gcd(n, m mod n)
• until the second number becomes 0.
while n ≠ 0 do
r ← m mod n
m← n
n←r
return m
Other method for computing
gcd(m,n)
Consecutive integer checking algorithm
Step 1 Assign the value of min{m,n} to t
Step 2 Divide m by t. If the remainder is 0, go to Step 3;
otherwise, go to Step 4
Step 3 Divide n by t. If the remainder is 0, return t and stop;
otherwise, go to Step 4
Step 4 Decrease t by 1 and go to Step 2
Other method for computing
gcd(m,n)
• Note that unlike Euclid’s algorithm, this algorithm, in the form
presented, does not work correctly when one of its input numbers is
zero.
• This example illustrates why it is so important to specify the set of an
algorithm’s inputs explicitly and carefully.
Characteristics of an Algorithm
• Unambiguous: Algorithm should be clear and unambiguous. Each of
its steps should be clear in all aspects and must lead to only one
meaning.
• E.g., Cook a dish, bring me water
• You may get a common problem (searching, sorting etc.) and find an
already-developed algorithm.
• You should clearly specify the set of instances of input that are to be
handled by your algorithm.
• E.g., Binary Search
• A correct algorithm is not one that works most of the time, but one
that works correctly for all legitimate inputs.
Fundamentals of Algorithmic
Problem Solving
Ascertaining the Capabilities of the Computational Device
• Most of the algorithms are designed for the von Neumann machine.
• The RAM model assumes that instructions are executed one after
another, one operation at a time.
• The RAM model does not consider newer computers that can execute
operations concurrently, i.e., in parallel.
• Most of the time, you would not worry about the speed and memory
of the today’s computers.
• You should select appropriate data structures (arrays, linked lists etc.)
• Searching
• Graph Problems
Important Problem Types
Sorting
• Linear/sequential search
• Binary search
Important Problem Types
Graphs
• Graphs
• Undirected Graphs
• Trees