Introduction to Algorithm Analysis Study Notes
Introduction to Algorithms
Definition: An algorithm is a step-by-step procedure for solving a specific computational problem.
Composition: It consists of a finite set of instructions that, when followed, accomplish a particular task.
Multiple Solutions: For any given problem, there can be infinitely many correct algorithms.
Optimization Goals: A high-quality algorithm should be optimized for both time and space efficiency.
Characteristics and Properties of an Algorithm
Input: An algorithm must have zero or more quantities supplied externally.
Output: At least one output must be produced.
Definiteness: Every instruction must be clear and unambiguous. Operations that are not permitted include:
Ambiguous commands like "add 6 or 7 to x"
Finiteness: The algorithm must terminate after a finite number of steps.
Note: Continuous programs like Operating Systems (which stay in a "wait" loop), database servers, or web servers are providing services and are not classified as algorithms because they do not necessarily terminate.
Effectiveness: Every instruction must be basic enough that it can be carried out by a person using only pencil and paper in a finite amount of time.
Computational Procedures: Algorithms that satisfy both definiteness and effectiveness are also known as computational procedures.
Algorithm vs. Program
Feature | Algorithm | Program |
|---|---|---|
Phase | Used during the design phase of the software development life cycle. | Used during the implementation/development phase. |
Knowledge | Requires problem or domain knowledge (e.g., Doctors for hospitals, Accountants for accounts). | Requires a programmer with language expertise. |
Language | Uses natural language, mathematical notation, or pseudo-code. | Written in specific programming languages like C, C++, Java, or Python. |
Dependency | Independent of hardware, software, or operating systems. | Dependent on hardware, software, and operating systems. |
Process | Involves analysis of the design. | Involves testing and debugging. |
Finiteness | Must satisfy the finiteness condition (must terminate). | Does not have to satisfy the finiteness condition. |
Algorithm Specification Methods
Natural Language: Typically written in common languages like English.
Graphical Representation: Using flowcharts. This method is effective primarily for small and simple algorithms.
Pseudo-code: Describes algorithms as programs using a syntax that resembles programming languages like C or Pascal.
Analysis of Algorithms: Time and Space Complexity
Analysis Objective: Determining how much time and memory space an algorithm requires to solve a problem.
Performance Metrics:
Time Complexity: The total computer time an algorithm needs to run to completion.
Space Complexity: The total memory an algorithm needs to run to completion.
External Factors: Algorithm performance is influenced by the hardware, operating system, compiler, size of input , and nature of the input.
Detailed Time Complexity Components
Program Time: Total time is the sum of compile time and run/execution time.
Independence of Compile Time: Compile time is generally independent of the specific instance characteristics of the problem.
Affecting Factors:
Characteristics of the compiler used.
Physical clock and machine on which the program executes.
Multiuser environment overhead.
Number of program steps.
Time Formula: For any algorithm , the time is calculated as:
Measurement of Complexity: Time complexity quantifies the amount of time taken as a function of the input length . It measures the variation in execution time relative to the number of operations performed, rather than the absolute time.
Step Count Definitions for Code Statements
Comments: Zero (0) steps.
Assignment Statements: One (1) step (if no external algorithm calls are involved).
Iterative Statements: Step count is assigned to the control part of the statement.
Total Calculation: If a statement inside a loop repeats, the frequency is multiplied by the time required for a single execution.
Common Problems and Primitive Operations
Problem | Associated Primitive Operation | Input Size |
|---|---|---|
Search for in array | Comparison of with elements of | Array size |
Multiply 2 matrices | Multiplication and Addition | Dimension of the matrix |
Sorting | Comparison | Array size |
Graph Traversal | Edge traversal frequency | Number of vertices and edges |
Recursive Procedure | Number of recursive calls | Array size/Input size |
Factorial | Multiplication | The input number |
LCM(a, b) | Basic arithmetic (division, subtraction) | Bits needed to represent a and b |
Space Complexity Components
Fixed Component: Independent of input/output characteristics. Includes:
Instruction space (code).
Space for simple variables and fixed-size component variables.
Space for constants.
Variable Component: Dependent on the problem instance. Includes:
Referenced variables.
Recursion stack space.
Structural components (Linked lists, heaps, trees, graphs).
Space Formula:
is the constant fixed component.
Frequency Count Method: Case Studies
Swapping Two Numbers
Code:
temp = a;(1),a = b;(1),b = temp;(1).Time Function: (Constant, ).
Space Function: (Constant, ).
Sum of Array Elements
Algorithm:
Sum(A, n)initializess = 0, then loopsfor (i=0; i < n; i++)to adds = s + A[i]andreturn s.Time Analysis:
s = 0: 1 timefor(i=0; i<n; i++):i=0(1 time),i < n( times),i++( times). Summed control count is .s = s + A[i]: times.return s: 1 time.Total Time Function: (Degree ).
Space Analysis:
Variables: ( words), (1), (1), (1).
Total Space Function: (Degree ).
Matrix Addition ( matrix)
Time Analysis: Nested loops. Outer loop runs times. Inner loop runs times. Calculation statement runs times.
Total Time Function: (Degree ).
Space Analysis: Arrays each take space. Scalars take 1 each.
Total Space Function: (Degree ).
Matrix Multiplication ( matrix)
Loop Structure: Triple nested loops (indices ).
Time Analysis:
Outer loop ():
Middle loop ():
Assignment
C[i,j] = 0:Inner loop ():
Calculation:
Total Time Function: (Degree ).
Space Complexity: (Degree ).
Complexity Analysis of Typical Code Patterns
Pattern | Time Analysis | Big-O |
|---|---|---|
| ||
| ||
| ||
| ||
| ||
| ||
| ||
Double nested loops (standard) | ||
| ||
| ||
Multi-loop: |
Growth Rate Comparison and Ordering
Functions ordered by growth rate (from slowest to fastest):
(Constant)
(equivalent to , as the constant factor 2 is dropped)
Common Complexity Classes
(Constant): Finding if a number is even/odd, checking if an item is null, printing the first element of a list.
(Logarithmic): Binary Search.
(Linear): Finding max/min values in an array, linear search.
(Linearithmic): Merge sort, Quick sort.
(Quadratic): Bubble sort, Selection sort, finding duplicate values in a collection.
(Polynomial): Matrix multiplication ().
(Exponential): Power set (), Fibonacci, Travelling Salesman via dynamic programming.`
(Factorial): String permutations, Brute-force Travelling Salesman.
Asymptotic Notations
Asymptotic analysis focuses on the "significant term" of the function, describing limiting behavior as tends to infinity.
Big-Oh : Asymptotic Upper Bound
Definition: if there exist positive constants and such that for all .
Usage: Represents a tight or loose upper bound. It is preferred to provide the closest possible function.
Example: for , so .
Big-Omega : Asymptotic Lower Bound
Definition: if there exist positive constants and such that for all .
Usage: Represents the guaranteed minimum performance.
Example: for , so .
Theta : Asymptotic Tight Bound
Definition: if there exist positive constants and such that for all .
Usage: Used for the average bound. An algorithm is only if it is both and .
Little-oh : Non-tight Upper Bound
Definition: if .
Relationship: Indicates that becomes insignificant relative to as grows.
Example: .
Little-omega : Non-tight Lower Bound
Definition: if .
Types of Analysis Cases
Worst Case: Provides an upper bound on running time. It serves as an absolute guarantee that the algorithm will not exceed this limit for any input.
Best Case: Provides a lower bound on running time. This describes the scenario where the algorithm runs at its fastest speed.
Average Case: Provides a prediction of the running time based on the assumption that input data is random. Any notation () can mathematically represent any of these cases, but they are conceptually distinct.
Rules for Asymptotic Analysis
Drop constants: becomes .
Drop lower order terms: becomes .
Polynomials vs Logarithms: Any polynomial dominates any logarithm.
Exponentials vs Polynomials: Exponential functions dominate polynomials.
Log Base: In algorithm analysis, "log" typically refers to unless specified otherwise.