Data Structure with C
-
Upload
syed-mustafa -
Category
Education
-
view
521 -
download
2
description
Transcript of Data Structure with C
1
2
Syllabus
Prof. A. Syed Mustafa (Ph.D)3
Syllabus
Prof. A. Syed Mustafa (Ph.D)4
Syllabus
Prof. A. Syed Mustafa (Ph.D)5
Syllabus
Prof. A. Syed Mustafa (Ph.D)6
7
Evaluation
• Grade Percentage
– FCD : 70% and above
– FC : 60% - 69%
– SC : 35% - 59%
– FL : less than 35%
• Syllabus Coverage Schedule
– 1st IA Test : 30% [ Portion- first 2.5 Units ]
– 2nd IA Test : 30% [ Portion- next 2.5 Units ]
– 3rd IA Test : 40% [ Portion- Last 3 Units ]
8
Evaluation• Assignments
– Total : 3
– Each Assignment to be submitted before the IA test
begins
• Attendance
– Class Participation: 85%
• You may get detained if you miss (more than) ¼ of the whole classes
• Academic dishonesty (e.g. cheating, copying, late coming and etc.) will be taken seriously
9
Announcement• Class Website
• The link for the CMS portal is:
– Intranet link: http:\\172.17.0.2\moodle
– Internet link: http:\\61.8.153.222\moodle
– http://gg.gg/hkbkis
• Class information such as lecture notes can be accessible through this website
• We will also use Moodle for online test
10
Announcement
• Programming Assignments
– We encourage to study and discuss together for doing programming assignments.
– However, you must do programming YOURSELF.
– You must not share any of source code with other students.
– Any kind of academic dishonesty will be viewed very seriously.
Unit -1
Prof. A. Syed Mustafa (Ph.D)11
Basic concepts
Prof. A. Syed Mustafa (Ph.D)12
Basic Concepts
Topics :
Pointers and Dynamic Memory Allocation
Algorithm Specification
Data Abstraction
Performance Analysis
Performance Measurement
Prof. A. Syed Mustafa (Ph.D)13
Basic Concepts
Objectives
Understanding core concepts of memory management, performance analysis.
Applying the pointer concepts to actual programming
managing memory efficiently
Improve the performance.
Prof. A. Syed Mustafa (Ph.D)14
Basic Concepts
Course Outcome:
Able to apply the pointer concepts to actual programming
Able to use memory efficiently
Able to increase the performance of the program.
Prof. A. Syed Mustafa (Ph.D)15
Basic Concepts
System Life Cycle
• Large-Scale program contains many complex interacting
parts.
• Programs undergo a development process called the system
life cycle.
• Solid foundation in
1. data abstraction
2. algorithm specification
3. performance analysis and measurement
provides necessary methodology.
Prof. A. Syed Mustafa (Ph.D)16
Basic Concepts
System Life Cycle
5 phases of system life cycle:
1. Requirements: Begins with defining purpose of the project.What inputs (needs), outputs (results)
2. Analysis: Break the problem down into manageable pieces.bottom-up vs. top-down, divide and conquer
3. Design: data objects and operations creation of abstractdata types, the specification of algorithms and algorithmdesign strategies, ignore coding details.
4. Refinement & coding: choose representations for our dataobjects and write algorithms for each operation on them.
we should write those algorithms that are independent ofthe data objects first.
Prof. A. Syed Mustafa (Ph.D)17
Basic Concepts
System Life Cycle
5. Verification: consists of developing correctness proofs for theprogram, testing the program with a variety of input data andremoving errors.
Correctness proofs: proofs are very time-consuming anddifficult to develop for large projects. Scheduling constraintsprevent the development of a complete set of proofs for alarge system.
Testing: before and during the coding phase. testing is usedat key checkpoints in the overall process to determinewhether objectives are being met.
Error Removal: system tests will indicate erroneous code.Errors can be removed depending on the design & codingdecisions made earlier.
18
• For any type T in C there is a corresponding type pointer-to-T.
• The actual value of a pointer type is an address of memory.
– & the address operator.
– * the dereferencing ( or indirection ) operator.
– Declaration
• int i , *ip; // i is an integer variable and ip is a pointer to an integer.
• ip = &i;
then &i returns the address of i and assigns it as the value of pi.
Basic Concepts
Pointers
Prof. A. Syed Mustafa (Ph.D)
19
Basic Concepts
Pointers
• i = 10 or *ip = 10;
In both cases the integer 10 is stored as the
value of i.
In second case, the * in front of the pointer ip
causes it to be dereferenced,
by which we mean that instead of storing 10 into
the pointer, 10 is stored into the location
pointed at by the pointer ip.
Prof. A. Syed Mustafa (Ph.D)
20
Basic Concepts
Pointers
The size of a pointer can be different on
different computers.
The size of a pointer to a char can be longer
than a pointer to a float.
Test for the null pointer in C
if (ip == NULL) or if (ip==0) or if (!ip)
21
Basic Concepts
Pointers
The null pointer points to no object or
function.
The null pointer is represented by the integer
as 0 an in character as ‘\0’. The ASCII value for
NULL is 0.
The null pointer is interpreted as false in
relational expressions.
Prof. A. Syed Mustafa (Ph.D)
22
Basic Concepts
Dynamic Memory Allocation
• When we write program, we may not know how
much space we may need, to store data.
• C provides a mechanism called a heap, for
allocating storage at run-time.
• The function malloc() is used to allocate a new
area of memory.
Prof. A. Syed Mustafa (Ph.D)
23
Basic Concepts
Dynamic Memory Allocation
malloc()Syntax
void *malloc(size_t size)
Parameters
• size -- This is the size of the memory block, in bytes.
Return Value
• This function returns a pointer to the allocated memory,
or NULL if the request failsProf. A. Syed Mustafa (Ph.D)
24
Basic Concepts
Dynamic Memory Allocation
malloc()
• The name malloc stands for "memory allocation".
• The function malloc() reserves a block of memory
of specified size and return a pointer of
type void which can be casted into pointer of any
form.Prof. A. Syed Mustafa (Ph.D)
25
Basic Concepts
Dynamic Memory Allocation
• When memory is no longer needed, we may
free it by calling free() function.
• The call to malloc() determines size of
storage required to hold int or the float.
• The notations (int *) and (float *) are type
cast expressions.
Prof. A. Syed Mustafa (Ph.D)
26
Basic Concepts
Dynamic Memory Allocation
• The result is a pointer to the first byte of a
storage area of the proper size.
• The return value of the malloc() is void *.
• A call to malloc() may fail for lack of sufficient
memory
Prof. A. Syed Mustafa (Ph.D)
27
Basic Concepts
Dynamic Memory Allocation
Example:int *pi; float *pf;
pi = (int *) malloc (sizeof(int));
pf = (float *) malloc(sizeof(float));
*pi=1024; *pf=3.124;
printf(“an integer = %d, a float = %f\n”,*pi,*pf);
free(pi); free(pf);
Prof. A. Syed Mustafa (Ph.D)
28
Basic Concepts
Dynamic Memory Allocation
• When programming in C it is a wise practice to set all pointers to NULL
when they are not pointing to an object.
• Use explicit type casts when converting between pointer types:
pi = malloc(sizeof(int)); /* assign to pi a pointer to int */
pf = (float *) pi; /* casts an int pointer to float pointer */
• In many systems, pointers have the same size as type int. int is the
default type specifier.
Prof. A. Syed Mustafa (Ph.D)
29
Basic Concepts
Dynamic Memory Allocation
calloc()
• The name calloc stands for "contiguous memory
allocation“ or ‘c’ for cleared.
• The function calloc() allocates a block of memory for an
array of num elements, each of them size bytes long, and
initializes all its bits to zero.
30
Basic Concepts
Dynamic Memory Allocation
calloc()Syntax
void* calloc (size_t num, size_t size);
Parameters
• num -- Number of elements to allocate.
• size -- Size of each element
• size_t is an unsigned integral type.
Return Value
• On success, a pointer to the memory block allocated by the function.
• The type of this pointer is always void*, which can be cast to the desired type of data pointer in order to be dereferenceable.
•If the function failed to allocate the requested block of memory, a null pointer is returned.
Prof. A. Syed Mustafa (Ph.D)
31
Basic Concepts
Dynamic Memory Allocation
calloc()Example
int *ptr1,*ptr2;
ptr1 = (int *)calloc(10, sizeof(int));
ptr2=(int *)calloc(20,sizeof(float));Prof. A. Syed Mustafa (Ph.D)
32
Basic Concepts
Dynamic Memory Allocation
malloc () & calloc()Differrence
The only difference between malloc() and calloc() is
that, malloc() allocates single block of memory
whereas calloc() allocates multiple blocks of
memory each of same size and sets all bytes to
zero. Prof. A. Syed Mustafa (Ph.D)
33
Basic Concepts
Dynamic Memory Allocation
malloc () & calloc()Differrence
malloc function, whereas the area reserved to the states that
are undefined, the area allocated by the calloc function
contains a 0.
In fact, the calloc function is internally may be a function that
calls malloc. After securing function by malloc, the area is
filled with 0.
Prof. A. Syed Mustafa (Ph.D)
34
Basic Concepts
Dynamic Memory Allocation
free()Syntax
void free(void *ptr)
Parameters
• ptr -- Pointer to a memory block previously allocated with malloc(),
calloc() or realloc().Return Value
• None
Note:
If the memeory is not freed , then Dangling pointer arises which leads to garbage collection.
Prof. A. Syed Mustafa (Ph.D)
35
Basic Concepts
Dynamic Memory Allocation
Prof. A. Syed Mustafa (Ph.D)
36
Basic Concepts
Dynamic Memory Allocation
Prof. A. Syed Mustafa (Ph.D)
37
Basic Concepts
Dynamic Memory Allocation
Prof. A. Syed Mustafa (Ph.D)
38
Basic Concepts
Dynamic Memory Allocation
Prof. A. Syed Mustafa (Ph.D)
39
Basic Concepts
Dynamic Memory Allocation
realloc() -Reallocate memory block
void *realloc(void *ptr, size_t size)
• The C library function attempts to resize the memory block pointed to by ptr that was previously
allocated with a call to malloc or calloc or realloc
Parametersptr -- This is the pointer to a memory block previously allocated with malloc, calloc orrealloc to be reallocated.If this is NULL, a new block is allocated and a pointer to it isreturned by the function
•size -- This is the new size for the memory block, in bytes.If it is 0 and ptr points to anexisting block of memory, the memory block pointed by ptr is deallocated and a NULLpointer is returned.
Return ValueThis function returns a pointer to the newly allocated memory, or NULL if the requestfails.
Prof. A. Syed Mustafa (Ph.D)
40
Basic Concepts
Dynamic Memory Allocation
realloc() -Reallocate memory block
• The function realloc() reallocates a memory block with a specific new size.
• If we call realloc() the size of the memory block pointed to by the pointer is
changed to the given size in bytes.
• This way we are able to expand and reduce the amount of memory you
want to use (if available of course.)
• It is possible that the function moves the memory block to a new location,
in which way the function will return this new location.
• If the size of the requested block is larger then the previous block then the
value of the new portion is indeterminate.
Prof. A. Syed Mustafa (Ph.D)
41
Basic Concepts
Dynamic Memory Allocation
realloc() -Reallocate memory block
• The return value is a pointer to the reallocated memory block, which
may be either the same as ptr or a new location.
• The type of return pointer is void*, which can be cast to the desired
type of data pointer in order to be dereferenceable
• If the pointer is NULL then the function will behave exactly like the function
malloc(). It will assign a new block of a size in bytes and will return a pointer to
it.
• If the size is 0 then the memory that was previously allocated is freed as if a call
of the function free() was given. It will return a NULL pointer in that case.
Prof. A. Syed Mustafa (Ph.D)
42
•.
#include <stdlib.h>
#include <stdio.h> int main()
{ char *str;
str=(char *) malloc(4); /* Initial memory allocation */
strcpy(str, “data");
printf("String = %s, Address = %p\n", str, str);
/* Reallocating memory */
str = (char *) realloc(str, 13);
strcat(str, “structure");
printf("String = %s, Address = %p\n", str, str);
free(str);
return(0);
}
Basic Concepts
Dynamic Memory Allocation
Prof. A. Syed Mustafa (Ph.D)
43
Basic Concepts
Dynamic Memory Allocation
free()• Deallocate memory block
• A block of memory previously allocated by a call to malloc(), calloc() or realloc() is deallocated, making it available again for further allocations.
If ptr does not point to a block of memory allocated with the above functions, it causes undefined behavior.
If ptr is a null pointer, the function does nothing.
This function does not change the value of ptr itself, hence it still points to the same (now invalid) location.
Prof. A. Syed Mustafa (Ph.D)
44
Basic Concepts
Dynamic Memory Allocation
free()/* example */
#include <stdlib.h> /* malloc, calloc, realloc, free */
int main ()
{
int * i1, * i2, * i3;
i1 = (int*) malloc (100*sizeof(int));
i2 = (int*) calloc (100,sizeof(int));
i3 = (int*) realloc (i2,500*sizeof(int));
free (i1);
free (i3);
return 0;
}
Prof. A. Syed Mustafa (Ph.D)
45
Basic Concepts
Algorithm Specification
An algorithm is a finite set of instructions that, if followed, accomplishes a
particular task.
Algorithms must satisfy following criteria:
Input: there are zero or more quantities that are externally supplied.
Output: at least one quantity is produced.
Definiteness: Each instruction is clear and unambiguous.
Finiteness: for all cases, the algorithm terminates after a finite number of
steps.
Effectiveness: Every instruction must be basic enough to be carried out, it
must also be feasible. Prof. A. Syed Mustafa (Ph.D)
46
Basic Concepts
Algorithm Specification
• Difference between an algorithm and a program :
The program does not have to satisfy the fourth condition
(Finiteness).
• Describing an algorithm:
Natural language such as English can be used. Make sure
resulting instructions are definite.
• Flowchart:
work well only for algorithm, small and simple.
Prof. A. Syed Mustafa (Ph.D)
47
Basic Concepts
Algorithm Specification
• Difference between an algorithm and a program :
The program does not have to satisfy the fourth condition
(Finiteness).
• Describing an algorithm:
Natural language such as English can be used. Make sure
resulting instructions are definite.
• Flowchart:
work well only for algorithm, small and simple.
Prof. A. Syed Mustafa (Ph.D)
48
Basic Concepts
Algorithm Specification
Translating a Problem into an Algorithm
Example - Selection Sort
Devise a program that sorts a set of n integers,
where n>= 1, from smallest to largest.
Solution I:
From those integers that are currently unsorted,
find the smallest and place it next in the sorted list
. Prof. A. Syed Mustafa (Ph.D)
49
Basic Concepts
Algorithm Specification
Translating a Problem into an Algorithm
Describes sorting technique, but it is not an algorithm
Problems:1. Does not describe where and how the integers are initially
sorted.2. Does not indicate where to place the result..
Prof. A. Syed Mustafa (Ph.D)
50
Basic Concepts
Algorithm Specification
Translating a Problem into an Algorithm
Solution II: Selection Sort
An algorithm, written in partially C and English
for (i= 0; i< n; i++){
Examine list[i] to list[n-1] and suppose thatthe smallest integer is list[min];
Interchange list[i] and list[min];}
.
51
Basic Concepts
Algorithm Specification
Selection Sort
-find the smallest integer
-interchange or swap
-we can solve the problem using a function or macro
void swap(int *x, int *y) // both arguments are pointers
{
int temp= *x;
*x= *y;
*y= temp;
}Prof. A. Syed Mustafa (Ph.D)
52
Basic Concepts
Algorithm Specification
Selection Sort
#define swap(x,y,t)((t)= (x), (x)= (y), (y)= (t))
void sort(int list[ ], int n)
{
int i, j, min, temp;
for (i= 0; i< n-1; i++){
min= i;
for (j= i+1; j< n; j++){
if (list[j]< list[min]) min= j;
}
swap(list[i], list[min], temp);
}Prof. A. Syed Mustafa (Ph.D)
53
Basic Concepts
Algorithm Specification
Theorem 1.1:
sort(a, n) correctly sorts a set of n ≥ 1 integers; the
result remains in a[0] … a[n-1] such that
a[0] ≤ a[1] ≤ … ≤ a[n–1].
Prof. A. Syed Mustafa (Ph.D)
54
Basic Concepts
Algorithm Specification
Example: Binary Search
Assume that we have n ≥ 1 distinct integers that
are already sorted and stored in the array a[0] … a[n-1].
Our task is to determine if the integer x is present and
if so to return j such that x = a[j]; otherwise return -1.
Prof. A. Syed Mustafa (Ph.D)
55
Basic Concepts
Algorithm Specification
Example: Binary Search
1. Let left and right, respectively, denote the left and right ends of the list to be searched.
2. Initially, left = 0 and right = n – 1.
3. Let middle = (left + right) / 2 be the middle position in the list.
4. If we compare a[middle] with x, we obtain one of the three results.
Prof. A. Syed Mustafa (Ph.D)
56
Basic Concepts
Algorithm Specification
Example: Binary Search
1. x < a[middle] In this case, if x is present, it must be in the positions between 0 and middle – 1. Therefore, we set right to middle – 1.
2. x == a[middle]In this case, we return middle.
3. x > a[middle] In this case, if x is present, it must be in the positionsbetween middle+1 and n-1. So, we set left tomiddle+1.
Prof. A. Syed Mustafa (Ph.D)
57
Basic Concepts
Algorithm Specification
Binary Search.
Prof. A. Syed Mustafa (Ph.D)
58
Basic Concepts
Algorithm Specification
Binary Search.
int compare (int x, int y)
{
if (x < y) return -1;
else if ( x == y) return 0;
else return 1;
} // end of compare
Macro
#define compare (x, y) ( ( (x) < (y) ) ? -1: ( (x) == (y) ) ? 0 : 1 )
Prof. A. Syed Mustafa (Ph.D)
59
Basic Concepts
Algorithm Specification
Algorithms are implemented as functions in C.
Functions divide the programs into manageable
pieces.
They make program easier to read.
Functions can be tested separately.
Declare function first then define it later.
Prof. A. Syed Mustafa (Ph.D)
60
Basic Concepts
Algorithm Specification
Recursive algorithm
There are mainly two approaches for repetitive
approach.
1. Iteration
2. Recursion
Recursion is a repetitive process in which an
algorithm calls itself.
Prof. A. Syed Mustafa (Ph.D)
61
Basic Concepts
Algorithm Specification
Recursive algorithm
The following Figure 1 and Figure 2 portrayed the typical
pictorial examples for recursive calling.
Prof. A. Syed Mustafa (Ph.D)
62
Basic Concepts
Algorithm Specification
Recursive algorithm
The following Figure2 portrayed the typical pictorial
examples for recursive calling.
Prof. A. Syed Mustafa (Ph.D)
63
Basic Concepts
Algorithm Specification
Recursive algorithm
The following Figure portrayed the typical pictorial
examples for recursive calling.
Prof. A. Syed Mustafa (Ph.D)
64
Basic Concepts
Algorithm Specification
Recursive algorithm
Recursion is a programming technique in
which a method can call itself to solve a
problem.
Two Types:
1. Direct Recursion
2. Indirect recursion
Prof. A. Syed Mustafa (Ph.D)
65
Basic Concepts
Algorithm Specification
Recursive algorithm
1. Direct Recursion
Functions calls themselves
2. Indirect recursionFunctions calls other function that invoke the
calling function again.
Any function that we can write using assignment, if-
else and while statements can be written recursively.
Prof. A. Syed Mustafa (Ph.D)
66
Basic Concepts
Algorithm Specification
Value of Recursion
This is well suited an alternative concept in the following
situations
1. Recursion can be used to replace loop
2. A recursive procedure is mathematically more elegant than
one using loops
3. Sometime procedure that would tricky to write a loop are
straightforward to using recursion.
4. Recursively defined data structure, like list, are very well
suited to processing by recursive procedures and functionsProf. A. Syed Mustafa (Ph.D)
67
Basic Concepts
Algorithm Specification
Prof. A. Syed Mustafa (Ph.D)
68
Basic Concepts
Algorithm Specification
Prof. A. Syed Mustafa (Ph.D)
69
Basic Concepts
Algorithm Specification
Algorithm to compute factorial using recursive method:
Factorial (N)
1. Receive N
2. if N > 1 return
Factorial(N-1) * N
else
return 1
Prof. A. Syed Mustafa (Ph.D)
70
Basic Concepts
Algorithm Specification
program to compute factorial using recursive function:#include<stdio.h>
long factorial(int);
int main()
{ int n; long f;
printf("Enter an integer to find factorial\n");
scanf("%d", &n);
if (n < 0)printf("Negative integers are not allowed\n");
else { f = factorial(n);printf("%d! = %ld\n", n, f); }
return 0; }
long factorial(int n)
{ if (n == 0) return 1;
else return(n * factorial(n-1));
}Prof. A. Syed Mustafa (Ph.D)
71
Basic Concepts
Algorithm Specification
program to compute factorial using recursive function:
Prof. A. Syed Mustafa (Ph.D)
72
Basic Concepts
Algorithm Specification
program to compute factorial using recursive function:
Prof. A. Syed Mustafa (Ph.D)
73
Basic Concepts
Algorithm Specification
program to compute factorial using recursive function:
Prof. A. Syed Mustafa (Ph.D)
74
Basic Concepts
Algorithm Specification
program to compute factorial using recursive function:
Prof. A. Syed Mustafa (Ph.D)
75
Basic Concepts
Algorithm Specification
program to compute factorial using recursive function:
Prof. A. Syed Mustafa (Ph.D)
76
Basic Concepts
Algorithm Specification
Prof. A. Syed Mustafa (Ph.D)
77
Basic Concepts
Algorithm Specification
Prof. A. Syed Mustafa (Ph.D)
78
Basic Concepts
Algorithm Specification
Prof. A. Syed Mustafa (Ph.D)
79
Basic Concepts
Algorithm Specification
Recursive program: Fibonacci int main(){
int n=10;printf(“%d”, rfib(n));
}
int rfib(int n){
if (n==1 || n==2) return 1;return rfib(n1) + rfib(n2);
}
Prof. A. Syed Mustafa (Ph.D)
80
Basic Concepts
Algorithm Specification
Recursive program: Fibonacci
Prof. A. Syed Mustafa (Ph.D)
81
Basic Concepts
Algorithm Specification
Recursive program: Fibonacci
Prof. A. Syed Mustafa (Ph.D)
82
Basic Concepts
Algorithm Specification
Recursive program: Fibonacci
Prof. A. Syed Mustafa (Ph.D)
83
Basic Concepts
Algorithm Specification
Recursive algorithm: Greatest Common Divisor(x, y)
Prof. A. Syed Mustafa (Ph.D)
84
Basic Concepts
Algorithm Specification
/* PROGRAM TO FIND GCD OF TWO NUMBER USING RECURSION
EUCLIDS*/
#include<stdio.h>
#include<conio.h>
int gcd(int,int);
int main()
{ int a,b;
clrscr();
printf("\n Enter two number:" );
scanf("%d %d",&a,&b);
printf("GCD of two number : %d" ,gcd(a,b));
getch();
return(0);
}
Prof. A. Syed Mustafa (Ph.D)
85
Basic Concepts
Algorithm Specification
/* PROGRAM TO FIND GCD OF TWO NUMBER USING RECURSION
int gcd(int m, int n)
{
if(m==0)
return n;
if(n==0)
return m;
return gcd(n,m%n);
}
Prof. A. Syed Mustafa (Ph.D)
86
Basic Concepts
Algorithm Specification
/* PROGRAM TO FIND GCD OF TWO NUMBER USING RECURSION
int gcd(int a, int b)
{ if (a != b)
{if (a > b)
return gcd(a - b, b);
elsereturn gcd(a, b - a);
}return a;
}Prof. A. Syed Mustafa (Ph.D)
87
Basic Concepts
Algorithm Specification
Recursive algorithm: Greatest Common Divisor(x, y)
Prof. A. Syed Mustafa (Ph.D)
88
Basic Concepts
Algorithm Specification
Recursive algorithm
Prof. A. Syed Mustafa (Ph.D)
89
Basic Concepts
Algorithm Specification
Recursive algorithm
Prof. A. Syed Mustafa (Ph.D)
C(n, k) = C(n-1, k-1) + C(n-1, k) C(n, 0) = C(n, n) = 1
90
Basic Concepts
Algorithm Specification
Recursive algorithm-Binomial Coefficient
Prof. A. Syed Mustafa (Ph.D)
int binomialCoeff(int n, int k) // Returns value of Binomial Coefficient C(n, k)
{
if (k==0 || k==n) // Base Cases
return 1;
return binomialCoeff(n-1, k-1) + binomialCoeff(n-1, k); // Recur
}
int main() /* program to test above function*/
{
int n = 5, k = 2;
printf("Value of C(%d, %d) is %d ", n, k, binomialCoeff(n, k)); // C(5,2) is 10
return 0;
}
91
Basic Concepts
Algorithm Specification
Recursive algorithm -Binomial Coefficient
Prof. A. Syed Mustafa (Ph.D)
92
Basic Concepts
Algorithm Specification
Recursive algorithm: Towers of Hanoi
Prof. A. Syed Mustafa (Ph.D)
93
Basic Concepts
Algorithm Specification
Recursive algorithm: Towers of Hanoi
Prof. A. Syed Mustafa (Ph.D)
•Label the stands Src, Intr, Dest.
•Let n be the total number of discs.
•Number the discs from 1 (smallest, topmost) to n (largest, bottommost).
To move n discs from stand Src to stand Dest:
1.Move n-1 plates from Src to Intr. This leaves plate #n alone on plate Src.
2.Move plate #n from Src to Dest.
3.Move n-1 plates from Intr to Dest so they sit on plate #n.
94
Basic Concepts
Algorithm Specification
Recursive algorithm: Towers of Hanoi
Prof. A. Syed Mustafa (Ph.D)
95
Basic Concepts
Algorithm Specification
Recursive algorithm: Towers of Hanoi
Prof. A. Syed Mustafa (Ph.D)
FUNCTION MoveTower(disk, source, dest, inter)IF disk == 1, THEN:
move disk from source to destELSE:
MoveTower(disk - 1, source, inter, dest) // Step 1 abovemove disk from source to dest // Step 2 above
MoveTower(disk - 1, inter, dest, source) // Step 3 above
END IF
96
Basic Concepts
Algorithm Specification
Recursive algorithm: Towers of Hanoi
Prof. A. Syed Mustafa (Ph.D)
97
Basic Concepts
Algorithm Specification
Recursive algorithm: Towers of Hanoi
Prof. A. Syed Mustafa (Ph.D)
98
Basic Concepts
Algorithm Specification
Recursive algorithm: Towers of Hanoi
Prof. A. Syed Mustafa (Ph.D)
99
Basic Concepts
Algorithm Specification
Limitations of Recursion
Recursion should not be used if the answer to any of the
following questions is no:
Is the algorithm or data structure naturally suited to recursion (tree
is the first choice) ?
Is the recursive solution shorter and more understandable?
Does the recursive solution run within acceptable time and space
limits ?
As a general rule, recursive algorithms should be effectively used
only when their efficiency is logarithmic.
Prof. A. Syed Mustafa (Ph.D)
100
Basic Concepts
Data Abstraction
Abstraction is the process by which data and
programs are defined with a representation similar to
its meaning (semantics), while hiding away the
implementation details.
Prof. A. Syed Mustafa (Ph.D)
101
Basic Concepts
Data Abstraction
Abstraction tries to reduce and factor out details so that
the programmer can focus on a few concepts at a time. A
system can have several abstraction layers whereby
different meanings and amounts of detail are exposed to
the programmer.
For example, low-level abstraction layers expose details
of the hardware where the program is run, while high-
level layers deal with the business logic of the program.Prof. A. Syed Mustafa (Ph.D)
102
Basic Concepts
Data Abstraction
Prof. A. Syed Mustafa (Ph.D)
103
Basic Concepts
Data Abstraction
Prof. A. Syed Mustafa (Ph.D)
104
Basic Concepts
Data Abstraction
Prof. A. Syed Mustafa (Ph.D)
105
Basic Concepts
Data Abstraction
Prof. A. Syed Mustafa (Ph.D)
106
Basic Concepts
Data Abstraction
Prof. A. Syed Mustafa (Ph.D)
107
Basic Concepts
Data Abstraction
Prof. A. Syed Mustafa (Ph.D)
108
Basic Concepts
Data Abstraction
Prof. A. Syed Mustafa (Ph.D)
109
Basic Concepts
Data Abstraction
Prof. A. Syed Mustafa (Ph.D)
110
Basic Concepts
Data Abstraction
Prof. A. Syed Mustafa (Ph.D)
111
Basic Concepts
Data Abstraction
Prof. A. Syed Mustafa (Ph.D)
112
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
113
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
Space & Time
Does the program efficiently use primary and
secondary storage ?
Is the program’s running time acceptable for the
task ?
114
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
115
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
The space complexity of a program is the
amount of memory that it needs to run to
completion.
The time complexity of a program is the amount
of computer time that it needs to run to
completion
116
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
117
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
118
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
119
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
120
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
121
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
122
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
123
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
124
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
125
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
126
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
TP(n) = Ca ADD(n)+ CsSUB(n)+CLLDA(n)+CstSTA(n)
n –Instance Characteristic
Ca , Cs , CL , Cst – constants-time needed to perorm
each operation
ADD - No of additionsSUB - No of SubtractionLDA – No of LoadsSTA – No of Stores
Performed when the program is run with instance characteristic n.
127
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
128
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
129
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
130
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
131
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
132
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
General statements in a C programStep count
1. Comments 02. Declarative statements 03. Expressions and assignment statements 14. Iteration statements N5. Switch statement N6. If-else statement N7. Function invocation 1 or N8. Memory management statements 1 or N9. Function statements 010.Jump statements 1 or N
133
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
Note that a step count does not necessarily
reflect the complexity of the statement.
Step per execution (s/e):
The s/e of a statement is the amount by which
count changes as a result of the execution of
that statement.
134
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
135
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
136
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
137
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
138
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
139
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
140
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
141
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
142
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
143
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
144
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
145
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
146
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
147
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
148
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
149
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
150
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
151
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
152
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
153
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
154
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
155
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
156
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
157
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
158
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
159
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
160
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
161
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
162
Basic Concepts
Performance Analysis
Prof. A. Syed Mustafa (Ph.D)
Prof. A. Syed Mustafa (Ph.D) 163