DAA-Unit-I
DAA-Unit-I
OF
ALGORITHMS
Dr. T. Anusha
Algorithms
• It is a well-defined computational procedure that takes a value, or set of values, as input and
produces a value, or set of values, as output in a unit amount of time. An algorithm is thus a
sequence of computational steps that transform the input into the output.
Goals of an Algorithm
Goals of an Algorithm
• Always correct
• Always terminates
• Performance
Correctness of an Algorithm
• An algorithm for a computational problem is correct if, for every problem instance
provided as input, it halts, finishes its computing in unit time and outputs the
correct solution.
FOUR DESIRED PROPERTIES OF ALGORITHMS
Definiteness
• Each instruction must be clear and unambiguous
Finiteness
• The algorithm must terminate
Correctness
• It must provide correct output when presented with legal input
Efficiency
• Each instruction must be very basic so that it can be easily carried out.
Sor ng problem
Output: permutation 〈a'1, a'2, …, a'n〉 such that a'1 ≤ a'2 ≤ … ≤ a'n .
Example:
Input: 8 2 4 9 3 6
Such an input is called as the instance of a problem.
Output: 2 3 4 6 8 9
ti
Sor ng problem
• Algorithm Validation
• Process of checking the correctness of algorithms.
• Performed by providing all valid inputs to the algorithm
and checking its outputs with expected results.
• Gives a guarantee that the given algorithm always gives
correct answers.
• The ability of an algorithm to give correct outputs for valid
inputs is called algorithm correctness.
• Program correctness checks whether the algorithm
conforms to the given specifications.
Prove the Correctness of Algorithm
Correctness of Algorithm
Correctness of Algorithm
• Initialization
• The loop invariant must be true before the first execution of the loop.
• Maintenance
• If the invariant is true before an iteration of the loop, it should be true also after
the iteration.
• Termination
• When the loop is terminated the invariant should tell us something useful,
something that helps us understand the algorithm.
Correctness of Inser on Sort
• At the start of each iteration of the for loop, the subarray A[1: i-1] consists of the elements
originally in A[1: i-1], but in sorted order. ==> Loop Invariant
ti
Correctness of Inser on Sort
• Initialization
• The first iteration happens when i is 2. A[1: i-1] has only one element, the first one.
• The array having one element is sorted.
• Maintenance
• The iteration moves A[i-1], A[i-2] ,… A[0] by one position to the right, so that A[i] is
placed in correct position.
• Thus A[1: i-1] keeps the original elements but in sorted order.
• Termination
• The loop terminates when i = n+1; then A[1: i] is in sorted order.
Hence the algorithm is correct.
ti
Time Complexity Analysis of Inser on Sort
ti
Best case for Inser on sort
Worst case:
Worst case: Input is in descending order. Here ti is i.
T(n)= x * n2 + y * n - z
Worst case:
Time complexity is a quadratic
function of n (input size)
ti
Average case for Inser on sort
• The worst case running time gives the upper bound on the run time.
• Worst case occurs often.
• Looking for a non-existent data in a database
• The average case occurs as often as the worst case.
• If n random numbers are chosen, then half the elements in A[1: i-1] are greater than A[i]
• So, ti is i/2. This again leads to n2 as the lead term just like the worst case.
ti
Worst, Best and Average case
Worst, Best and Average case
Algorithm Analysis
Algorithm
Analysis
getMax(arr, n):
index := 0
LinearSearch(A, n, key)
max := arr[0]
I := 0
while i < n, do for i in range 1 to n - 1, do
if A[i] = key, then if arr[i] > max, then
break
max := arr[i]
end if
done index := i
return i end if
done
return index
Opera on Count Method
C3 (n) C3 * n
C4 1 C4
Total=c1+c2*(n+1)+c3*n+c4
ti
is large,= so that means <roughly proportional to when is large= and
Rate of growth
means / Order
<roughly of growth
proportional to of an Algorithm
when is large= We’ll use -notation
informally in this chapter and deûne it precisely in Chapter 3.
We usually consider one algorithm to be more efûcient than another if its worst-
• case
The rate of growth is important for analysing an algorithm for large input size
running time has a lower order of growth. Due to constant factors and lower-
• order
So, theterms, an algorithm
leading whose running time has a higher order of growth might
terms are considered.
take less time for small inputs than an algorithm whose
Worst caserunning time
insertion has
sort: a lower or-
• der
Drop the constant co-effiecients
of growth. But on large enough inputs, an algorithm whose worst-case running
time is , for example, takes less time T(n)=
in x
the * n 2+y*n-z
worst case than an algorithm
• Drop the lower order terms
whose worst-case running time is . Regardless of the constants hidden by
• the -notation, there is always some. number, say , such that for all input sizes
The insertion sort’s leading term is n 2
2.2-1
Express the function in terms of -notation.
Rate of growth / Order of growth of an Algorithm
Asympto c Analysis
•Goal: to simplify analysis of running time by getting rid of”details”, which may be affected
by specific implementation and hardware
•like“rounding”: 1,000,001=1,000,000
•3n2=n2
•Capturing the essence: how the running time of an algorithm increases with the size of the
input in the limit.
•Asymptotically more efficient algorithms are best for all but small inputs
a t + a t + … + a t = f(n),
0 n 1 n−1 k n−k
Based on this fact, one can classify linear recurrence equations into two types:
linear recurrence equations with constant coefficients and those with variable
coefficients.
This recurrence equation is dependent on the variable n and does not have
constant coefficients.
Analysis of Framework
What is the recurrence equation for the sequence 1000, 2000, 4000,
8000, …?
Example
Solution
t0 = 1000
t1 = 2000 = 2 × 1000 = 2 × t0
t2 = 4000 = 2 × 2000 = 2 × t1 = 22 t0
tn = 2 × t(n-1)
It can be observed that tn = 2 × t(n-1) is the required recurrence equation of this problem.
Example
Find the recurrence equation and the initial condition of the following
sequence:
Find the recurrence equation and the initial condition of the following sequence:
7, 21/4 , 63/16, 189/64 , …
Solution
Let the initial condition be t0 = 7. Let us observe the patterns. Let us calculate the
ratios of the successive elements as follows:
Substitution Method
Solution As said earlier, first make a guess of the solution and then verify it.
Guess: For making a guess, use different values of n in the recurrence equation
as follows:
t0 = 1
t1 = t1−1 + 2 = t0 + 2 = 3
t2 = t2−1 + 2 = t1 + 2 = 5
t3 = t3−1 + 2 = t2 + 2 = 7
:
:
The sequence obtained (1, 3, 5, 7, …) indicates that every term differs from the
previous one by 2. This is an odd-number series. Therefore, one can guess that
the solution for the recurrence equation would be 2n + 1. As this is a non-recursive
formula in terms of n, this can be a solution. To confirm this, one should verify the
guess.
Examples of Input Size
Example
Another Example
T(n) = 2T(n − 1) + 1
Base case: T(0) = 0
Another Example
The process is continued till the closed form is obtained, which can be confirmed by the observation of the common pattern
that emerges from the process of repeated substitution
Forward Substitution
Recurrence Tree Method
Recurrence Tree Method
Designing Algorithms
• The method used in insertion sort - Increment Method
• Divide and Conquer method is used to design an algorithm with less worst-case run time.
• Divide
• Break the original problem into several sub problems
• Sub problems are similar to original problem
• But they are smaller in size
• Conquer
• Solve the sub problems recursively
• Combine
• Combine the solutions of sub problems to form the solution of the original problem.
• If the base problem is small, it is solved directly, else it is solved recursively.
Designing Algorithms
Merge Sort
Starts with the original array A[1:n]
In each step, it sorts a sub-array, recursing to smaller and smaller sub arrays.
MERGE-SORT A[1 . . n]
1.If n = 1, done.
2.Recursively sort A[ 1 . . ⎡n/2⎤ ] and A[ ⎡n/2⎤+1 . . n ] .
3.“Merge” the 2 sorted lists.
The recursion ends when the sub array can’t be spliced further, i.e, have only one element.
p q r
Merge Sort 1
12 3 7
2 3 4 5
9 14 6 11 2
6 7 8
divide 1 11
p q r p q r
1 2 3 4 5 6 7 8
12 3 7 9 14 6 11 2
divide 2 6 12 16
p,q r p,q r p,q r p,q r
1 2 3 4 5 6 7 8
12 3 7 9 14 6 11 2
divide 3 4 7 8 13 14 17 18
p,r p,r p,r p,r p,r p,r p,r p,r
1 2 3 4 5 6 7 8
12 3 7 9 14 6 11 2
merge 5 9 15 19
p,q r p,q r p,q r p,q r
1 2 3 4 5 6 7 8
3 12 7 9 6 14 2 11
merge 10 20
p q r p q r
1 2 3 4 5 6 7 8
3 7 9 12 2 6 11 14
merge 21
p q r
1 2 3 4 5 6 7 8
2 3 6 7 9 11 12 14
Merge Rou ne
Merging two sorted sub arrays [1, 4, 7, 11, 12] and [2, 3, 9, 10, 15]
Table 1
L R L R L R L R L R L R L R L R L R
12 15 12 15 12 15 12 15 12 15 12 15 12 15 12 15 12 15
11 10 11 10 11 10 11 10 11 10 11 10 11 10 11
7 9 7 9 7 9 7 9 7 9 9
4 3 4 3 4 3 4
1 2 2
1 2 3 4 7 9 10 11 12 15
ti
M ERGE
Merge Sort 1
2
// length of
// length of
3 let and be new arrays
4 for to // copy into
5
6 for to // copy into
7
2.3 Designing algorithms 39 8 // indexes the smallest remaining element in
9 // indexes the smallest remaining element in
10 // indexes the location in to ûll
M ERGE -S ORT 11 // As long as each of the arrays and contains an unmerged element,
1 if // zero or one element? // copy the smallest unmerged element back into .
2 return 12 while and
3 // midpoint of 13 if
4 M ERGE -S ORT // recursively sort 14
5 M ERGE -S ORT // recursively sort 15
6 // Merge and into . 16 else
7 M ERGE 17
18
19 // Having gone through one of and entirely, copy the
rays to form sorted subarrays of length , merges those to form sorted subarrays
// remainder of the other to the end of .
of length , and merges those to form the ûnal sorted subarray of length . If
20 while
is not an exact power of , then some divide steps create subarrays whose lengths
21
differ by . (For example, when dividing a subarray of length , one subarray has
length and the other has length .) Regardless of the lengths of the two subarrays 22
being merged, the time to merge a total of items is . 23
24 while
25
2.3.2 Analyzing divide-and-conquer algorithms
26
When an algorithm contains a recursive call, you can often describe its running 27
Time Complexity of Merge Sort