Algorithms Unit-1
Algorithms Unit-1
3. Theta (θ): The theta notation is both an upper and lower bound, so it defines
exact asymptotic behaviour. Mathematically it is defined as:
f(n) = Θ(g(n)) [read as "f of n is theta of g of n"], if there exists a positive
constants c1, c2 and n0 , such that 0 ≤ c1.g(n) ≤ f(n) ≤ c2.g(n) ∀ n ≥ n0
Analysis:
1. Input: n elements are given.
2. Output: the number of comparisons required to make sorting.
3. Logic: If we have n elements in insertion sort, then n-1 passes are required to
find a sorted array.
In pass 1: no comparison is required
In pass 2: 1 comparison is required
In pass 3: 2 comparisons are required
............................................................................
...............................................................................
In pass n: n-1 comparisons are required
Total comparisons: T (n) = 1+2+3+...........+ n-1
= (n-1)n / 2
= O (n2)
Therefore complexity is of order n2
Divide and Conquer paradigm: Divide and Conquer algorithm consists of a
dispute using the following three steps.
1. Divide the original problem into a set of sub-problems of less size.
2. Conquer: Solve every sub-problem individually, recursively.
3. Combine: Put together the solutions of the sub-problems to get the solution to
the whole problem.
Divide
Sub-problem Sub-problem
Solve Solve
Conquer
Sub-problem Sub-problem
Solution to Solution to
Sub-problem Sub-problem
Combine
Solution to
the Problem
Examples: Some of the algorithms based on the Divide & Conquer approach
include:
1. Binary Search
2. Sorting (merge sort, quick sort)
The principles of Divide & Conquer Strategy are:
1. Relational Formula
2. Stopping Condition
Advantages of Divide and Conquer
It minimizes the effort of designing an algorithm as it works on dividing the
main problem into two or more sub-problems of less size and then solve them
recursively.
It efficiently uses cache memory without occupying much space because it
solves simple sub-problems within the cache memory instead of accessing the
slower main memory.
Disadvantages of Divide and Conquer
An explicit stack may overuse the space.
It may even crash the system if the recursion is performed rigorously greater
than the stack present in the CPU.
Recurrence Relation: A recurrence is an equation or inequality that describes a
function in terms of its values on smaller inputs. To solve a Recurrence Relation
means to obtain a function defined on the natural numbers that satisfy the
recurrence.
For example in Merge Sort, to sort a given array, we divide it in two halves and
recursively repeat the process for the two halves. Finally we merge the results. Time
complexity of Merge Sort can be written as T(n) = 2T(n/2) + cn. There are mainly
three methods for solving Recurrences:
1. Substitution Method
2. Recursion Tree Method
3. Master Method