Why Study Algorithms?
Theoretical Reasons
- Algorithms form the cornerstone of computer science.
Practical Reasons
- Understanding essential algorithms is crucial across different computing areas.
What is an Algorithm?
An algorithm is a sequence of unambiguous instructions for solving a problem, producing a required output for any valid input in finite time.
Example: Sorting
- Input: A sequence of numbers
- Output: A sorted sequence such that whenever .
- Algorithms: Selection sort, Insertion sort, Merge sort
Properties of Algorithms
- Each step must be unambiguous.
- The valid input range should be clearly defined.
- An algorithm can be expressed in multiple ways.
- Multiple algorithms can solve the same problem with different efficiencies.
Problem: Greatest Common Divisor (GCD)
Definition: Find the greatest common divisor of two nonnegative integers and , where at least one is nonzero.
Example
Solutions to GCD
Euclid’s Algorithm
- If , return .
- Otherwise, compute .
Example:
Pseudocode Representation:
Algorithm Euclid(m, n)
while n ≠ 0 do
begin
r = m mod n
m = n
n = r
end
return mConsecutive Integer Checking Algorithm
- Set .
- If , check .
- If true, return .
- Otherwise, decrement and repeat.
Example (Partial Steps for )
- Start with .
- Decrease until a common divisor is found.
Middle-School Procedure
- Find prime factors of and .
- Identify common prime factors.
- Multiply them to get .
Example:
Fundamentals of Algorithmic Problem Solving
- Understand the problem.
- Know the computational limits.
- Choose exact or approximate solving methods.
- Decide on data structures.
- Use algorithm design techniques.
- Specify algorithms (pseudocode, flowcharts).
- Prove correctness.
- Analyze efficiency (time, space, simplicity, generality).
- Implement in code.
Important Problem Types
- Sorting: Arrange items in order.
- Searching: Find a value in a dataset.
- String Processing: Locate patterns in text.
- Graph Problems: e.g., Traveling Salesman, Graph Coloring.
- Combinatorial Problems: Solve constraints with desired properties.
- Geometric Problems: e.g., Closest-Pair Problem.
- Numerical Problems: Solve equations, compute integrals, etc.
Test Your Understanding
- Problem: Implement Euclid’s Algorithm for computing . What is the result?
- 2