Unit 1 Updated
Unit 1 Updated
Lesson 4. Recursion
Lesson 5. Searching: Linear Search and Binary Search Techniques, and their complexity
A[0] 10 20 30
A[1] 40 50 60
A[2] 70 80 90
• Example –to delete name of a student who has left the course
• Combining the list of two files of sorted data items into a single
sorted file
42
50
© Kalasalingam academy of research and education 50
Algorithm Analysis
• Time taken by an algorithm?
– How long the algorithm takes :-
• will be represented as a function of the size of the input.
• f(n)→how long it takes if ‘n’ is the size of input.
– How fast the function that characterizes the
running time grows with the input size.
• “Rate of growth of running time”.
• The algorithm with less rate of growth of running time is
considered better.
© Kalasalingam academy of research and education 51
Asymptotic Notations
• Asymptotic Notations are languages that allow us to analyze
an algorithm’s running time by identifying its behavior as the
input size for the algorithm increases.
• This is also known as an algorithm’s growth rate.
• The word Asymptotic means approaching a value or curve
arbitrarily closely (i.e., as some sort of limit is taken).
This function runs in O(1) time (or "constant time") relative to its input. The input array could be 1
item or 1,000 items, but this function would still just require one step.
© Kalasalingam academy of research and education 58
Big-O Notation (Ο)
• O(n)
– Big O notation O(N) represents the complexity of an algorithm, whose
performance will grow linearly (in direct proportion) to the size of the
input data.
– O(n)example
– This function runs in O(n) time (or "linear time"), where n is the number of items in the
array. If the array has 10 items, we have to print 10 times. If it has 1000 items, we have to print 1000
times.
© Kalasalingam academy of research and education 59
Big-O Notation (Ο)
• O(n2)
– Big O notation O(n2) represents the complexity of an algorithm,
whose performance is directly proportional to the square of the
size of the input data.
– O(n2) example
• Traversing a 2D array
61
int add(int a,
int b)
{
return a+b;
}
While reducing the problem size, there should be a limit after which
the problem size reduction should not go on.
•STOPPING CONDITION
element
element
element
element
element
element
low high
middle
Searching for 18.
© Kalasalingam academy of research and education 102
Binary Search Example
low high
middle
Searching for 18: found!
17
© Kalasalingam academy of research and education 103
Binary Search – Example 2
Example: sorted array of integer keys. Target=7.
3 6 7 11 32 33 53
3 6 7 11 32 33 53
3 6 7 11 32 33 53
3 6 7 11 32 33 53
3 6 7 11 32 33 53
3 6 7 11 32 33 53
3 6 7 11 32 33 53
3 6 7 11 32 33 53
3 6 7 11 32 33 53
3 6 7 11 32 33 53
3 6 7 11 32 33 53