Академический Документы
Профессиональный Документы
Культура Документы
Mathematical Model
Informal algorithm
Data Structure
(DS)
Program
(C-Program)
1 INTRODUCTION
1. Non-Computational problem
A problem that has no precise and simple specification
Example: Convince your boss for salary hike, convince your faculty for marks.
2. Computational Problem
Specification of input
6. Performance Evaluation
As an algorithm is executed, it uses the computers CPU to perform operations and its memory to
hold the program and data.
An efficient algorithm
needs less running time
uses less space
6.1 Space Complexity: The space complexity of an algorithm is the amount of memory it needs
to run to completion.
6.2 Time Complexity: The time complexity of an algorithm is the amount of computer time it
needs to run to completion.
6.3 Performance evaluation of an algorithm refers to the task of computing space and time
complexity of an algorithm.
Performance evaluation can be loosely divided into two major phases:
1) a priory estimates(Performance Analysis)
Uses analytical methods
Machine independent
2) a posterior testing (Performance Measurement or profiling):
It is the process of executing a correct program on data sets and measuring time
and space it takes to compute results
Machine dependent
Performance Analysis is general methodology because
It uses high level description of an algorithm(Pseudo-code)
All possible input instances are taken into account
Machine independent
7. Space Complexity
Components of space complexity
7.1 Instruction space: Space needed for code
7.2 Data Space:
(1) Space needed for constants and simple variables
(2) Space needed for dynamically allocated objects (Such as arrays, structures, etc.)
7.3 Environment stack space: It is used to save information needed to resume execution of
partially executed function.
Each time a function is invoked the following data are saved on the environment stack
The return address
The values of local variables and formal parameters
7.4 Recursion stack space: Amount of stack space needed by recursive functions is called
recursion stack space. It depends on
Space needed by local variables and formal parameters
Maximum depth of recursion (i.e., maximum number of nested recursive calls)
Compiler being used
The total space needed by a program is divided into two parts:
A fixed part independent of instance characteristics (e.g., size, number, value)
1. Instruction space
2. Data space( space needed for constants and simple variables and some dynamically
allocated objects)
Note: The space needed by some of the dynamically allocated memory may also be
independent of
problem size
3. Environment stack space for non-recursive functions
A variable part dependent on instance characteristics
1. Dynamically allocated space
2. Recursion stack space
7.5 Definition
The space complexity S(P) of any algorithm P can be written as
S(P) = C + SP(I)
C constant that denotes fixed part
SP Variable part that depends on instance characteristics (I) (e.g., size, number, value)
Examples
1.
Algorithm abc(a, b, c)
{
return a+b+b*c/(a+b+4.0);
}
C= Space needed for a, b, c and result;
SP(abc)=0
2.
Algorithm Sum(a,n)
{
s=0;
for(i=1 to n)
s=s+a[i];
return s;
}
Space required for
formal parameters a and n
local variables s ,i and constant 0
instruction space.
This amount of space needed does not depend on value of n.
Ssum(n) =0
Since a is actually the address of the first element in a[](i.e., a[0]), the space needed by it is also
constant.
3.
Algorithm rsum(int a[], int n)
{
if(n>0)
return rsum(a, n-1)+a[n-1];
return 0;
}
Let
reference of a =4 bytes;
value of n = 4 bytes;
return address = 4 bytes
are stored on recursion stack for each recursion call.
Each recursive call require 12 bytes
Depth of recursion=(n+1)
recursion stack space =12(n+1)
Srsum(n) = 12 (n+1)
8. Time Complexity
Time taken by a program P is sum of compile time and runtime
T (P) =C+TP (I)
C (compile time) is independent of instance characteristics ( constant).
TP (I) (Run time) is dependent on instance characteristics.
(i) However, analytical approach to determine the exact runtime is complicated.
Since runtime depends on machine dependent issues like i) Type ofprocessor, ii) Access
rate (read/write operations), iii) Architecture and machine independent issue iv) input
size.
Size of input
number of elements in array(one parameter)
Number of items to be sorted.
i.e., number of elements in array(one parameter)
Dimension of matrices(pxq, qxr)(three parameters)
numbers of vertices and edges.(Two parameters)
(iv) Assumption
We define notion of step as machine independent as possible.
Let each line/statement/step of our pseudo code execute in constant time so that analysis of
algorithm is machine independent
Definition: Total runtime (Time Complexity)
The running time of the algorithm is the sum of running times for each statement executed.
=
( ) (. )
Example:
Program/Pseudo code
int sum(int a[], int n)
{
int s=0;
int i;
for(i=0;i<n;i++)
s+=a[i];
return s;
}
C1
C2
C3
C4
C5
1
0
n+1
n
1
Example:Linear search
Pseudo code
LinearSearch(A, n, k)
A[n+1]=k;
i=1;
while(A[i]k)
i++;
if(i<=n)
return i;
else
return -1;
cost times
C1
C2
C3
C4
C5
1
1
ti
ti-1
1
9. Sorting Problem
Input: a sequence <a1,a2,...,an> of n numbers.
Output: a permutation <a1',a2',...,an'> of the input with a1' <= a2' <= ... <= an'.
Usually, the numbers to be sorted are part of a collection of data called a record. Each record
contains a key, which is the value to be sorted.
Example of a record
Key Other data
9.1 Some definitions
Internal Sort
The data to be sorted is all stored in the computers main memory(RAM).
External Sort
Some of the data to be sorted might be stored in some external, slower, device.
In Place Sort
The amount of extra space required to sort the data is constant w.r.to input size.
Stable sort
A STABLE sort preserves relative order of records with equal keys
Ideal Sorting
The ideal sorting algorithm would have the following properties:
Stable: Equal keys aren't reordered.
Operates in place, requiring O(1) extra space.
Worst-case O(nlg(n)) key comparisons.
Worst-case O(n) swaps.
Adaptive: Speeds up to O(n) when data is nearly sorted or when there are few unique
keys.
There is no sorting algorithm that has all of these properties, and so the choice of sorting
algorithm depends on the application.
Definition
Invariant
An invariant is a property of data that is unmodified by an algorithm, typically a set of
relationships that hold between elements.
Finding invariants makes it easier to prove properties of the algorithm.
SELECTION SORT
Pseudocode
Selection sort (A,n)
Cost Times
C1
min=i;
C2
n-1
for (j=i+1 to n)
C3
n
n1
n1
i=1 j=i+1 1 = i=1 (n i)// Comaprisons
C5
n1
i=1 (n i) //Swaps
n-1
Loop Invariant
At start of each iteration of outer for loop, the sub array A[1.j-1] consists the j-1 smallest
elements in the array A[1n] in the sorted order.
Worst Case Analysis
n1 n1
() = 1
i=1 j=i+1
n1
i=1 n
=
i1
=(n-2)+(n-3)+.+1=(n-1)(n-2)/2=(n2)
Properties
1 Complexity
Best-case Worst-case Average-case
(n2)
(n2)
(n2)
2. Not Stable
3. In-place
4. (n2) comparisons
5. (n) swaps(Exchanges)
6. Selection sort takes about n2/2 comparisons and n swaps
7. Not Adaptive
8. Selection sort is used for sorting files with very large values and small keys.
BUBBLE SORT
BubbleSort(A, n)
for i = 1 to n-1 do
for j = 1 to n-1-i do
If (a[j+1] < a[j])
swap a[j] anda[j+1]
BubbleSort_modified(A, n)
for i = 1 to n-1 do
count=0;
for j = 1 to n-1-i do
If (a [j+1] < a[j])
Swap (a[j] ,a[j+1])
count++;
if(count==0) return
Loop Invariant:
At the start of each iteration of the outer for loop, the subarray A [n-i+1..n] consists of the i
largest elements in the array A[1 . . n] in sorted order.
Properties
1 Complexity
Best-case
Worst- Averagecase
case
2
(n ) BubbleSort
(n2)
2
(n) BubbleSort_modified (n )
2. Stable
3. In-place
4. O (n2) comparisons and O (n2) swaps
5. About n2/2 comparisons and n2/2 swaps in both average and worst case
6. Adaptive
INSERTION SORT
Pseudo code
INSERTION-SORT(A, n)
Cost Times
for j= 2 to n
C1
C2
n-1
i =j 1
C3
n-1
C4
nj=2 t j // comparisons
key= A[ j]
//Insert A[ j ] into the sorted sequence A[1 . .j -1]
A[i + 1] = A[i]
//exchanges
C5
i=i 1
C6
A[i + 1] = key
C7
nj=2 t j 1 // exchanges
nj=2 t j 1
n-1
j =2
j =2
j =2
=
>
j
j
1
( j 1) =
2
2
2
j 2
j 2
=j 1 =
=
n(n 1)
n(n 1)
n(n + 1)
T (n) = c1 n + c 2 (n 1) + c3 (n 1) + c 4
1 + c 5
+ c6
+ c7 (n 1)
2
2
2
Loop Invariant:
At the start of each iteration of the outer for loopthe loop indexed by jthe subarray
A[1 . . j-1] consists of the elements originally in A[1 . . j-1] but in sorted order.
Properties
1. Complexity
Best-case
(n)
Worst-case
(n2)
Average-case
(n2)
2. Stable
3. In-place
4. O (n2) comparisons and O (n2) swaps
5. Insertion sort takes about n2/4 comparisons and n2/8 swaps on random input (average case)
and in the worst case, they are double.
6. Adaptive (Insertion sort is linear for almost sorted arrays)
General rules
1. Assignment O(1)
2. Linear for loop
O(Number of iterations in a loop * Number of statements inside the loop)
Example:for( i=0 to n)
{
print ( hi );
x = x+1;
y =y+1;
}
T ( n ) = ( 3 * n ) = (n)
3. Nested Loops:
Analyze the innermost loop first, complexity of next outer loop = number of iterations in this
loop * complexity of inner loop, etc..
Example:
sum = 0;
for (i=0; i < N; i++)
for (j=0; j < N; j++)
sumsum + 1;
Inner loop: (N)
Outer loop: N iterations
Overall: (N2)
4. If-then-else statements:
Worst-case running time: the test, plus the if part or the else part (whichever is the larger).
if (Condition)
S1
else
S2
5. Consecutive statements: Add the time complexities of each statement.
Practice Problems
1. Best case for an algorithm
(a) takes the same time for all data;
(b) assumes the data that the algorithm handles in the greatest time;
(c) assumes the data that the algorithm handles in the least time;
(d) is the expected time considering all possible input data;
2. Worst case for an algorithm
(a) takes the same time for all data;
(b) assumes the data that the algorithm handles in the greatest time;
(c) assumes the data that the algorithm handles in the least time;
(d) is the expected time considering all possible input data;
3. Average case for an algorithm
(a) takes the same time for all data;
(b) assumes the data that the algorithm handles in the greatest time;
(c) assumes the data that the algorithm handles in the least time;
(d) is the expected time considering all possible input data;
4. The time complexity of Insertion sort is
(a) O(lg n); (b) O(n);
(c) O(n2);
(d) O(2n)
(d) (n2)
(b) (n)
(c) (n)
(d) (n2)
(d) (n lg n)
(d) (n2)
(a) (lg n)
(b) (n)
(c) (n2)
(d) (n n))
(a) (lg n)
(b) (n)
(c) (n2)
(d) (n n)
(c) (n2)
(d) (n n)
(a) (1)
(b) (lg n)
(c) (n)
(d) (n)
(a) (1)
(b) (lg n)
(c) (n)
(d) (n)
(b) (lg n)
(c) (n)
(d) (n)
(a) (1)
(b) (lg n)
(c) (n)
(d) (n)
(d) (n3)
(d) (n2)
(d) (n2)
(d) (n2)
(d) (n2)
(d) (n2)
(d) (n)
(d) (n2 lg n)
(d) (n5/2)
(d) (n2)
(d) (n5)
(d) (n4)
(d) (n)
31. Consider the following C-program fragment in which i, j and n are integer variables.
j=0;
for (i = n, ; i > 0; i /= 2)
j +=i;
Let val (j) denote the value stored in the variable j after termination of the for loop. Which
one of the following is true?
(A) val (j) = ( log n)
(B) val (j) = ( n)
(C) val (j) = (n )
(D) val (j) = (n log n)
32. Consider the following function:
int unknown int n {
int i, j, k=0;
for(i=n/2; in; i++)
for(j=2; jn; j=j*2)
k=k+n/2;
return k;
}
The return value of the function is
(A) (n2)
(D) (n3 lg n)