Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

CMP215 Data Structures Through C++

Download as pdf or txt
Download as pdf or txt
You are on page 1of 184

Introduction To Data Structures

Yashavant Kanetkar
kanetkar@ksetindia.com

Objectives

~ What is the meaning of Data Structure


~ Why are they important
~ What different types exist
~ How do you select the correct one
~ Does the selection matter

What Are Data Structures

~ Proper organization leads to efficient access


~ Examples:
• Notes in a wallet
• Certificates in a file
• Chapters in a book
• Words in a dictionary

~ Same is true about storing data in computer


~ If stored properly, it can be used efficiently
~ So , DS = Storage with motive of efficient use

1
Should I Really Care

~ I keep getting some or the other Bug in the S/W


~ Slow working of a particular site
~ Asking same data to be entered repeatedly
~ Google search versus others
~ It takes an eternity to sort data
~ Moral...
Good programming begins with right
choice of DS

Properties Of A Good Data Structure

~ Permits a variety of critical opns to be performed


~ Uses less execution time
~ Uses less memory space

5 -1 34 12 53

Common DS Data Link

55 63 60 N
~ Arrays Node Node Node
~ Sparse Matrices
Top 25
~ Linked Lists f r
20
~ Stacks
10 61 9 23 - 8 42
~ Queues
A
~ Trees
1
~ Graphs B C

D E 2 3

F G H 4

2
Which One To Use

~ Time complexity
~ Space complexity
~ At times, ease of use
~ At times, operations that we wish to perform
~ At times, programming language used
~ Some are suited better for some applications
• Ex. B-Trees for Databases
• Ex. Stacks for function calls

Impact Of Good Data Structures

~ Ease of implementation
~ Quality of implementation
~ Quality of performance

Choices Available

~ Implement Data Structures yourselves


~ Use standard libraries:
• C++'s Standard Template Library
• Java's Collections Framework
• Microsoft's .NET Framework

3
Searching
Asang Dani

Objectives
· Operations performed on an array
· What are algorithms
· Important features of algorithms
· Conventions to follow while writing an algorithm
· Linear search and Binary search

Algorithm
· Method of accomplishing a task in a finite number of steps
· Origin - Persian Mathematician - Abu Jaffer Al-Khowarizmi
· Aka - Recipe, Method, Technique, Procedure, Routine
· Important Features:
· Input - Must have zero or more inputs
· Output - Must have one or more outputs
· Finiteness - Must terminate after finite no. of steps
· Definiteness - Each step must be unambiguously defined
· Effectiveness - All operations must be sufficiently basic
· Types:
· Iterative - Repetition using loop
· Recursive - Divide and Conquer

1
Array Operations
Operations Description
Traversal Processing each element in the array
Search Finding the location of an element with
a given value
Insertion Adding a new element to an array
Deletion Removing an element from an array
Sorting Organizing the elements in some order
Merging Combing two arrays into a single array

Linear Search
main( )
{
int a[ ] = { 11, 2, 9, 13, 57, 25, 17, 1, 90, 3 } ;
int i, num ;
printf ( "Enter no. to search: " ) ;
scanf ( "%d", &num ) ;
for ( i = 0 ; i <= 9 ; i++ )
{
if ( a[ i ] == num )
break ;
}
if ( i == 10 )
printf ( "No such number in array" ) ;
else
printf ( "Number is at position %d", i ) ;
}

Binary Search l m u
main( ) 1 2 3 9 11 13 17 25 57 90
{
int a[ ] = { 1, 2, 3, 9, 11, 13, 17, 25, 57, 90 } ;
int l = 0, u = 9, m, num ;
printf ( "Enter number to search: " ) ;
scanf ( "%d", &num ) ;
57
while ( l <= u )
{
m=(l+u)/2;
if ( a[m] == num )
{
printf ( "No. is at position %d ", m ) ; exit( ) ;
}
a[m] > num ? ( u = m - 1 ) : ( l = m + 1 ) ;
}
printf ( "Element is not present in the array." ) ;
}

2
Searching &
Frequency Count
Asang Dani
asang@ksetindia.com

Objectives

· Analyzing an algorithm
· Rate of increase for growth rate with respect to
Big Oh notation

Analysis Of Algorithms
Determining

Time Requirement Space Requirement

Difficulty Cheaper - Not so relevant


X Machine dependent
X Language dependent
X Compiler dependent
X Iterative - WD in loop
X Recursive - WD in break & make
Solution
X Don’t calculate exact time
X Calculate approx. no. of operns. for given input
X No. of opns α Time

1
Example - Biggest of 4
3 comparisons
Algorithm 1 Algorithm 2
if ( a > b ) else big = a
if ( a > c ) if ( b > c ) if ( b > big )
if ( a > d ) if ( b > d ) big = b
return a return b end if
else else if ( c > big )
return d return d big = c
end if end if
else end if
else if ( d > big )
if ( c > d )
if ( c > d ) return c big = d
return c else end if
else return d return big
return d end if
end if end if
end if end if

What To Count
· Multiplication of Matrices - Number of multiplications
· Searching - Number of comparisons
· Sorting - Number of comparisons
· Count chars in a file

for ( i = 0 ; i <= 255 ; i + + )


a[ i ] = 0 ;
while ( ( ch = getc ( fp ) ) != EOF )
a[ ch ] + + ;
N Opns. in Loop1 Opns. in Loop2  Total
500256 + 256 + 256 500 + 500 + 500 2268
( 33%) ( 66%)
50000 256 + 256 + 256 50000 + 50000 + 50000 150768
( 1%) ( 99%)

Fibonacci Series
1 fibonacci ( ) Line no. No. of execution
2 {
3 old = 1 ; 3 1
4 1
4 new = 1 ;
5 1
5 n = 20 ;
6 n-1
6 for ( i = 1 ; i < n ; i + + ) 8 n-1
7 { 9 n-1
8 a = old + new ; 10 n-1
9 printf ( "%d ", a ) ; 11 n-1
10 old = new ;
11 new = a ; Total 5n - 2
12 }
13 }
Ignoring the const 5 & 2
complexity -> O( n )

2
Exercise
Determine the frequency counts for all statements in the
following two program segments:
1 for ( i = 0 ; i < n ; i + + )
2 { Line no. No. of exec.
3 for ( j = 0 ; j < i ; j + + ) 1 n
4 { 3 n*i
5 for ( k = 0 ; k < j ; k + + ) 5 n*i*j
6 {
7 x++; 7 n*i*j
8 } n(1+i+2ij)
9 } O(n)
10 }
1 i=0 Line no. No. of exec.
2 while ( i < n ) 1 1
3 {
2 n
4 x=x+1;
5 i= i+1; 4 n
6 } O(n) 5 n

Rate of Increase
n log n n log n n2 n3 2n
1 0.0 0.0 1.0 1.0 2.0
2 1.0 2.0 4.0 8.0 4.0
5 2.3 11.6 25.0 125.0 32.0
10 3.3 33.2 100.0 1000.0 1024.0
15 3.9 58.6 225.0 3375.0 32768.0
20 4.3 86.4 400.0 8000.0 1048576.0
30 4.9 147.2 900.0 27000.0 1073741824.0
40 5.3 212.9 1600.0 64000.0 1099511627776.0
50 5.6 282.2 2500.0 125000.0 1125899906842620.0
O( 1 ) - const., O( n ) - linear, O( n2 ) - quadratic, O( n3 ) - cubic
O( 2n ) - exponential
O( log n ) is faster than O( n )
O( n log n ) is faster than O( n2 ) but not as good as O( n )

Exercise
For which range of values would the algorithm whose order
of magnitude is n3 be better than an algorithm whose order
of magnitude is 2n
Range Better
n n3 2n
n=1 n3
1 1.0 2.0 n = 2 to 9 2n
2 8.0 4.0 n > 10 n3
5 125.0 32.0
6 216.0 64.0
7 343.0 128.0
8 512.0 256.0
9 729.0 512.0
10 1000.0 1024.0
15 3375.0 32768.0
20 8000.0 1048576.0
30 27000.0 1073741824.0
40 64000.0 1099511627776.0
50 125000.0 1125899906842620.0

3
Analysis Of
Searching Methods
Asang Dani

Objectives
· Tools to calculate time complexity
· Cases to be considered while analyzing
algorithms
· Analysis of Linear search and Binary search

Classification Of Growth
· Rate of growth is dominated by largest term in an equation
· Neglect terms that grow more slowly
· Leftover is known as order of the algorithm
· Algos. are grouped into 3 categories based on their order
· Big Omega - Ω ( f ) 
If g( x ) є Ω( f ), g( n ) >= cf( n ) for all n >= n0 (c = const.)
Represents class of funcns that grow at least as fast as f
· Big Oh - O( f ) 
If g( x ) є O( f ), g( n ) <= cf( n ) for all n >= n0 (c = const.)
Represents class of funcns that grow no faster than f
· Big Theta - θ( f )
θ( f ) = Ω( f ) ∩ O( f ) 
Represents class of funcns that grow as fast as f

1
Analysis Of Linear Search
linearsearch ( int *list, int value, int n )
{
Best Worst Avg.
for ( i = 0 ; i < n ; i + + )
{ 1 N N+2
if ( value == list [ i ] ) 2
return i ;
}
· Possible inputs
return -1 ;
· Probability of each input
}
The value being searched
is found in first location
· The value being searched matches the last elements
in the list
· The value being searched is not present in the list

Average Case
N
A( N ) =
Probability
1
N+1 * ∑i
i=1
+N

N
A( N ) =
1
N+1 ∑
i=1
i + N+1
1
*N
1 N(N+1) N
A( N ) =
N+1 * 2
+N+1
N N
+1_
N 1
A( N ) = +N+1 =
2 2 N+1
N+2
A( N ) ≈
2
1
(As n gets very large, becomes almost 0)
N+1

Analysis Of Binary Search


bisearch ( int *a, int x ) Halving nature of algo.
{
lower = 0 ; upper = 10 ; N = 2k - 1
while ( lower <= upper )
{ 2k - 1 - 1, 1, 2k - 1 - 1
mid = ( lower + upper ) / 2 ; K = 3, 23 - 1 = 7, N = 7
switch ( compare ( x, a[ mid ] ) ) 23 - 1 - 1, 1, 23 - 1 - 1
{ 3, 1, 3
case '>' : K = 2, 22 - 1 = 3, N = 3
lower = mid + 1 ; break ; 22 - 1 - 1, 1, 22 - 1 - 1
case '<' : 1, 1, 1
upper = mid - 1 ; break ; N = 2k - 1
case '=’ :
log2 2k = log2 ( N + 1 )
printf ( "%d ", mid ) ; exit( ) ;
k log2 2 = log2 ( N + 1 )
} Best Worst k = log2 ( N + 1 )
}
1 log ( N + 1 )
}

2
Hashing
Asang Dani

Objectives

· Hashing Techniques
x Division method
x Mid – Square method
x Folding method
x Digit Analysis method
x Linear and quadratic probing

Hashing Functions

· Division 
· Mid - Square
· Folding
· Digit Analysis

1
Division
3229329 4231176 7621913 9812427 2178115 4031231

Store elements as per hash value 0


Hash value - index based 1 4031231
Hash value = no. % 10
2
If hash value clashes - collision
- chaining (not efficient) 3 7621913
- rehashing 4
1431327 5 2178115
6 4231176
7 9812427
8 1431327
9 3229329
Linear Probing

Mid - Square
· Identifiers - A = 1, ..., Z = 26, 0 = 27, 1 = 28, ..., 9 = 36
· Find octal equivalent of each character
· Square the octal equivalent
· Use middle bits of square as hash value
· Table size = 2r, r is no. of middle bits
X X1 (X1) 2
A 01 1
B 02 4
... ... ...
Y 31 1701
Z 32 2000
0 33 2101
1 34 2204
A1 134 20420
A2 135 20711
CAT 030124 125620

Folding
· Distribute digits in multiple partitions
· Excluding last make all partitions equal
· Add partition values to get hash value

No. Of
Partition
Digits
1 1
2 2
3 1, 2 CAT 030124
4 1, 1, 2
5 2, 2, 1 0 3 0 1 24 28
6 1, 1, 1, 1, 2
7 3, 3, 1
8 3, 3, 2
9 2, 2, 2, 2, 1
... ...

2
Digit Analysis
· Each identifier is interpreted as a no. using some radix r
· Same radix is used for other identifiers
· Digits in each identifier is examined
· Digits with skewed distribution are deleted
· Digits are deleted till balance digits are in range of HT

More Hashing
· Hash table contains buckets
· Each buckets may contain several slots
· Each slot can hold one record
· Collision - when two identifiers hash into same bucket
· Overflow - when new identifier is hashed into a full bucket
· If number of slots = 1 then Collision = Overflow
· Collision handling techniques:
· Linear probing -
search the bucket ( f ( x ) + i ) % b, for 0 <= i <= b - 1
· Quadratic probing -
search the bucket f ( x )
( f ( x ) + i2 ) % b
( f ( x ) - i2 ) % b, for 1 <= i <= ( b - 1) / 2

Linear Probing
4028 2133 1098 7915 6749 5141 3138 f ( x ) = no. % 10
key = ( f( x ) + i ) % b
f ( int no, int *arr, int b )
{ 0 6749
int i, j, initialpos ; 1 5141
j = no % 10 ; intialpos = j ; 2 3138
for ( i = 1 ; arr[ j ] != no && arr[ j ] != 0 ; i + + ) 3 2133
{ 4
j = ( no % 10 + i ) % b ;
if ( j == initialpos ) 5 7915
{ 6
printf ( "Array full" ) ; return ; 7
} 8 4028
} 9 1098
arr [ j ] = no ;
}

3
Quadratic Probing
4028 2133 1098 7915 6749 5141 3138

f ( x ) = no. % 10 0
key = f( x ) 1 5141
= f( x ) + i2 ) % b 2 3138
= f( x ) - i2 ) % b 3 2133
for 1 <= i <= ( b -1 ) / 2 4
5 7915
6
7 6748
8 4028
9 1098

4
Sorting
Asang Dani

Objectives

· Selection Sort and its Analysis


· Bubble Sort and its Analysis
· Radix Sort

main( )
Selection Sort
{ 17 6 13 12 2 i j
int a[ ] = { 17, 6, 13,12, 2 } ; 6 17 13 12 2 0-1
int i, j, t ; 6 17 13 12 2 0-2
for ( i = 0 ; i <= 3 ; i + + ) 6 17 13 12 2 0-3
{ 2 17 13 12 6 0-4
for ( j = i + 1 ; j <= 4 ; j + + ) 2 13 17 12 6 1-2
{ 2 12 17 13 6 1-3
if ( a[ i ] >a[ j ] )
2 6 17 13 12 1-4
{
t = a[ i ] ; a[ i ] = a[ j ] ; 2 6 13 17 12 2-3
a[ j ] = t ; 2 6 12 17 13 2-4
}
}
2 6 12 13 17 3 - 4
}
for ( i = 0 ; i <= 4 ; i + + )
printf ( "%d", a[ i ] ) ;
}

1
Analysis Of Selection Sort
selectionsort ( int *a, int n )
{
17, 6, 13, 12, 2
for ( i = 0 ; i < n - 1 ; i + + )
{ i No. of comp.
for ( j = i + 1 ; j < n ; j + + )
{ 0 4
if ( a[ i ] > a[ j ] ) 1 3
{ 2 2
t = a[ i ] ; 3 1
a[ i ] = a[ j ] ;
N-1
∑i
a[ j ] = t ; N(N-1)
} =
} 2
i=1
}
} = O ( N2 )

Bubble Sort
main( )
{ 17 6 13 12 2 i i+1
int a[ ] = { 17, 6, 13, 12, 2 } ; 6 17 13 12 2 0-1
int i, j, t ; 6 13 17 12 2 1-2
for ( j = 0 ; j <= 3 ; j + + ) 6 13 12 17 2 2-3
{ 6 13 12 2 17 3-4
for ( i = 0 ; i <= 3 - j ; i + + )
{ 6 13 12 2 17 0 - 1
if ( a[ i ] > a[ i + 1 ] ) 6 12 13 2 17 1 - 2
{ 6 12 2 13 17 2 - 3
t = a[ i ] ; a[ i ] = a[ i + 1 ] ; 6 12 2 13 17 0 - 1
a[ i + 1 ] = t ; 6 2 12 13 17 1 - 2
}
}
} 2 6 12 13 17 0 - 1
for ( i = 0 ; i <= 4 ; i + + )
printf ( "%d", a[ i ] ) ;
}

Analysis Of Bubble Sort


bubblesort ( int *a, int n )
{
17, 6, 13, 12, 2
for ( j = 0 ; j < n - 1 ; j + + )
{ j No. of comp.
for ( i = 0 ; i < ( n - 1 ) - j ; i + + )
{ 0 4
if ( a[ i ] > a[ i + 1 ] ) 1 3
{ 2 2
t = a[ i ] ; 3 1
a[ i ] = a[ i + 1 ] ;
a[ i + 1 ] = t ; N-1

}
} ∑ i=1
i =
N(N-1)
2
}
} = O ( N2 )

2
Radix Sort
9 47 21 32 5 13 27 4 54 76 29 85 98 62 30
Q0 30 Add elements in Q0 4 5 9
respective Q.
Q1 21 Q1 13
initially, w.r.t units
Q2 32 62 place then w.r.t tens Q2 21 27 29
place and so on....
Q3 13 Q3 30 32
30 21 32 62 13
Q4 4 54 4 54 5 85 76 Q4 47
Q5 5 85 47 27 98 9 29 Q5 54
Q6 76 Q6 62
Q7 47 27 Q7 76
Q8 98 Q8 85
Q9 9 29 Q9 98
4 5 9 13 21 27 29 30 32 47 54 62 76 85 98

Program
main( ) initq ( int arr[ 10 ][ 3 ] )
{ {
int a[ ] = { 9, 47, 21, 32, 5, int i, j ;
13, 27, 4, 54, 76 } ; for ( i = 0 ; i < 10 ; i + + )
int arr[ 10 ][ 3 ], k, dig ; {
dig = 1 ; for ( j = 0 ; j < 3 ; j + + )
for ( k = 0 ; k <= 1 ; k + + ) arr[ i ][ j ] = 0 ;
{ }
initq ( arr ) ; }
radix ( a, arr, 10, dig ) ;
combine ( a, arr ) ;
dig *= 10 ;
}
for ( i = 0 ; i < 10 ; i + + )
printf ( "%d", a [ i ] ) ;
}
Contd...

...Contd.
radix ( int a[ ], int arr[ ][ 3], combine ( int *a, int arr[ ][ 3 ] )
int n, int dig ) {
{ int i, j, x = 0 ;
int i, j, key ; for ( i = 0 ; i < 10 ; i + + )
for ( i = 0 ; i < n ; i + + ) {
for ( j = 0 ; j < 3 ; j + + )
{
{
key = ( a [ i ] / dig ) % 10 ;
if ( arr[ i ][ j ] ! = 0 )
for ( j = 0 ; j < 3 ; j + + )
{
{ a[ x ] = arr[ i ][ j ] ;
if ( arr[ key ][ j ] == 0 ) x++;
{ }
arr[ key ][ j ] = arr[ i ] ; }
break ; }
} }
}
}
}

3
Sorting & Recursion
Asang Dani

Objectives

· Insertion Sort
· Recursive Functions

main( ) Insertion Sort


{
int a[ ] = { 10, 12, 18, 19, 24, 2 } ; for ( i = 0 ; i <= 5 ; i ++ )
int i, j, k, t ; printf ( "%d\t", a[ i ] ) ;
for ( i = 1 ; i <= 5 ; i ++ ) }
{
t = a[ i ] ; a[0] a[1] a[2] a[3] a[4] a[5]
for ( j = 0 ; j < i ; j++ )
{ 10 12 18 19 24 2
if ( t < a[ j ] ) t
{ 2
for ( k = i ; k >= j ; k-- ) a[0] a[1] a[2] a[3] a[4] a[5]
a[ k ] = a[k - 1] ;
a[ j ] = t ; 10
10 12 12 18 18 19 24
break ;
} a[0] a[1] a[2] a[3] a[4] a[5]
} 2 10 12 18 19 24
}

1
Simple Form
main( )
{
printf ( ”Hi” ) ;
Loop
main( ) ; infinite
}

One More Form


main( )
{
f( ) ;
}
Loop
f( )
{
infinite
printf ( ”Hi” ) ;
f( ) ;
}

main( )
More General
31698
{
int num, sum ;
d5
printf ( ”Enter a number” ) ;
scanf ( ”%d”, &num ) ; 327 485
sum = sumdig ( num ) ; d3
printf ( ”%d”, sum ) ;
}
sumdig ( int n ) 12 n s d
{ 327 0 7
int d ; int s = 0 ; 32 7 2
while ( n != 0 ) 3 9 3
{ 0 12
d = n % 10 ;
n = n / 10 ; s = s + d ;
}
return ( s ) ;
}

main( )
{
int num, sum ;
printf ( ”Enter a number” ) ;
scanf ( ”%d”, &num ) ; 327
sum = rsum ( num ) ;
printf ( ”%d”, sum ) ;
}
rsum ( int n )
{ 4!
int d ; int s ;
if ( n != 0 ) 4*3*2*1
{ 4*3!
d = n % 10 ; n = n / 10 ;
s = d + rsum ( n ) ; 3*2!
}
else 2*1!
return ( 0 ) ;
return ( s ) ;
}

2
rsum ( int n ) rsum ( int n )
{ 327 {
if ( n != 0 ) if ( n != 0 )
{ {
d = 327 % 10 ; d = 3 % 10 ;
n = 327 / 10 ; n = 3 / 10 ;
s = 7 + rsum ( 32 ) ; s = 3 + rsum ( 0 ) ;
} }
else else
return ( 0 ) ; return ( 0 ) ;
return ( s ) ; return ( s ) ;
} }
rsum ( int n ) rsum ( int n )
{ {
if ( n != 0 ) if ( n != 0 )
{ {
d = 32 % 10 ; d=
n = 32 / 10 ; n=
s = 2 + rsum ( 3 ) ; s=
} }
else else
return ( 0 ) ; return ( 0 ) ;
return ( s ) ; return ( s ) ;
} }

Recursive Factorial
main( ) Recursion Tips
{
int num, fact ;
· Make recursive call in an if
printf ( ”Enter no.” ) ;
scanf ( ”%d”, &num ) ; · else block is escape route
fact = refact ( num ) ; · else contains end cond. logic
printf ( ”%d”, fact ) ;
· return may not be present
}
refact ( int n )
{
int p ;
if ( n != 0 )
p = n * refact ( n - 1 ) ;
else
return ( 1 ) ;
return ( p ) ;
}

3
QuickSort
Asang Dani

Objectives

· Splitting mechanism in quick sort


· QuickSort algorithm
· QuickSort program

11 2 9 13 57 25 17 1 90 3 Split Array
11 2 9 13 57 25 17 1 90 3

11 2 9 13 57 25 17 1 90 3

11 2 9 13 57 25 17 1 90 3

11 2 9 3 57 25 17 1 90 13

11 2 9 3 57 25 17 1 90 13

11 2 9 3 1 25 17 57 90 13

11 2 9 3 1 25 17 57 90 13

1 2 9 3 11 25 17 57 90 13

1
void quicksort ( int *, int, int ) ;
int split ( int *, int, int ) ;
Quick Sort
main( )
{
int arr[ 10 ] = { 11, 2, 9, 13, 57, 25, 17, 1, 90, 3 } ;
int i ;
quicksort ( arr, 0, 9 ) ;
for ( i = 0 ; i <= 9 ; i++ )
printf ( "%d\t", arr[ i ] ) ;
}
void quicksort ( int *a, int lower, int upper )
{
int i ;
if ( upper > lower )
{
i = split ( a, lower, upper ) ;
quicksort ( a, lower, i - 1 ) ;
quicksort ( a, i + 1, upper ) ;
}
} Cont…

Cont… 11 2 9 13 57 25 17 1 90 3 p - L to R
q - R to L
int split ( int a[ ], int lower, int upper ) if ( p < q )
{ {
int i, p, q, t ; t = a[ p ] ;
p = lower + 1 ; a[ p ] = a[ q ] ;
q = upper ; a[ q ] = t ;
i = a[ lower ] ; }
}
while ( p <= q ) t = a[ lower ] ;
{ a[ lower ] = a[ q ] ;
while ( a[ p ] < i ) a[ q ] = t ;
p++ ; return q ;
while ( a[ q ] > i ) }
q-- ;
11 2 9 3 1 25 17 57 90 13

1 2 9 3 11 25 17 57 90 13

Problem
Show the steps for sorting the following numbers using
Quick Sort Algorithm

[ 42, 23, 74, 11, 65, 58, 94, 36, 99, 87 ]

2
Write the steps for quick
Exercise sort of following elements:
[ 43, 23, 74, 11, 65, 58, 94, 36, 99, 87 ]
p q
43 23 74 11 65 58 94 36 99 87
p q
43 23 74 11 65 58 94 36 99 87
p q
43 23 74 11 65 58 94 36 99 87
p q
43 23 36 11 65 58 94 74 99 87
p q
43 23 36 11 65 58 94 74 99 87
pq
43 23 36 11 65 58 94 74 99 87
q p
43 23 36 11 65 58 94 74 99 87
Contd...

Contd… q p
43 23 36 11 65 58 94 74 99 87

11 23 36 43 65 58 94 74 99 87
p q p q
11 23 36 43 65 58 94 74 99 87
pq p q
11 23 36 43 65 58 94 74 99 87
q p p q
11 23 36 43 65 58 94 74 99 87
pq
11 23 36 43 65 58 94 74 99 87
q p
65 58 94 74 99 87

58 65 94 74 99 87

Complexity
Algorithm Worst Case Best Case
Bubble sort O (n2) O (n2)
Selection Sort O (n2) O (n2)
Quick Sort O (n2) log2 n
Insertion sort O (n2) n–1
Binary Tree Sort O (n2) O (n log n)
Heap Sort O (n log n) O (n log n)
Merge Sort O (n log n) O (n log n)

3
Structures
Asang Dani

Objectives

· Defining and using structures


· Creating an array of structures
· How to copy one structure variable into another
· Using nested structures
· Passing structure elements
· Passing structures

Handling Data
main( )
{
char n[ ] = { ’A’, ’X’, ’Y’, ’\0’ } ;
int a[ ] = { 23, 27, 28 } ;
float s[ ] = { 4000.50, 5000.00, 6000.75 } ;
int i ;
for ( i = 0 ; i <= 2 ; i ++ )
printf ( "%c %d %f", n[ i ], a[ i ], s[ i ] ) ;
}

1
main( ) Structures
{
struct employee
{
.
structure
char n ; £ operators
int a ;
float s ;
};
struct employee e 1 = { ’A’, 23, 4000.50 } ;
struct employee e2 = { ’X’, 27, 5000.00 } ;
struct employee e3 = { ’Y’, 28, 6000.75 } ;
printf ( "%c %d %f", e1.n, e1. a, e1. s ) ;
printf ( "%c %d %f", e2.n, e2.a, e2.s ) ;
printf ( "%c %d %f", e3.n, e3.a, e3.s ) ;
}

main( ) Array of Structures


{
struct employee
{
char n ;
int a ;
float s ;
};
struct employee e[ ] = {
{ ’A’, 23, 4000.50 } ,
{ ’X’, 27, 5000.00 } ,
{ ’Y’, 28, 6000.75 }
};
int i ;
for ( i = 0 ; i <= 2 ; i++ )
printf ( "%c %d %f", e[ i ] .n, e[ i ].a, e[ i ].s ) ;
}

Terminology
Structure
Keyword struct employee name/tag
{
char n ; Structure
int a ; elements/
members
float s ;
};
struct employee e1, e2, e[ 10 ] ;

Structure
variables Array of
structures

2
Conclusion
A structure is usually a collection of
dissimilar elements.
Structure elements are always stored in
adjacent memory locations.

struct employee e[ 3 ] = { .. } ;
A 23 400.50 X 27 500.00 Y 28 600.75
401 408 415

Array of Structures
A 23 400.50 X 27 500.00 Y 28 600.75
401 408 415
struct employee e[ ] = { ... } ;
Ptr. to structure
char *p ;
struct employee *q ;
struct employee (*r )[ 3 ] ; Ptr. to array of structures

p=e ; q=e ; r=e ; 402 struct employee *z[3] ;


p++ ; q++ ; r++ ;
printf ( "%u", p ) ; 408
printf ( "%u", q ) ; Array of Ptrs to structures
printf ( "%u", r ) ; 422

Copying Rahul
e1
23 400.50

main( ) e2
{ Rahul 23 400.50
struct emp
{ e3
char n[20] ;
int a ; Rahul 23 400.50
float s ;
};
struct emp e1 = { "Rahul", 23, 4000.50 } ;
piecemeal
copying struct emp e2, e3 ;
e2.n = e1.n ; strcpy ( e2.n, e1.n ) ;
e2.a = e1.a ;
e2.s = e1.s ; copying at
one shot
e3 = e1 ;
printf ( "%s %d %f", e3.n, e3.a, e3.s ) ;
}

3
Nested Structures
main( )
{ e
struct address
{ a
char city[20] ;
long int pin ; Rahul 23 Ngp 44010 400.50
};
struct emp
{
char n[20] ; int age ;
struct address a ; float s ;
};
struct emp e={ "Rahul", 23, "Ngp", 44010, 4000.50 } ;
printf ( "%s %d %s %ld %f", e.n, e.age, e.city, e.pin,
e.s ) ;
} e.a.city a.city
e.a.pin
printf ( ”%d”, a.b.c.d.e.f ) ; f - int

Passing Structure Elements


main( ) b
{ Basic 425 135.00
struct book 501 521 523
{
char n[20] ; int nop ; float pr ;
};
struct book b = { "Basic", 425, 135.00 } ;
display (b.n, b.nop, b.pr ) ;
show ( b.n, &b.nop, &b.pr ) ;
}
display ( char *n, int pg, float p )
{
printf ( "%s %d %f", n, pg, p ) ;
}
show ( char *n, int *pg, float *p )
{
printf ( "%s %d %f", n, *pg, *p ) ;
}

Passing Structures b
Basic 425 135.00
main( )
{ 501 521 523
struct book
{
char n[20] ; int nop ; float pr ;
};
struct book b = { "Basic", 425, 135.00 } ;
display1 ( b ) ; show1 ( &b ) ;
}
display1 ( struct book bb )
{
printf ("%s %d %f", bb.n, bb.nop, bb.pr ) ;
}
show1 ( struct book *bb )
{
printf ( "%s %d %f", ( *bb ) .n, ( * bb ) .nop,( * bb ) .pr );
printf ( "%s %d %f", bb -> n, bb -> nop, bb -> pr ) ;
}

4
Structures &
Polynomials
Asang Dani

Objectives
· Representing polynomials using structures
· Passing array of structures
· How to perform operations like addition and
multiplication on polynomials using structures

Problem
· There are two arrays A & B. A contains 25 elements
whereas B contains 30 elements. Write a procedure to
create an array C which contains only those elements
which are common to A & B.

1
Polynomial
X7 + 2 X6 + 3 X5 + 4 X4 + 5 X2
int a[ ] = { 1, 7, 2, 6, 3, 5, 4, 4, 5, 2 } ;

Problems
· Only integer coefficients
· Not intuitive - What is a[ 7 ]

struct term
{ a[ ]
int coeff ; 1 7 2 6 3 5 4 4 5 2
int exp ;
};
struct term a[ ] = { 1, 7, 2, 6, 3, 5, 4, 4, 5, 2 } ;
printf ( "%d %d", a[3].coeff, a[3].exp ) ;

Passing Array of Structures


struct term a[ ]
{
int coeff ; int exp ; 1 7 2 6 3 5 4 4 5 2
};
main( ) p p+1 p+2
{
struct term a[ ] = { 1, 7, 2, 6, 3, 5, 4, 4, 5, 2 } ;
fun ( a ) ;
}
fun ( struct term *p )
{
int i ;
for ( i = 0 ; i < 5 ; i++ )
{
printf ( "%d %d", ( * ( p + i ) ).coeff, ( *( p + i ) ).exp ) ;
printf ( "%d %d", p[ i ].coeff, p[ i ].exp ) ;
}
}

Polynomial Addn X7 + 2 X6 + 3 X5 + 4 X4 + 5 X2
X4 + X3 + X2 + X + 2
a[ ]
struct term
{ 1 7 2 6 3 5 4 4 5 2
int coeff ; b[ ]
int exp ;
}; 1 4 1 3 1 2 1 1 2 0

int polyadd ( struct term *, int, struct term *, int, struct term * ) ;
main( )
{
struct term a[ ] = { 1, 7, 2, 6, 3, 5, 4, 4, 5, 2 } ;
struct term b[ ] = { 1, 4, 1, 3, 1, 2, 1, 1, 2, 0 } ;
struct term c[20] ;
int numa = 5, numb = 5, numc, i ;
numc = polyadd ( a, numa, b, numb, c ) ;
Cont…

2
Cont…
for ( i = 0 ; i < numc ; i++ )
printf ( "%d x^%d + ", c[ i ].coeff, c[ i ].exp ) ;
}

int polyadd ( struct term *pa, int na, struct term *pb, int nb,
struct term *pc )
{
int i = 0, j = 0, k = 0 ;
while ( i < na && j < nb )
{
if ( pa[ i ].exp == pb[ j ] .exp )
{
pc[ k ].coeff = pa[ i ].coeff + pb[ j ] .coeff ;
pc[ k ].exp = pa[ i ].exp ;
i++ ; j++ ; k++ ;
}
Cont…

Cont… X7 + 2 X6 + 3 X5 + 4 X4 + 5 X2 X4 + X3 + X2 + X + 2
else while ( i < na )
{ {
if ( pa[ i ].exp > pb[ j ].exp ) pc[ k ] = pa[ i ] ;
i++ ; k++ ;
{
}
pc[ k ].coeff = pa[ i ].coeff ;
pc[ k ].exp = pa[ i ].exp ; while ( j < nb )
i++ ; k++ ; {
} pc[ k ] = pb[ j ] ;
pc[ k ] = pa[ i ] ;
else j++ ; k++ ;
{ }
pc[ k ] = pb[ j ] ;
j++ ; k++ ; return k ;
} }
}
} // end of while loop

Polynomial Multiplication
struct term
{
int coeff ;
int exp ;
};
int polymul ( struct term *, int, struct term *, int, struct term * ) ;
int polyadd ( struct term *, int, struct term *, int, struct term * ) ;
main( )
{
struct term a[ ] = { 1, 7, 2, 6, 3, 5, 4, 4, 5, 2 } ;
struct term b[ ] = { 1, 4, 1, 3, 1, 2, 1, 1, 2, 0 } ;
struct term c[20] ;
int numa = 5, numb = 5, numc, i ;
numc = polymul ( a, numa, b, numb, c ) ;
for ( i = 0 ; i < numc ; i++ )
printf ( "%d x^%d + ", c[ i ].coeff, c[ i ].exp ) ;
} Cont…

3
int polymul ( struct term *pa, int na, struct term *pb, int nb,
struct term *pc )
{
struct term t , temp[20] ;
int i, j, numpc, numtemp = 0, k ;
for ( i = 0 ; i < na ; i++ )
{ X7 + 2 X6 + 3 X5 + 4 X4 + 5 X2
for ( j = 0 ; j < nb ; j++ ) X4 + X3 + X2 + X + 2
{
t.coeff = pa[ i ].coeff * pb[ j ].coeff ;
t.exp = pa[ i ].exp + pb[ j ].exp ;
numpc = polyadd ( &t, 1, temp, numtemp, pc ) ;
for ( k = 0 ; k < numpc ; k++ )
Solution
temp[ k ] = pc[ k ] ;
numtemp = numpc ; Iteration t temp pc
}
} 1 x11 Empty x11
return numpc ; 2 x10 Empty x10
}

4
Two Dimensional
Arrays
Asang Dani

Objectives

· Declaring and using two dimensional arrays


· How to write a program to find the saddle point

main( )
Two Dimensional Array
{
int a[ ][ 5 ] = {
{ 2, 6, 1, 8, 4 } ,
optional { 1, 2, 5, 6, 8 },
optional
compulsory { 7, 9, 8, 7, 21 },
{ 4, 5, 6, 8, 10 } int b[ ][1][2][3]
};
int i, j ; 21
printf ( "%d", a[ 2 ][ 4 ] ) ; compulsory
printf ( "%d %d", sizeof ( a ), a ) ;
for ( i = 0 ; i <= 3 ; i + + ) 40 4080
{
for ( j = 0 ; j <= 4 ; j + + )
printf ( "%d", a [ i ][ j ] ) ;
printf ( ”\n” ) ;
}
}

1
main( )
{
Saddle Point
int a[ ][ 5 ] = { big = small ;
5, 2, 2, 6, 5, for ( r = 0 ; r <= 4 ; r++ )
4, 9, 3, 4, 8, {
9, 4, 2, 1, 9, if ( a[ r ][ col ] > big )
7, 1, 0, 8, 7, {
6, 2, 1, 5, 9 big = a[ r ][ col ] ;
}; row = r ;
for ( i = 0 ; i <= 4 ; i++ ) }
{ }
small = a[ i ][ 0 ] ; if ( big == small )
for ( j = 0 ; j <= 4 ; j++)
{
{
if ( a[ i ][ j ] < small ) printf ( "%d", big ) ;
{ printf ( "%d %d", row, col );
small = a[ i ][ j ] ; break ;
col = j ; }
} }
}
Define variables
}

Problem
· Given 2 matrices A & B of the order ( n x n )
· Upper triangle = 0, Lower triangle = Non-zero
· Generate C of n x ( n + 1 ) t o accommodate A and B
A C B C
a[ 4 ][ 4 ]
0, 0 0, 0 0, 0 0, 1
1 0 0 0 1, 0 1, 0 1, 0 0, 2
5 2 0 0 2, 0 2, 0 2, 0 0, 3
6 7 3 0 3, 0 3, 0 3, 0 0, 4
1 11 15 16 18
8 9 10 4 1, 1 1, 1 1, 1 1, 2
5 2 12 17 19
2, 1 2, 1 2, 1 1, 3
6 7 3 13 20
11 0 0 0 3, 1 3, 1 3, 1 1, 4
8 9 10 4 14
15 12 0 0 2, 2 2, 2 2, 2 2, 3
16 17 13 0 c[ 4 ][ 5 ] 3, 2 3, 2 3, 2 2, 4
18 19 20 14 3, 3 3, 3 3, 3 3, 4
b[ 4 ][ 4 ]

main( ) A C B C
{ 0, 0 0, 0 0, 0 0, 1
int a[ ][ 4 ] = {
1, 0, 0, 0, 1, 0 1, 0 1, 0 0, 2
5, 2, 0, 0, 2, 0 2, 0 2, 0 0, 3
6, 7, 3, 0, 3, 0 3, 0 3, 0 0, 4
8, 9, 10, 4 1, 1 1, 1 1, 1 1, 2
};
int b[ ][ 4 ] = { 2, 1 2, 1 2, 1 1, 3
11, 0, 0, 0, 3, 1 3, 1 3, 1 1, 4
15, 12, 0, 0, 2, 2 2, 2 2, 2 2, 3
16, 17, 13, 0, 3, 2 3, 2 3, 2 2, 4
18, 19, 20, 14
}; 3, 3 3, 3 3, 3 3, 4
int c[ 4 ][ 5 ], i, j ; for ( i = 0 ; i <= 3 ; i ++ )
for ( j = 0 ; j <= 3 ; j++ ) {
{ for ( j = i + 1 ; j <= 4 ; j++ )
for ( i = j ; i <= 3 ; i++ ) c[ i ][ j ] = b[ j - 1 ][ i ] ;
c[ i ][ j ] = a[ i ][ j ] ; }
} Cont…

2
Cont…

for ( i = 0 ; i <= 3 ; i ++ )
{
for ( j = 0 ; j <= 4 ; j++ )
printf ( "%d ", c[ i ][ j ] ) ;
printf ( "\n" ) ;
}
}

Determine
Determine values of a[ i ][ j ] and b[ i ][ j ] from matrix c

Determine a[ i ][ j ] Determine b[ i ][ j ]
if ( j > i ) if ( j > i )
element = 0 ; element = 0 ;
else else
element = c[ i ] [ j ] ; element = c[ j ] [ i + 1 ] ;
a[ 3 ][ 2 ] = c[ 3 ][ 2 ] b[ 3 ][ 2 ] = c[ 2 ][ 4 ]

1 0 0 0 11 0 0 0 1 11 15 16 18
5 2 0 0 15 12 0 0 5 2 12 17 19
6 7 3 0 16 17 13 0 6 7 3 13 20
8 9 10 4 18 19 20 14 8 9 10 4 14

4x4 4x4 4x5

Problem
· A magic square of 4 rows x 4 columns contains different
elements. Write a function to verify whether the sum of
each individual column elements, sum of each individual
row elements and sum of diagonal elements is equal or
not.

16 3 2 13
5 10 11 8
9 6 7 12 34
4 15 14 1

3
Sparse Matrices
Asang Dani

Objectives

· Sparse matrices
· How to pass arrays
· Performing 3 tuple conversion

Sparse Matrices
r c Non-zero
15 0 0 22 0 -15 6 6 8
0 11 3 0 0 0 0 0 15
0 0 0 -6 0 0 0 3 22
0 0 0 0 0 0 0 5 -15
91 0 0 0 0 0 1 1 11
0 0 28 0 0 0 1 2 3
2 3 -6
4 0 91
3-Tuple Form 5 2 28

1
Passing Arrays
main( ) fun2 ( int *pa, int r, int c )
{ {
int a[ ][ 4 ] = { General
int i, j ;
1, 0, 3, 8,
5, 2, 0, 7 for ( i = 0 ; i < r ; i++ )
}; {
for ( j = 0 ; j < c ; j++ )
fun1 ( a, 2, 5 ) ;
fun2 ( a, 2, 5 ) ; {
} printf ( "%d", *pa ) ;
fun1 ( int ( *p )[ 4 ], int r, int c ) pa++ ;
{ }
int i, j ; }
}
for ( i = 0 ; i < r ; i++ )
{ a[ ]
for ( j = 0 ; j < c ; j++ ) 1 0 3 8 5 2 0 7
printf ( "%d", p[ i ][ j ] ) ;
} p[ 1 ][ 3 ] *(*(p+1)+3)
}

3-Tuple Conversion
# include <alloc.h> r c Non-zero
main( )
{ 3 4 6
int a[ 3 ][ 4 ] = { 0 0 4
4, 0, 0, 1,
2, 0, 0, 9, 0 3 1
6, 1, 0, 0 1 0 2
}; 1 3 9
int *ta ; 2 0 6
ta = create ( a, 3, 4 ) ; 2 1 1
display ( ta ) ;
free ( ta ) ;
}

Cont… for ( i = 0 ; i < r ; i++ )


{
int * create ( int *pa, int r, int c )
for ( j = 0 ; j < c ; j++ )
{
{
int rows, *p, i, j, k ; if ( *pa != 0 )
rows = count ( pa, r, c ) + 1 ; {
p = ( int * ) malloc ( rows * p[ k ] = i ; k++ ;
3 * sizeof ( int ) ) ; p[ k ] = j ; k++ ;
p[ k ] = *pa ; k++ ;
p[ 0 ] = r ; p[ 1 ] = c ;
p[ 2 ] = rows - 1; k = 3 ; }
pa ++ ;
pa }
}
return p ;
4 0 0 1 2 0 0 9 6 1 0 0 }
p
3 4 6 0 0 4 0 3 1 1 0 2 1 3 9 2 0 6 2 1 1

2
Cont…

int count ( int *pa, int r, int c )


{
int count = 0, i, j ;
for ( i = 0 ; i < r ; i++ )
{
for ( j = 0 ; j < c ; j++ )
{
if ( *pa != 0 ) pa
count ++ ;
4 0 0 1 2 0 0 9 6 1 0 0
pa++ ;
}
}
return count ;
}

Cont…

void display ( int *p )


{
int i, rows ;
rows = p[ 2 ] + 1 ;
for ( i = 0 ; i < rows * 3 ; i++ )
{
if ( i % 3 == 0 )
printf ( "\n" ) ;
printf ( "%d\t", p[ i ] ) ;
}
}

p
3 4 6 0 0 4 0 3 1 1 0 2 1 3 9 2 0 6 2 1 1

3
Transpose of
Sparse Matrices
Asang Dani

Objectives

· What is a transpose?
· How to get the transpose of a sparse matrix

Transpose
4 0 0 3 4 3 0 11 12
3 0 0 1 0 0 0 0 0
0 0 2 5 0 0 2 0 0
11 0 0 0 3 1 5 0 1
12 0 0 1

4 5 9
5 4 9
0 0 4 0 0 4
0 3 3 0 1 3 Hint
1 0 3 0 3 11
1 3 1 Search for 0, 1, 2, etc. in
0 4 12 first column of matrix A
2 2 2
2 3 5 2 2 2 and then set matrix B
3 0 11 3 0 3
4 0 12 3 1 1
4 3 1 3 2 5
3 4 1

1
Program - Transpose
#include <alloc.h> display ( tb ) ;
main( ) free ( ta ) ;
{ free ( tb ) ;
int a[ 5 ][ 4 ] = { }
4, 0, 0, 3,
3, 0, 0, 1, 5 4 9 4 5 9
0, 0, 2, 5, 0 0 4 0 0 4
11, 0, 0, 0, 0 3 3 0 1 3
12, 0, 0, 1 1 0 3 0 3 11
};
int *ta , *tb ; 1 3 1 0 4 12
ta = create ( a, 5, 4 ) ; 2 2 2 2 2 2
tb = transpose ( ta ) ; 2 3 5 3 0 3
3 0 11 3 1 1
4 0 12 3 2 5
4 3 1 3 4 1

int * transpose ( int *ta ) tb[ 0 ] = cols = ta[ 1 ] ;


{ tb[ 1 ] = ta[ 0 ] ;
int rows, c, nz, p, q, cols ; tb[ 2 ] = nz = ta[ 2 ] ;
int *tb ; q=1;
rows = ta[ 2 ] + 1 ;
for (c = 0 ; c < cols ; c++ )
tb = ( int * ) malloc ( rows *
{
3 * sizeof ( int ) ) ;
for ( p = 1; p <= nz; p++)
5 4 9 4 5 9 {
0 0 4 0 0 4 if ( ta[ p * 3 + 1 ] == c )
0 3 3 0 1 3 {
1 0 3 0 3 11 tb[ q*3 ] = ta[ p*3+1 ] ;
tb[ q*3+1 ] = ta[ p*3 ] ;
1 3 1 0 4 12 tb[ q*3+2 ] = ta[ p*3+2 ];
2 2 2 2 2 2 q++ ;
2 3 5 3 0 3 }
3 0 11 3 1 1 }
}
4 0 12 3 2 5
return tb ;
4 3 1 3 4 1 }

Problem
Write a program to verify whether transpose of a given
sparse matrix is same as the original sparse matrix.

2
Addition of
Sparse Matrices
Asang Dani

Objectives
· Sparse Matrices
· Perform addition of two sparse matrices

Addition of SM
4 0 0 3 7 0 0 0 11 0 0 3
3 0 0 1 0 2 1 0 3 2 1 1
0 0 2 5 + 0 5 0 2 = 0 5 2 2
11 0 0 0 0 0 0 0 11 0 0 0
12 0 0 1 1 0 0 0 13 0 0 1

5 4 9 5 4 6 5 4 12
0 0 11
0 0 4 0 0 7 0 3 3
0 3 3 1 1 2 1 0 3
1 0 3 + 1 2 1 =
1 1 2
1 3 1 2 1 5 1 2 1
2 2 2 2 3 2 1 3 1
2 3 5 4 0 1 2 1 5
3 0 11 2 2 2
4 0 12 2 3 2
4 3 1 3 0 11
4 0 13
4 3 1

1
5 4 9 5 4 6 5 4 12 Tips
0 0 4 0 0 7 0 0 11
0 3 3 1 1 2 0 3 3
1 0 3 + 1 2 1 = 1 0 3
1 3 1 2 1 5 1 1 2
2 2 2 2 3 2 1 2 1
1 3 1
2 3 5 4 0 1 2 1 5
3 0 11 2 2 2
4 0 12 2 3 2
4 3 1 3 0 11
4 0 13
4 3 1

· Rows in C = Rows in A + Rows in B - Sometimes True


· Row of A < Row of B - Copy from A
· Row of B < Row of A - Copy from B
· Row A = Row B Check columns

Addition of SM
# include <alloc.h> int *ta, *tb, *tc ;
main( ) ta = create ( a, 5, 4 ) ;
{ tb = create ( b, 5, 4 ) ;
int a[ 5 ][ 4 ] = { tc = add ( ta, tb ) ;
4, 0, 0, 3, display ( tc ) ;
3, 0, 0, 1, free ( ta ) ;
0, 0, 2, 5, free ( tb ) ;
11, 0, 0, 0, free ( tc ) ;
12, 0, 0, 1 }
};
5 4 9 5 4 6
int b[ 5 ][ 4 ] = {
0 0 4 0 0 7
7, 0, 0, 0, 0 3 3 1 1 2
0, 2, 1, 0, 1 0 3 + 1 2 1
0, 5, 0, 2, 1 3 1 2 1 5
0, 0, 0, 0 2 2 2 2 3 2
1, 0, 0, 0 2 3 5 4 0 1
}; .. .. ..

int * add ( int *s1, int *s2 ) else


{ rowa = cola = BIGNUM ;
int *p, i, j, k ; #define BIGNUM 100
int max, maxa, maxb ; if ( j <= maxb )
int rowa, cola, vala ; {
int rowb, colb, valb ; rowb = s2[ j * 3 + 0 ] ;
colb = s2[ j * 3 + 1 ] ;
maxa = s1[ 2 ] ; maxb = s2[ 2 ] ; valb = s2[ j * 3 + 2 ] ;
max = maxa + maxb + 1 ;
}
p = ( int * ) malloc ( max * 3 * else
sizeof (int) ) ; rowb = colb = BIGNUM ;
i=j=k=1;
while ( k <= max ) 5 4 9 5 4 6
{ 0 0 4 0 0 7
if ( i <= maxa ) 0 3 3 1 1 2
{ 1 0 3 + 1 2 1
rowa = s1[ i * 3 + 0 ] ; 1 3 1 2 1 5
cola = s1[ i * 3 + 1 ] ; 2 2 2 2 3 2
vala = s1[ i * 3 + 2 ] ; 2 3 5 4 0 1
} .. .. ..

2
Cont… if ( rowa > rowb )
if ( rowa < rowb ) {
{ p[ k * 3 + 0 ] = rowb ;
p[ k * 3 + 0 ] = rowa ; p[ k * 3 + 1 ] = colb ;
p[ k * 3 + 1 ] = cola ; p[ k * 3 + 2 ] = valb ;
p[ k * 3 + 2 ] = vala ; j++ ;
i++ ; }
}
5 4 9 5 4 6 5 4 12
0 0 4 0 0 7 0 0 11
0 3 3 1 1 2 0 3 3
1 0 3 + 1 2 1 = 1 0 3
1 3 1 2 1 5 1 1 2
2 2 2 2 3 2 1 2 1
1 3 1
2 3 5 4 0 1 2 1 5
3 0 11 2 2 2
4 0 12 2 3 2
4 3 1 .. ..Cont…
..

Cont… if ( cola > colb )


{
if ( rowa == rowb ) p[ k * 3 + 0 ] = rowb ;
{
if ( cola == colb ) p[ k * 3 + 1 ] = colb ;
{ p[ k * 3 + 2 ] = valb ;
p[ k*3+0 ] = rowa ; j++ ;
p[ k* 3+1 ] = cola ; }
p[ k*3+2 ] = vala + valb ; } // if
i++ ; j++ ; max- - ; k++ ;
} } // end of while loop

if ( cola < colb )


{ 5 4 9 5 4 6
p[ k * 3 + 0 ] = rowa ; 0 0 4 0 0 7
p[ k * 3 + 1 ] = cola ; 0 3 3 1 1 2
p[ k * 3 + 2 ] = vala ; 1 0 3 + 1 2 1
i++ ; 1 3 1 2 1 5
} 2 2 2 2 3 2
2 3 5 4 0 1
.. .. ..

Cont…
p[ 0 ] = s1[ 0 ] ;
p[ 1 ] = s1[ 1 ] ;
p[ 2 ] = max ;
return p ;
} // end of add( )

5 4 9 5 4 6 5 4 12
0 0 4 0 0 7 0 0 11
0 3 3 1 1 2 0 3 3
1 0 3 + 1 2 1 = 1 0 3
1 3 1 2 1 5 1 1 2
2 2 2 2 3 2 1 2 1
1 3 1
2 3 5 4 0 1 2 1 5
3 0 11 2 2 2
4 0 12 2 3 2
4 3 1 .. ..Cont…
..

3
Multiplication of
Sparse Matrices
Asang Dani

Objectives

·Matrix multiplication
·Multiplication of sparse matrices

Matrix Multiplication
4 0 0 1 1 0 4 3 ik k j i k kj
2 0 0 9 x 2 0 = 2 27 00 00 00 01
6 1 0 0 0 0 8 0 01 10 01 11
0 3 02 20 02 21
3x 4 4x 2 3x 2 03 30 03 31
10 00 10 01
for ( i = 0 ; i < 3 ; i + + )
{ 11 10 11 11
for ( j = 0 ; j < 2 ; j + + ) 12 20 12 21
{ 13 30 13 31
s=0;
for ( k = 0 ; k < 4 ; k + + ) 20 00 20 01
s = s + a[ i ][ k ] * b[ k ][ j ] ; 21 10 21 11
22 20 22 21
c[ i ][ j ] = s ;
23 30 23 31
}
}

1
Multiplication of SM
# include <alloc.h> int *ta, *tb, *tc ;
main( )
ta = create ( a, 3, 4 ) ;
{
tb = create ( b, 4, 2 ) ;
int a[ 3 ][ 4 ] = {
tc = mul ( ta, tb ) ;
4, 0, 0, 1,
2, 0, 0, 9, display ( tc ) ;
6, 1, 0, 0 free ( ta ) ;
}; free ( tb ) ;
free ( tc ) ;
int b[ 4 ][ 2 ] = { }
1, 0,
2, 0,
0, 0,
0, 3
};
Cont…

int* mul ( int *x, int *y ) s_in_x ( int *p, int i )


{ {
int *c , i , j, k, px ; int j ;
k = x[ 0 ] * y[ 1 ] + 1 ; for ( j = 1 ; j <= p[ 2 ] ; j++ )
z = ( int * ) malloc ( k * 3 * {
if ( p[ j * 3 ] == i )
sizeof ( int ) ) ;
k=1; return j ;
} 3 4 6
for ( i = 0 ; i < x[ 0 ] ; i++ ) }
{ 0 0 4
return -1 ;
for ( j = 0 ; j < y[ 1 ] ; j++ ) } 0 3 1
{ 1 0 2
px = s_in_x ( x, i ) ;
1 3 9
2 0 6
To be Continued...
2 1 1
p
3 4 6 0 0 4 0 3 1 1 0 2 1 3 9 2 0 6 2 1 1

int* mul ( int *x, int *y ) s_in_y ( int *p, int j, int colx )
{ {
/* Existing Code */ int i ;
for ( i = 0 ; i < x[ 0 ] ; i++ ) for ( i = 1 ; i <= p[ 2 ] ; i++ )
{ {
for ( j = 0 ; j < y[ 1 ] ; j++ ) if ( p[ i * 3 + 1 ] == j &&
{ p[ i * 3 ] == colx )
px = s_in_x ( x, i ) ; return i ;
if ( px != -1 ) } col X = row Y
{ return -1 ;
py = s_in_y ( y, j, }
3 4 6 4 2 3
x[ px * 3+1 ] ) ;
0 0 4 0 0 1
0 3 1 1 0 2
4 0 0 1 1 0 1 0 2 3 1 3
2 0 0 9 2 0 1 3 9
6 1 0 0 0 0 2 0 6
0 3 2 1 1

2
int* mul ( int *x, int *y ) 4 0 0 1 1 0
{
for ( i = 0 ; i < x[ 0 ] ; i++ ) 2 0 0 9 2 0
{ 6 1 0 0 0 0
for ( j = 0 ; j < y[ 1 ] ; j++ ) 0 3
{
px = s_in_x ( x, i ) ; 3 4 6 4 2 3
if ( px != -1 ) 0 0 4 0 0 1
{ 0 3 1 1 0 2
s=0;
1 0 2 3 1 3
while ( x[ px * 3 ] == i )
{ 1 3 9
py = s_in_y ( y, j, x[ px*3+1 ] ); 2 0 6
2 1 1
if ( py != -1 )
s = s + x[ px * 3 + 2 ] * y[ py * 3 + 2 ] ;
px++ ;
}
..
}

int* mul ( int *x, int *y ) if ( s != 0 )


{ {
int *z, i, j, k, px, py, s ;
z[ k * 3 + 0 ] = i ;
for ( i = 0 ; i < x[ 0 ] ; i + + ) z[ k * 3 + 1 ] = j ;
{ z[ k * 3 + 2 ] = s ;
for ( j = 0 ; j < y[ 1 ] ; j + + ) k++ ;
{
px = s_in_x ( x, i ) ; }
if ( px != -1 ) } // if
{ } // j loop
s=0; } // i loop
while ( x[ px * 3 ] == i ) z[ 0 ] = x[ 0 ] ;
{ z[ 1 ] = y[ 1 ] ;
py = s_in_y ( ... ) ; z[ 2 ] = k - 1 ;
if ( py != -1 ) return z ;
s = s + ... ; }
px++ ;
}

3
Storage
Asang Dani

Objectives

· How two dimensional arrays are stored


· 3-D arrays
· 4-D arrays
· N-D arrays

Storage - 2D Array 3 x 4 matrix


a00 a01 a02 a03
a10 a11 a12 a13
a20 a21 a22 a23
Row major
a00 a01 a02 a03 a10 a11 a12 a13 a20 a21 a22 a23

int a[ 3 ][ 4 ] ; int a[ m ][ n ]
a23 BA + 2 * 4 + 3 aij BA + i * n + j

Col major
a00 a10 a20 a01 a11 a21 a02 a12 a22 a03 a13 a23

int a[ 3 ][ 4 ] ; int a[ m ][ n ]
a23 BA + 3 * 3 + 2 aij BA + j * m + i

1
3-D Array

a[ 1…u1, 1…u2, 1…u3 ] u2

u1
u3
Row major
a[ i ][ j ][ k ] α + ( i – 1 ) * u2u3 + ( j – 1 ) * u3 + ( k - 1)

Column major
a[ i ][ j ][ k ] α + ( i – 1 ) * u2u3 + ( k – 1 ) * u2 + ( j - 1)

4-Dimensional Array
a[ 1…u1, 1…u2, 1…u3, 1…u4 ]

Row major
a[ i ][ j ][ k ][ l ] α + ( i – 1 ) * u2u3u4 + ( j – 1 ) * u3u4
+ ( k – 1 ) *u4 + ( l – 1 )

Column major
a[ i ][ j ][ k ][ l ] α + ( i – 1 ) * u2u3u4 + ( j – 1 ) * u3u4
+ ( l – 1 ) *u3 + ( k – 1 )

n-Dimensional Array
a[ 1…u1, 1…u2, 1…u3, …, un ]

Row major Column major


a[ i1 ][ i2][ i3 ][ .. ][ in ] a[ i1 ][ i2][ i3 ][ .. ][ in ]

α + ( i1 – 1 ) * u2u3u4…un α + ( i1 – 1 ) * u2u3u4…un
+ ( i2 – 1 ) * u3u4…un + ( i2 – 1 ) * u3u4…un
+ ( i3 – 1 ) * u4u5…un + ( i3 – 1 ) * u4u5…un
+ ( i4 – 1 ) * u5u6…un + ( i4 – 1 ) * u5u6…un
+ +
. .
. .
. .
+ ( i n - 1 – 1 ) * un + ( i n – 1 ) * un - 1
+(in–1) +(in-1–1)

2
Problem
Find location of element A[ 6 ][ 2 ][ 3 ][ 8 ] relative to first
element of the array A[ 3:8][ 2:4][ 3:6 ][ 6:9 ]
Row major
α +(6–3)*((4–2+1)*(6–3+1)*(9–6+1))
+(2–2)*((6–3+1)*(9–6+1))
+(3–3)*(9–6+1)
+ 8– 6

Col major
α +(6–3)*((4–2+1)*(6–3+1)*(9–6+1))
+(2–2)*((6–3+1)*(9–6+1))
+(8–6)*(6–3+1)
+ 3– 3

3
Dynamic Memory
Allocation
Asang Dani

Objectives

·Limitations on arrays
·Dynamic memory allocation
·How the memory allocation is done

Arrays
No Flexibility
main( )
{
int m1, m2, m3, i, per [ 10 ] ;
for ( i = 0 ; i <= 9 ; i++ )
{
printf ( "Enter marks" ) ;
scanf ( "%d %d %d", &m1, &m2, &m3 ) ;
per [ i ] = ( m1 + m2 + m3 ) / 3 ;
printf ( "%d", per [ i ] ) ;
}
}

1
Dynamic Allocation
# include "alloc.h"
main( )
{
int *p ; int m1, m2, m3, i, per ;
Memory printf ( "Enter no. of students" ) ;
p scanf ( "%d", &n ) ;
malloc
p int( *n)*malloc
= (malloc (2n) *; 2 ) (; n * 2 ) ;
for ( i = 0 ; i < n ; i++ )
{
n*2 scanf ( "%d%d%d", &m1, &m2, &m3 ) ;
per = ( m1 + m2 + m3 ) / 3 ;
* ( p + i ) = per ;
}
for ( i = 0 ; i < n ; i++ )
printf ( "%d", *( p + i ) ) ;
}

Memory Allocation
Array malloc( )

Static Dynamic

Compile Time Execution Time

· Variables are created only during execution


· Static - Arrangement made at compilation time
- Arrangement - Offset + Instruction to create var
· Dynamic - Arrangement made at execution time
- Arrangement - Call to malloc( )

int x, y ;
main( ) Allocation
{
int j ; float k ; int *p ;
p = ( int * ) malloc ( 20 ) ; Compiler
}
· Symbol table entries for variables
- Name, Scope, Length
- Offset from DS (global), SS (local)
· Instructions for local variables
· Call to malloc( )
· Creates OBJ and discards Symbol Table
· Our object code + Library’s object code Linker
· Create EXE file format (Header to help loader)
· If too many globals - Loader fails Loader
Fatal
· If too many locals - Stack overflow
· If too much dynamic demand - Heap full

2
Better Still...
?
int *p[ ] ;
char ch = ’Y’ ;
while ( ch = = ’Y’ )
{
scanf ( "%d %d %d", &m1, &m2, &m3 ) ;
per = ( m1 + m2 + m3 ) / 3 ;
p
p[ =i ]malloc
malloc ( =int
((int
*2 ))(*malloc
;2) malloc
) ; ( 2 () 2; ) ; p p p
*( p +
*p = per ;i ) = per ;
printf ( "Another student y/n" ) ; 55 63 28 45
ch = getche( ) ;
}
Memory Leaks

Best... NULL

55 400 63 750 28 900 45 120 60


200 400 750 900 120
node

55 63 28 45 60

data link
NULL
Linked List
struct node
{
int data ;
struct node *link ;
};

3
Procedural
Programming
Yashavant Kanetkar

Objectives
· Disadvantages of Procedural Programming
· The need for Object-Oriented Programming
· How structures in C++ are different

Structures
struct emp Structure Name
{
char n[20] ; int a ; float s ; Structure Elements
};
struct emp e1 = { "Anil", 23, 5000 } ; e1- Structure Var.
struct emp e2 = { "Amol", 24, 6000 } ; p - Structure Pointer
e[10] - Array of struct.
printf ( "%s %d %f", e1.n, e1.a, e1.s ) ;
struct emp *p ; Structure
p = &e1 ; Operators
printf ( "%s %d %f", p->n, p->a, p->s ) ;
e1 e2 p
Anil 23 5000 Amol 24 6000 400
400 500
Structure - Blueprint, Template
Structure Variable - Specific Instances enjoying different data

1
Stack

Top 20
Top 10 10
Top
Empty Push 10 Push 20

Top 20
10 Top 10
Top
Pop Pop Empty

Procedural Programming
Data1 void push ( ... ) - Sequence
Data2
{ - Decision
// code - Repetition
Data3 - Case
}
:::::: void pop ( ... )
Statement 1 { Control Inst.
Statement 2 // code Local variables
Statement 3 }
Statement 4 main( ) - AKA Structured Prog.
Statement 5 { - Crux - Functional Abstracn
Statement 6 Call push - Reuse at function level
Call pop - Ex. C, Pascal, Ada
:::::
}
Limitations:
- Functions - Poor real world model
- Routines - No importance to data
- Procedures - No true reuse

Real-World Model

· 4-Cylinder Engine
Objects · Synchromesh Gearbox
· Anti-lock Break
· 1.5 Ton AC
· Karaoke Sound

Reusable Objects
· Frame Window
· Dockable Toolbar
· Popup Menu
· Flat Scrollbar
· Push Button

2
Object Contents
4-Cylinder Engine

Functions Data
· Igniting fuel · Oil Temp.
· Moving piston · Oil Viscosity
· Opening valves · RPM
· Ejecting burnt fuel · Timing details
· Rotating crank · Type of fuel

Dockable Toolbar

Functions Data
· Create toolbar · Size
· Display toolbar · No. of buttons
· Change color · Size of button
· Change size · Color
· Change font · Font

Procedures Properties

More Objects
Stack Object

Functions Data
· Push( ) · Array
· Pop( ) · Top
· Printall( )

DateTime Object

Functions Data
· getdate( ) · dd, mm, yy
· gettime( ) · h, m, s
· setdate( )
· settime( )

3
Object Oriented
Solution
Yashavant Kanetkar

Objectives
· Basics of Classes and Objects
· Access modifiers
· Data Members and Member Functions

Procedural Solution
datetime.c stack.c Use

struct datetime struct stack struct stack s1 ;


{ { s1.a[4] = 8 ;
int dd, mm, yy ; int top ; s1.top = -66 ;
int h, m, s ; int a[10] ;
}; };
void getdate( ) void push ( ... )
{ { Limitations
// code // code - No importance to data
} }
- Stress on procedures
void setdate ( ... ) void pop ( ... )
{ {
// code // code
} }

1
OO Solution
stack.c Use
struct stack stack s1, s2 ;
{ s1.push ( .. ) ;
private :
int top ; s1.push ( .. ) ;
int a[10] ; s2.push ( .. ) ;
public : s2.push ( .. ) ;
s2.pop( ) ;
void push ( ... )
{ s1.top = -1 ; 
// code s1.a[ 4 ] = 45 ; 
}
void pop ( ... )
{
// code Facts
}
- Ex. C++, Java, SmallTalk
};
- 1980, AT&T Bell Labs
- Bjarne Stroustrup

Difference

C C++

Collection Collection of
of Data Data & Funs. Classes

Class Object
- Blueprint, Template - Specific Data
- Data & Functions - Functions
Unique
General
Class Stack Object s1 Object s2
- a[ 10 ] - 5 elements - 7 elements
- top - top = 4 - top = 6
- push( ), pop( ) push( ), pop( ) push( ), pop( )

Classes In C++
z1
# include <iostream.h> i j
Class members are class a 10 3.14
by default private {
int i ;
float j ; z2
}; i j
class is void main( ) 20 6.28
optional {
a z1 = { 10, 3.14 } ;
cout << z1.i << z1.j ; z1, z2 - Objects
a z2 = { 20, 6.28 } ;
cout << z2.i << z2.j ;
}
cout - Console Output
<< - Insertion Operator
Overloaded cout << z1.i << z1.j ;
operator
printf ( "%d %f", z1.i, z1.j ) ;


2
Making It Work
# include <iostream.h>
class a
{
public :
int i ; float j ;
} ;
void main( )
{
a z = { 10, 3.14 } ;
cout << z.i << z.j ;
}

Running C++ Programs


File Menu
New
Win32 Console Application
Supply Application name as 'Sample'
Select 'An Empty Project'
File Menu
New
C++ Source File !
Supply File name
Type & Save Ctrl F5
Build 'Sample.exe'
Execute 'Sample.exe'

3
Classes In C++
Yashavant Kanetkar

Objectives
· How to work with multiple objects
· How to print the data
· How to construct objects

Still Better Way... Can functions be


hidden?
class a Data
{ Hiding
private :
Encapsulation int i ; float j ;
at work
public :
void setdata ( int ii, float jj )
{ z1
i = ii ; j = jj ;
} i j
};
void main( ) 10 3.14
{
a z1, z2 ; z2
z1.setdata ( 10, 3.14 ) ;
z2.setdata ( 100, 2.5 ) ; i j
}
100 2.5

1
Which Is Better #include <iostream.h>
class sample
#include <iostream.h> {
class sample private :
{ int age ;
public : public:
int age ; void setdata ( int x )
}; {
if ( x > 0 )
void main( )
{ age = x ;
sample s1, s2 ; int x ; }
};
cin >> x ; void main( )
if ( x > 0 ) {
s1.age = x ; sample s1, s2 ; int x ;
cin >> x ; cin >> x ;
if ( x > 0 ) s1.setdata ( x ) ;
s2.age = x ; cin >> x ;
} s2.setdata ( x ) ;
}

void main( )
Printing The Data {
#include <iostream.h> a z1, z2 ;
class a z1.setdata ( 10, 3.14 ) ;
{ z2.setdata ( 100, 2.5 ) ;
private : z1.printdata( ) ;
int i ; float j ; z2.printdata( ) ;
public : }
void setdata ( int ii, float jj ) z1
{
i = ii ; j = jj ; i j
}
10 3.14
void printdata( )
{
z2
cout << i << " " << j ;
} i j
};
100 2.5

2
this Pointer
Yashavant Kanetkar

Objectives
· What comprises an object
· What is a this pointer
· Utility of the this pointer

class a
{
How Many Copies
private : z1 z2
int i ; i i
public : 10 20
void setdata ( int ii )
{
i = ii ; void setdata ( int i )
} {
void printdata( ) i = ii ;
{ }
cout << i ; void printdata( ) Shared
} {
}; cout << i ;
void main( ) }
{
a z1, z2 ; Member Functions
z1.setdata ( 10 ) ;
Conceptually - Many
z2.setdata ( 20 ) ;
Practically - One
}

1
The this Pointer
class ex
{ void setdata ( ex* const this,
private : int ii, float aa )
int i ; float a ;
public :
void setdata ( int ii, float aa ) e1
{
this -> i = ii ; i a
Optional this -> a = aa ;
} Caution!! 400 404
}; this Pointer cannot
e2
void main( ) be modified
{ i a
ex e1, e2 ;
e1.setdata ( 5, 5.5 ) ; 500 504
e2.setdata ( 10, 10.5 ) ;
} this
ex::setdata ( &e1, 5, 5.5 ) ; 500
400
ex::setdata ( &e2 10, 10.5 ) ;

Is this Necessary e1
class ex i a
{
private :
int i ; float a ; 400 404
public : e2
void setdata ( int i, float a )
{ i a
this -> i = i ;
this -> a = a ; 500 504
}
};
void main( )
{
ex e1, e2 ;
e1.setdata ( 5, 5.5 ) ;
e2.setdata ( 10, 10.5 ) ;
}

2
Access Specifier
& Constructor
Yashavant Kanetkar

Objectives
· Hiding versus security
· How constructors work
· Advantages of constructors
· Overloaded Constructors

Recap...
· Classes - Datatypes
· Objects - Variables
· Access Specifiers - private, public
- Facilitate Hiding
· Why create a project
· Why create Win32 Console application

To compile all files · Output in DOS window


at one shot · cout - sends output to console

1
Hiding vs Security
class sample
{ s
private : 10
int i ; float j ; 500 504
public:
p
void display( )
{ 500
cout << i ;
}
}; “The protection of private data can be
circumvented through pointers. But this,
void main( )
of course, is cheating.
{
C++ protects against accident rather than
sample s ;
deliberate fraud.” - Bjarne Stroustrup
int *p ;
p = ( int * ) &s ;
*p = 10 ;
}

C vs C++ class stack


{
struct stack Advantages private :
{ - Cleaner int top ; int a[ 10 ];
int top ; int a[ 10 ] ; - Better organized public :
}; stack( )
- Sure initialisation {
void init ( struct stack *s ) top = 0 ;
{ }
s -> top = 0 ; void push ( int x )
} {
void push ( struct stack *s, int x ) a[ top ] = x ;
top++ ;
{ }
s -> a[s -> top] = x ; s -> top++ ; };
} void main( )
void main( ) {
{ stack s1 ;
stack s1, s2 ; s1.push ( 10 ) ;
init ( &s1 ) ; push ( &s1, 10 ) ; stack s2 ;
init ( &s2 ) ; push ( &s2, 20 ) ; s2.push ( 5 ) ;
} }

class ex Constructors
{ e1
private : 2 Argument
int i ; float j ; Constructor i j
public :
ex ( int ii, float jj ) 10 3.14
{
i = ii ; j = jj ;
} Overloaded e2
ex( ) Functions
{ i j
i = 0 ; j = 0.0 ;
} 0 0.0
}; 0 Argument
void main( ) Constructor
{ Either I do it or you do it
ex e1 ( 10, 3.14 ) ; Object Creation
ex e2 ;
· Allocate space in memory
}
· Call the constructor

2
Function
Overloading
Yashavant Kanetkar

Objectives
· Function overloading
· Default values for arguments
· Pitfalls in overloading functions

Function Overloading
void set ( int i ) void main( )
{ {
set ( 10 ) ;
}
set ( 10, 3 ) ;
void set ( int i, int j )
set ( 10, 3.14 ) ;
{
set ( 3.14, 10 ) ; 
}
set ( 3.14, 10 ) ; 
void set ( int i, float j ) }
{
} Arguments must differ in
void set ( float jj, int ii ) · Number
{ · Order
}  · Type
int set ( float jj, int ii ) Different return types not
{ enough for overloading
} 

1
Two In One e1
class ex i j
{ Can we write
private : 0-Arg Ctor  10 3.14
int i ; float j ; e2
public : i j
ex ( int ii = 0, float jj = 0.0 )
{ 0 0.0
i = ii ; j = jj ;
} e4
}; i j
void main( ) Error-prone for too
many args 15 0.0
{
ex e1 ( 10, 3.14 ) ; e5
ex e2 ; i j
}
ex e3 ( , 1.2 ) ;  10 0.0
What if
ex e4 ( 15 ) ;  ex e6 = 2, 1.1 ;  Doesn’t create
ex e5 = 10 ;  ex e7( ) ;  an object

2
Constructors

Yashavant Kanetkar

Objectives
· Array of objects
· Calling constructors explicitly
· Pointer to an Object

Nameless
Calling Ctor Explicitly Objects
# include <iostream.h> void main( )
class ex {
{ A nameless object ex e1 ;
private : gets created e1 = ex ( 10, 19.5 ) ;
int i ; e1.display( ) ;
float f ; Object dies after
assignment ex e[ ] = {
public : ex ( 2, 3.4 ),
ex ( int x = 0, float y = 0.0 ) Better ex ( 3, 1.1 )
{ };
i=x;
f=y; ex e2 ( 1, 1.7 )
} ex e3 ( 3, 1.1 ) ;
ex f[ ] = { e1, e2, e3 } ;
void display( )
{ for ( int i = 0 ; i <= 2 ;
cout << i << f ;
} i++ )
}; · Define before use e[ i ].display( ) ;
· Doesn't die }

1
Pointer To An Obj.
# include <iostream.h> void main( )
class ex {
{ ex e ( 1, 2.5 ) ;
private : 1 2.5
int i ; float f ; e.display( ) ;
public : e.set ( 2, 5.5 ) ;
e.display( ) ; 2 5.5
ex ( int x, float y )
{ fun ( &e ) ;
i=x; f=y; e.display( ) ; 3 8.5
} }
void set ( int x, float y ) void fun ( ex *p )
{ {
i=x; f=y; p -> set ( 3, 8.5 ) ;
} }
void display( ) this ptr = address of e
{
cout << i << f ; Set new data - Call set( )
} Set data from other fun. - Pass addr.
};

2
Types of Ctors

Yashavant Kanetkar

Objectives
· Normal Constructor
· Copy constructor
· Overloaded Assignment Operator
· Which gets called when

Readymades
class ex void main( )
{
{ 0-Arg
}; ex e1 ;
· 0-Arg constructor ex e2 ; Overloaded =
· Copy constructor e2 = e1 ;
· Overloaded =
ex e3 = e2 ;
} Copy Constr.

1
Which Gets Called
class ex
{ Calls overloaded =
private : void main( )
int i ; float f ; {
public : ex e1 ( 1, 2.5 ) ;
ex ( int x = 0, float y = 0 ) ex e2 ;
{
i=x; f=y; e2 = e1 ;
} ex e3 = e1 ;
void set ( ex x ) e2.set ( e1 ) ;
{ ex e4 = 5 ;
i = x.i ; ex x = e1 e2.set ( 1 ) ;
} e2 = fun( ) ;
};
ex nameless obj. ( 1 ) }
ex fun( ) ex e4 ( 5 ) ;
{ ex x = nameless obj.
ex t ; Calls Copy Ctor
return t ;
} Calls Copy Ctor, Overloaded =

2
Operator
Overloading
Yashavant Kanetkar

Objectives
· What is operator overloading
· Need for Operator overloading
· Which operators cannot be overloaded

Operator Overloading
# include <iostream.h> comp operator + ( comp c2 )
class comp {
{ comp t ;
private : Return t.r = r + c2.r ;
Type
double r, i ; t.i = i + c2.i ;
public : return t ;
comp ( double rr = 0, } c = a.operator + ( b ) ;
double ii = 0 ) };
{ c = nameless obj.
r = rr ; void main( )
i = ii ; {
} comp a ( 1.0, 1.0 ) ;
void print( ) comp b ( 2.0, 2.0 ) ;
{ comp c ;
cout << r << i ; c=a+b;
}
cout << "c = " ;
c.print( ) ;
}

1
Tips About Overloading
· The operators . , :: , ? and : cannot be overloaded
· Precedence cannot be changed through overloading

· Overloading allowed for user-defined types

a.b - Can’t be broken :: - Resolves scope


Clumsy ? : - Don’t manipulate

2
Pre, Post and
References
Yashavant Kanetkar

Objectives
· Overloading of pre & post incr. operators
· Need of References
· Subtleties of References

Pre & Post


class index index operator ++ ( int n )
{ {
private : int count ; index t ;
public : t.count = count ;
index( ) count++ ;
{ return t ;
count = 0 ; }
} };
void display( )
{ void main( )
cout << count ; {
} index i, j, k ; i.operator ++( )
index operator ++ ( ) j = ++i ;
{ k = i++ ; i.operator ++(0)
index t ; i.display( ) ;
count++ ;
t.count = count ; j.display( ) ;
return t ; k.display( ) ;
} 2 1 1
}

1
References
int i = 10 ;
int &j = i ; 10 10 j - Reference
cout << i << j ; i - Referrent

j = 20 ; 20 20 i j
cout << i << j ; 10 300
300 400
i = 30 ; 30 30
cout << i << j ;

· Changing a reference changes referrent


· A reference is a const pointer
· A reference is automatically de-referenced
· Hence when we use a reference we reach a referrent

Subtleties
int i = 10 ;
Reference must always
int &j ;  be initialised
j=i;

int i = 10, k = 20 ;
int &j = i ;
20 20 30 Once tied always
j=k; remains tied
k = 30 ;
cout << i << j << k ;

· Multiple references are allowed


· No way to create a reference to a reference
· Array of references is not allowed

2
More About
References
Yashavant Kanetkar

Objectives
· Call by value
· Call by address
· Call by reference
· Which call to use when

Different Calls A · Automatic de-referencing


d
v · Avoids a copy
# include <iostream.h> void fun3 ( data &z )
{
struct data
z.i = 3 ; z.f = 10.5 ;
{
}
int i ; float f ;
}; }; Can all be fun( )
class emp void main( )
{ {
public : data d = { 1, 2.2 } ;
emp e ;
void fun1 ( data x ) 1 2.2
{ e.fun1 ( d ) ;
x.i = 2 ; x.f = 5.5 ; cout << d.i << d.f ;
e.fun2 ( &d ) ; 2 5.5
}
cout << d.i << d.f ;
void fun2 ( data *y ) e.fun3 ( d ) ; 3 10.5
{
y->i = 2 ; y->f = 5.5 ; cout << d.i << d.f ;
} }

1
Are References Necessary
class comp
{
public :
comp operator + ( comp c2 )
{
comp t ;
How to avoid a copy?
t.r = r + c2.r ;
t.i = i + c2.i ;

};
}
return t ;
 Use Reference

Use Pointer

void main( )
{
comp a ( 1.0, 1.0 ) ;
comp b ( 2.0, 2.0 ) ;
comp c ;
c=a+b; c = a.operator + ( b ) ;
}

2
Dynamic Memory
Allocation - I
Yashavant Kanetkar

Objectives
· What is Static Memory Allocation
· What is Dynamic Memory Allocation
· How memory is allocated on stack and heap
· Differences between static & dynamic allocation

Dynamic Memory Allocation


int i ; int *i ; float *a ;
float a ; i = ( int * ) malloc ( sizeof ( int ) ) ;
struct emp a = ( float * ) malloc ( sizeof ( float ) ) ;
{ struct emp
char n[ 20 ] ; {
int a ; char n[ 20 ] ;
float s ; int a ;
}; float s ;
emp e ; };
emp *e ;
e = ( emp * ) malloc ( sizeof ( emp ) ) ;

new i = new int ;


- Operator a = new float ;
- Does DMA e = new emp ;

1
Static V/s Dynamic

Top 2000
1.5
20
10

Stack Heap

int x, y ;
void main( )
Allocation
{
int j ; float k ; int *p ;
p = new int ; Compiler
}
· Symbol table entries for variables
- Name, Scope, Length
- Offset from DS (global), SS (local)
· Emits instructions for local variables
· Emits call to new( )
· Creates OBJ code and discards Symbol Table
· Our object code + Library’s object code Linker
· Create EXE file format (Header to help loader)
· If too many globals - Loader fails Loader
Fatal
· If too many locals - Stack overflow
· If too much dynamic demand - Heap full

2
Dynamic Memory
Allocation - II
Yashavant Kanetkar

Objectives

· Difference between new and malloc( )


· Difference between delete and free( )
· How to avoid memory leaks & dangling ptrs
· Allocating memory dynamically for an array

Named & Nameless Objects


class shape
{
private :
int i, j ;
};
shape p ; q
p
shape *q ; Garb.
4000
i j q = new shape ;
Garb. Garb.
i j

Garb. Garb.
Nameless Obj.
4000

1
Are new And malloc( ) Same
class ex void main( )
{ {
private : ex *p1, *p2 ;
int i ; float a ; p1 = new ex ;
public : p2 = new ex ( 10, 3.5 ) ;
ex( )
{ delete p1 ;
i=0; delete p2 ;
a = 0.0 ; }
} operator
ex ( int ii, float aa )
{
i = ii ;
a = aa ;
}
}; - new allocates memory, calls constructor
- What is allocated must be de-allocated
- delete calls destructor, deallocates memory

Avoid Memory Leaks - I


class ex void main( )
{ {
private : void f( ) ; If new is used in
int *p ; float *q ; f( ) ; constructor, use
public : } delete in destructor
ex ( int ii, float aa ) void f( )
{ {
p = new int ; ex e ( 10, 5.5 ) ;
q = new float ; }
*p = ii ; e
*q = aa ; p q Leaked
} memory
~ex( ) Destructor 300 400
{
delete p ; 10 5.5
delete q ; 300 400
}
}; Doesn't delete q

Array Allocation
int *q ;
q = new int ;
Can be a variable
int *p ;
p = new int[ 10 ] ;
for ( int i = 0 ; i < 10 ; i++ )
*(p+i)=i;

0 1 2 3 ..
40 44 48 ...

2
Avoid Memory Leaks - II
class ex void main( )
{ {
private : void f( ) ;
int *p ; float *q ; f( ) ;
public : }
ex ( ) void f( )
{ {
p = new int ; ex *z ;
q = new float ; z = new ex[ 10 ] ; delete [ ] z ;
*p = 0 ;
delete z ;
*q = 0 ; }
}
~ex( ) ex[0] ex[1] ex[2] ex[..]
{ p q p q p q p q
delete p ;
delete q ;
}
};

3
Static Members
Yashavant Kanetkar

Objectives
· Static Data Members
· Static Member Functions
· Static Storage Class
· Comparison of Instance, Static and Friend Fun.

Static s1.objects( )
;
# include <iostream.h> void main( ) s2.objects( )
;
class sample {
{ sample s1, s2 ;
int i ; sample :: objects( ) ;
static int count ; }
public : s1 s2
sample( ) i i
{
i=0; 0 0
count ++ ;
} 2
static void objects( )
{ count
cout << count ;
static functions can access
}
}; only static data
int sample::count = 0 ;

1
Difference
Function Access Private Within class Invoked using
Type Data / Functions scope Object

Member   
Static only static  
Friend   

2
Reuse
Mechanisms
Yashavant Kanetkar

Objectives
· Ways to reuse existing code
· Inheritance reuse mechanism
· Containership reuse mechanism
· What are templates
· When to use which mechanism

What Next
Class
· Data Hiding
· Guaranteed initialization of data
· Implicit type conversion – double to comp
· Function overloading
· Operator overloading
· User controlled memory management
· Shared data and functions

1
Reuse

Object-code Source-code
Level level

Containership Inheritance Templates

CStringList CWnd

CString
CButton

"Has a" "Like a"


relationship relationship

Relationships Window

Car Window Window MyWindow


Engine Statusbar Toolbar
Vehicle Toolbar Statusbar Toolbar Statusbar

Vehicle

Car
Window Window
Engine

Button Toolbar Combo Edit List

Toolbar will contain Combo will contain


multiple button objects Edit & List objects

2
Containership
and Inheritance
Yashavant Kanetkar

Objectives

· How containership works


· How Inheritance works
· Sample Programs

Containership class stringlist


{
class string private :
{ string s[ 50 ] ;
private : int c ;
char str[ 100 ] ; public :
public : stringlist( )
string ( char *s = " " ) {
{ c=0;
} }
void print( ) void add ( string t )
{ {
} s[ c ] = t ; c++ ;
}
// functions void printall( )
}; {
// code
}
};

1
Inheritance
# include <iostream.h> class index1: public index
class index {
{

private : protected :
int count ;
public :
void operator - -( )
{
public :
index( ) count - - ;
}
{
}; index1 i ;
count = 0 ;
} void main( )
void display( ) {
{
}
cout << count ; 
index i ;
i.display( ) ;
0

void operator ++ ( ) i++ ; 1


{ i.display( ) ;
count ++ ;i.operator ++( ) ; i- - ;
0
} i.display( ) ;
}; }

2
Virtual Functions
Yashavant Kanetkar

Objectives
· How to achieve runtime polymorphism
· How runtime polymorphism works
· Purpose of pure virtual functions

#include <iostream.h> class rectangle : public shape


class shape {
{ Keyword public :
public : void draw( )
void draw(
virtual void )draw( ) {
{ cout << "rect" ;
cout << "shape" ; }
} }; Same effect in data?
}; void main( )
{ No. Data
class circle : public shape shape *p ; isn't virtual
{ circle c ;
public : rectangle r ;
void draw( ) p = &c ; // no error
{ shape
p -> draw( ) ;
cout << "circle" ; circle
p = &r ;
} shape
p -> draw( ) ;
};
} rect

1
Pure Virtual Functions
#include <iostream.h> class rectangle : public shape
{
class shape
{ public :
public : void draw( )
virtual void draw( ) = 0 ; {
}; cout << "rectangle" ;
}
class circle : public shape } ;
{
public : void main( )
void draw( ) {
{ circle c1, c2, c3, c4, c5 ;
cout << "circle" ; rectangle r1, r2, r3, r4, r5 ;
} shape *p[10] = { &c1, &r4, .. } ;
}; for ( int i = 0 ; i <= 9 ; i++ )
p[ i ] -> draw( ) ;
X Same Interface }
X Different Implementation

Summary...
Upcasted pointer - base *b ;
derived d ;
b = &d ;

Abstract class - Contains at least one pure virtual function


- May contain non-virtual function
- Object creation not possible
Virtual fun. mechanism - Upcasted pointer
- If function names are same
- Base class version if non-virtual
- Derived class version if virtual
A virtual function is early bound if called through object

A virtual function is late bound if called through pointer


(upcasted or not)

2
Linked List
Yashavant Kanetkar
kanetkar@ksetindia.com

Objectives

Ë Limitation of Arrays
Ë What are linked lists
Ë How to create linked lists
Ë How to create a linked list of records

Why Linked Lists


Ë Array size cannot be changed
Ë Adjacent locations may not be available
Ë Insertion / Deletion is tedious
Ë Solution – Linked List

Data Link

55 63 28 45 60 N
Node Node Node Node Node

Ë No size limit
Ë Operations are easy

1
Linked List
# include <iostream> p q r ss
using namespace std ;
struct node
{ 55 63 28 45 N
int data ;
node *link ;
};
int main( )
{
node *p, *q, *r, *s ;
p = new node ;
q = new node ;
r = new node ;
s = new node ;
p -> data = 55 ; q -> data = 63 ; r -> data = 28 ; s -> data = 45 ;
p -> link = q ; q -> link = r ; r -> link = s ; s -> link = NULL ;

..Cont p q r ss

int main( ) 55 63 28 45 N
{
...
...
... t t t
...
cout << p -> data << endl << q -> data << endl ;
cout << r -> data << endl << s -> data << endl ;
cout << p -> link -> data << endl ;
cout << p -> link -> link -> data << endl ;
t=p;
while ( t != NULL )
{
cout << t -> data << endl ; t = t -> link ;
}
}

# include <iostream>
using namespace std ;
Most General
struct node
{
int per ; node *link ;
};
void add ( node **q, int pp ) ;
int main( )
{
node *p ; char ch = ’Y’ ; int pp, m1, m2, m3 ;
p = NULL ;
while ( ch == ’Y’ )
{
cin >> m1 >> m2 >> m3 ;
pp = ( m1 + m2 + m3 ) / 3 ;
add ( &p, pp ) ;
cout << "Another student Y/N" ;
cin >> ch ;
}
}

2
void add ( node **q, int pp )
{
node *r ; node *t ;
r = new node ;
r -> per = pp ; r -> link = NULL ;
if ( *q == NULL ) Empty linked list
*q = r ; r
else
{ 45 N
t = *q ;
while ( t -> link != NULL ) *q
t = t -> link ;
t -> link = r ;
} Non-empty linked list
} *q r

45 16 25 N
 90 N

t t t

Variety...
55 63 28 45 60 N

1.1 0.3 1.7 3.5 2.9 N

Anil 24 Sunil 21 Anuj 22 N

struct node
{
char name[ 20 ] ;
int age ;
node *link ;
};

# include <iostream>
using namespace std ;
LL Of Records
struct node
{
char name [ 20 ] ; int age ; node *link ;
};
void add ( struct node **q, struct node n ) ;
int main( )
{
node *p ;
node t ; char ch = ’Y’ ;
p = NULL ;
while ( ch == ’Y’ )
{
cout << "\nEnter name & age: " ;
cin >> t.name >> t.age ;
add ( &p, t ) ;
cout << "Another student Y/N" ;
cin >> ch ;
}
} Contd...

3
void add ( node **q, node n )
{
node *r ; node *t ;
r = new node ;
*r = n ; r -> link = NULL ;
if ( *q == NULL )
Empty linked list
*q = r ;
else r
{
t = *q ; Anil 24 N
while ( t -> link != NULL )
t = t -> link ; *q
t -> link = r ;
} Non-empty linked list
}
*q r

Anil 24 Sunil 21 N
 Anuj 22 N

t t

4
Operations on
Linked List
Yashavant Kanetkar
kanetkar@ksetindia.com

Objectives
♦ How to append a new node to a link list
♦ How to add a new node at the beginning of a LL
♦ How to insert a new node in a linked list
♦ How to delete a node from a linked list
♦ How to delete all nodes in the list

LL Operations
# include <iostream> l.insert ( 7, 0 ) ;
using namespace std ; l.insert ( 2, 1 ) ;
l.insert ( 5, 99 ) ;
int main( )
{ l.display( ) ;
linkedlist l ; c = l.count( ) ;
cout << c ;
int c ;
l.del ( 30 ) ;
l.append ( 14 ) ; l.del ( 10 ) ;
l.append ( 30 ) ; l.display( ) ;
l.append ( 25 ) ; c = l.count( ) ;
l.append ( 17 ) ; cout << c ;
l.display( ) ;
l.deleteall( ) ;
l.addatbeg ( 7 ) ; }
l.addatbeg ( 58 ) ;
l.display( ) ;

1
class linkedlist linkedlist Class
{
private :
struct node
{
int data ; node *link ;
} *p ;
public :
linkedlist( ) ;
~linkedlist( ) ;
void append ( int num ) ;
void addatbeg ( int num ) ;
void insert ( int loc, int num ) ;
void display( ) ;
int count( ) ;
void del ( int num ) ;
void deleteall( ) ;
};

Ctor & Dtor


linkedlist :: linkedlist( )
{
p = NULL ;
}

linkedlist :: ~linkedlist( )
{
deleteall( ) ;
}

void linkedlist :: append ( int num )


{
Append
node *r , *t ;
r = new node ;
r -> data = num ;
r -> link = NULL ; Empty List
if ( p == NULL ) p r
p=r;
else
{ 14 N
t=p;
while ( t -> link != NULL )
t = t -> link ;
t -> link = r ; Non-Empty List
}
p t t r
}

14 30 25 N 17 N

2
Add At Beginning
void linkedlist :: addatbeg ( int num )
{
node *t ;
t = new node ;
t -> data = num ;
t -> link = p ;
p=t;
}

t p p

7 14 30 25 N
New node

Insert Node
void linkedlist :: insert ( int pos, int num )
{
node *t , *r ;
int i ; p t t
t=p;
for ( i = 0 ; i < pos ; i++ ) 14 30 25 N
{
if ( t -> link == NULL )
break ; 2
t = t -> link ; r
}
r = new node ;
r -> data = num ;
r -> link = t -> link ;
t -> link = r ;
}

Display And Count


q q

14 30 25 N

void linkedlist :: display( ) int linkedlist :: count( )


{ {
node *q = p ; node *q = p ;
while ( q != NULL ) int c = 0 ;
{ while ( q != NULL )
cout << q->data << endl ; {
q = q -> link ; q = q -> link ;
}
c++ ;
} }
return c ;
}

3
void linkedlist :: del ( int num )
{ Node to be Deleted = 14
node *t , *prev ;
p t p
t=p;


while ( t != NULL )
{ 14 30 2 N
if ( t -> data == n )
{
if ( t == p )
p = t -> link ;
else
prev -> link = t -> link ; Node to be Deleted = 2
delete t ; p t t prev t
return ;


}
prev = t ; 14 30 2 25 N
t = t -> link ;
} prev
cout << "\nEle. not found." ;
}

Delete All Nodes


p t p

14 30 2 N

void linkedlist :: deleteall( )


{
node *t ;
while ( p != NULL )
{
t=p;
p = p -> link ;
delete t ;
}
}

4
Ascending Order
Linked List
Yashavant Kanetkar
kanetkar@ksetindia.com

Objectives

Ω How to create an ascending order linked list


Ω How to sort elements in the linked list

Ascending Order LL
# include <iostream>
using namespace std ;
int main( )
{
sortedll l ;
int c ;
l.add ( 5 ) ;
l.add ( 1 ) ;
l.add ( 6 ) ;
l.add ( 4 ) ;
l.add ( 7 ) ;
l.display( ) ;
c = count ( p ) ;
cout << "No. of elements =" << c ;
}

1
Sorted Linked List Class
class sortedll
{
private :
struct node
{
int data ; node *link ;
} *p ;

public :
sortedll( ) ;
~sortedll( ) ;
void add ( int num ) ;
void display( ) ;
int count( ) ;
};

Ctor And Dtor


sortedll :: sortedll( )
{
p = NULL ;
}

sortedll :: ~sortedll( )
p t p
{
node *t ;
while ( p != NULL )
{
1 5 6 N

t = p -> link ;
delete p ;
p=t ;
}
}

add( ) Function
void sortedll :: add ( int n )
{
node *r , *t ;
t=p;
r = new node ;
r -> data = n ;
Empty LL
if ( p == NULL || p -> data > n )
{ p r
p=r;
p -> link = t ;
5 N
}
Addition At Beginning New node
p r p t

2 4 5 6 N
Cont… New node

2
Cont… p t t

2 4 6 N
else
{ 5
while ( t != NULL )
{ r
if ( ( t -> data <= n && t -> link == NULL ) ||
( t -> data <= n && t -> link -> data > n ) )
{
r -> link = t -> link ; t -> link = r ;
return ;
}
t = t -> link ;
} pt r
t
}
}
2 4 5 N 6 N

Sorting
# include <iostream>
using namespace std ;
int main( )
{
linkedlist l ;
l.append (17 ) ;
l.append ( 6 ) ;
l.append ( 13 ) ;
l.append ( 12 ) ;
l.append ( 2 ) ;
l.display( ) ;
l.selectionsort( ) ;
l.display( ) ;
}

Sorted Linked List Class


class linkedlist
{
private :
struct node
{
int data ; node *link ;
} *p ;

public :
linkedlist( ) ;
~linkedlist( ) ;
void append ( int num ) ;
void display( ) ;
void selectionsort( ) ;
int count( ) ;
};

3
Ctor And Dtor
linkedlist :: linkedlist( )
{
p = NULL ;
}

linkedlist :: ~linkedlist( )
{
node *q ;
while ( p != NULL )
{
q = p -> link ;
delete p ;
p=q ;
}
}

void linkedlist :: selectionsort( )


{
node *a , *b ;
int n, i, j, t ;
a = p ; n = count( ) ;
for ( i = 0 ; i < n - 1 ; i++ )
{
b = a -> link ;
for ( j = i + 1 ; j < n ; j++ )
{
if ( a -> data > b -> data )
{
t = a -> data ; a -> data = b -> data ; b -> data = t ;
}
b = b -> link ;
}
a = a -> link ; p a a b b
}
}
17 6 13 12 2 N

4
Reversing & Merging
Linked Lists
Yashavant Kanetkar
kanetkar@ksetindia.com

Objectives

Ω Perform advanced operations on linked lists


Ω How to reverse a linked list
Ω How to merge two linked lists

Reversing LL

7 43 3 23 5 N

t prev r p

7 N 43 3 23 5

1
Program
# include <iostream>
using namespace std ;
int main( )
{
linkedlist l ;
l.append ( 7 ) ;
l.append ( 43 ) ;
l.append ( 3 ) ;
l.append ( 23 ) ;
l.append ( 5 ) ;
l.display( ) ;
l.reverse( ) ;
l.display( ) ;
}

Linked List Class


class linkedlist
{
private :
struct node
{
int data ; node *link ;
} *p ;

public :
linkedlist( ) ;
~linkedlist( ) ;
void append ( int num ) ;
void reverse( ) ;
void display( ) ;
};

Ctor And Dtor


linkedlist :: linkedlist( )
{
p = NULL ;
}

linkedlist :: ~linkedlist( )
{
node *q ;
while ( p != NULL )
{
q = p -> link ;
delete p ;
p=q ;
}
}

2
void linkedlist :: reverse( )
{
node *r , *prev, *t ;
r = p ; prev = NULL ;
while ( r != NULL )
{
t = prev ;
prev = r ;
r = r -> link ;
prev -> link = t ;
}
p = prev ;
}
t r prev t r prev t r prev t r prev r prev

7 N 43 3 23 5 N
p p

Merging LL
f

9 12 14 17 79 N
s

12 17 24 64 87 N

9 12 14 17 24

64 79 87 N

Program
# include <iostream> s.add ( 12 ) ;
using namespace std ; s.add ( 17 ) ;
int main( ) s.add ( 24 ) ;
{ s.add ( 64 ) ;
sortedll f, s, t ; s.add ( 87 ) ;
f.add ( 9 ) ; cout << "\nSecond LL: " ;
f.add ( 12 ) ; s.display( ) ;
f.add ( 14 ) ;
t.merge ( f, s ) ;
f.add ( 17 ) ;
f.add ( 79 ) ; cout << "\nMerged LL: " ;
t.display( ) ;
cout << "First LL: " ; }
f.display( ) ;

3
Sorted Linked List Class
class sortedll
{
private :
struct node
{
int data ; node *link ;
} *p ;

public :
sortedll( ) ;
~sortedll( ) ;
void add ( int num ) ;
void display( ) ;
void merge ( sortedll& l1, sortedll& l2 ) ;
};

Ctor And Dtor


sortedll :: sortedll( )
{
p = NULL ;
}

sortedll :: ~sortedll( )
{
node *q ;
while ( p != NULL )
{
q = p -> link ;
delete p ;
p=q ;
}
}

void sortedll :: merge ( sortedll& l1, sortedll& l2 )


{
node *z ; Empty List
node *l1p = l1.p ;
p z
node *l2p = l2.p ;
if ( l1p == NULL && l2p == NULL )
return ;
while ( l1p != NULL && l2p != NULL )
{
if ( this -> p == NULL )
z = this -> p = new node ;
else
{ Non-Empty List
z -> link = new node ;
z = z -> link ; pz z
}
14

4
if ( l1p -> data < l2p -> data )
First List
{
z -> data = l1p -> data ; l1p l1p l1p
l1p = l1p -> link ;
}
else 9 12 14 N
{
if ( l1p->data == l2p -> data )
Second List
{
z -> data = l2p -> data ; l2p l2p
l1p = l1p -> link ;
l2p = l2p -> link ;
} 12 17 24 N
else
{
if ( l2p->data < l1p->data ) Third List
{ z z z
z -> data = l2p -> data ;
l2p = l2p -> link ;
} 9 12 14
} } }// while

while ( l1p != NULL ) Third List


{
z -> link = new node ; z
z = z -> link ;
z -> data = l1p -> data ; 64 79 87 N
l1p = l1p -> link ;
}
while ( l2p != NULL )
{
z -> link = new node ;
z = z -> link ;
z -> data = l2p -> data ;
l2p = l2p -> link ;
}
z -> link = NULL ;
} // merge( )

5
Linked List
& Polynomials
Yashavant Kanetkar
kanetkar@ksetindia.com

Objectives

♦ How to concatenate two linked lists


♦ How to represent a polynomial using a LL
♦ How to perform polynomial addition using LL

Concatenation Of LL
#include <iostream> s.add ( 7 ) ;
using namespace std ; a.add ( 13 ) ;
int main( ) s.add ( 2 ) ;
{ s.add ( 84 ) ;
sortedll f, s ; cout << "\nSecond LL: " ;
f.add ( 1 ) ; s.display( ) ;
f.add ( 41 ) ; f.concat ( s ) ;
f.add ( 3 ) ;
f.add ( 9 ) ; cout << "\nConcatenated LL: " ;
f.display( ) ;
cout << "\nFirst LL: " ; }
f.display( ) ;

1
sortedll Class
class sortedll
{
private :
struct node
{
int data ;
node *link ;
} *p ;

public :
sortedll( ) ;
~sortedll( ) ;
void add ( int num ) ;
void display( ) ;
void concat ( sortedll& l2 ) ;
};

Ctor And Dtor


sortedll :: sortedll( )
{
p = NULL ;
}

sortedll :: ~sortedll( )
{
node *q ;
while ( p != NULL )
{
q = p -> link ;
delete p ;
p=q;
}
}

void sortedll :: concat ( sortedll& l2 )


{ t = l2.p -> link ;
node *t , *n ;
while ( t != NULL )
if ( l2.p == NULL )
{
return ;
t=p; n -> link = new node ;
while ( t -> link != NULL ) n = n -> link ;
t = t -> link ; *n = * t ;
n -> link = NULL ;
n = new node ;
t = t -> link ;
*n = *l2.p ;
}
n -> link = NULL ;
}
t -> link = n ;
First List Second List
p t t p

9 12 14 N 12 17 24 N

2
Polynomial Addition
# include <iostream> poly p2, p3 ;
using namespace std ; p2.append ( 1.5, 6 ) ;
int main( ) p2.append ( 2.5, 5 ) ;
{ p2.append ( -3.5, 4 ) ;
poly p1 ; p2.append ( 4.5, 3 ) ;
p1.append ( 1.4, 5 ) ; p2.append ( 6.5, 1 ) ;
p1.append ( 1.5, 4 ) ; p2.display( ) ;
p1.append ( 1.7, 2 ) ; p3.add ( p1, p2 ) ;
p1.append ( 1.8, 1 ) ; p3.display( ) ;
p1.append ( 1.9, 0 ) ; }

p1.display( ) ;

1.4 X5 + 1.5 X4 + 1.7 X2 + 1.8 X1 + 1.9 X0

1.5 X6 + 2.5 X5 – 3.5 X4 + 4.5 X3 + 6.5 X1

poly Class
class poly
{
private :
struct polynode
{
float coeff ;
int exp ;
polynode *link ;
} *p ;
public :
poly( ) ;
~poly( ) ;
void append ( float c, int e ) ;
void display( ) ;
void addition ( poly &l1, poly &l2 ) ;
};

Ctor And Dtor


poly :: poly( )
{
p = NULL ;
}

poly :: ~poly( )
{
polynode *q ;

while ( p != NULL )
{
q = p -> link ;
delete p ;
p=q;
}
}

3
Append
void poly :: append ( float c, int e )
{
polynode *t = p ;
if ( t == NULL )
{
t = new polynode ;
p=t;
}
else
{
while ( t -> link != NULL )
t = t -> link ;
t -> link = new polynode ;
t = t -> link ;
}
t -> coeff = c ;
t -> exp = e ;
t -> link = NULL ;
}

Display
void poly :: display( ) if ( t -> exp != 0 )
{ cout << t -> coeff
polynode *t = p ; << "x^" << t -> exp ;
int f = 0 ; else
while ( t != NULL ) cout << t -> coeff ;
{ t = t -> link ;
if ( f != 0 ) f=1;
{ }
if ( t -> coeff > 0 ) }
cout << " + " ;
else
cout << " " ;
}

Addition
void poly :: addition ( poly &l1, poly &l2 )
{
polynode *z ;
polynode *l1p, *l2p ;
l1p = l1.p ;
l2p = l2.p ;

if ( l1.p == NULL && l2.p == NULL )


return ;

while ( l1p != NULL && l2p != NULL )


{
if ( p == NULL )
z = p = new polynode ;
else
{
z -> link = new polynode ;
z = z -> link ;
}

4
if ( l1p -> exp < l2p -> exp )
{
z -> coeff = l2p -> coeff ; z -> exp = l2p -> exp ;
l2p = l2p -> link ;
}
else
{
if ( l1p -> exp > l2p -> exp )
{
z -> coeff = l1p -> coeff ; z -> exp = l1p -> exp ;
l1p = l1p -> link ;
}
else
{
if ( l1p -> exp == l2p -> exp )
{
z -> coeff = l1p -> coeff + l2p -> coeff ;
z -> exp = l1p -> exp ;
l1p = l1p -> link ; l2p = l2p -> link ;
}
}}}

...Contd. while ( l2p != NULL )


{
while ( l1p != NULL ) if ( p == NULL )
{ {
if ( p == NULL ) p = new polynode ;
{ z=p;
p = new polynode ; }
z=p; else
} {
else z -> link = new polynode ;
{ z = z -> link ;
z -> link = new polynode ; }
z = z -> link ; z -> coeff = l2p -> coeff ;
} z -> exp = l2p -> exp ;
z -> coeff = l1p -> coeff ; l2p = l2p -> link ;
z -> exp = l1p -> exp ; }
l1p = l1p -> link ; z -> link = NULL ;
} }

5
Circular
Linked List
Yashavant Kanetkar
kanetkar@ksetindia.com

Objectives

Ω What are circular linked lists


Ω How to add a new node to a circular list
Ω How to delete an existing node from a circular list
Ω How to count the nodes of the circular linked list
Ω How to display the nodes in the circular linked list

Circular Linked List


p

12 17 24 64 87

1
CLL Operations
# include <iostream> l.insert ( 2, 99 ) ;
using namespace std ; l.insert ( 66, 88 ) ;
int main( ) l.display( ) ;
{ l.del ( 15 ) ;
cll l ; l.del ( 10 ) ;
int c ; l.del ( 88 ) ;
l.append ( 10 ) ; l.display( ) ;
l.append ( 18 ) ; c = l.count( ) ;
cout << "No. of ele. << c ;
l.addatbeg ( 5 ) ; }
l.addatbeg ( 15 ) ;

class cll cll Class


{
private :
struct node
{
int data ; node *link ;
} *p ;
public :
cll( ) ;
~cll( ) ;
void append ( int n ) ;
void addatbeg ( int n ) ;
void insert ( int pos, int n ) ;
void display( ) ;
int count( ) ;
void del ( int num ) ;
void deleteall ( ) ;
};

Ctor And Dtor


cll :: cll( )
{
p = NULL ;
}

cll :: ~cll( )
{
deleteall ( ) ;
}

2
void cll :: append ( int n )
{
Append
node *r , *t ;
r = new node ; Empty List
r -> data = n ; p r
if ( p == NULL )
p=r;
17
else
{
t=p;
while ( t -> link != p )
t = t -> link ;
t -> link = r ; Non-Empty List
} pt t t r
r -> link = p ;
}
12 17 24 64

void cll :: addatbeg ( int n )


{
Prepend
node *r , *t ;
r = new node ;
r -> data = n ; Empty List
if ( p == NULL ) p r
r -> link = r ;
else
{ 17
t=p;
while ( t -> link != p )
t = t -> link ;
t -> link = r ; r -> link = p ; Non-Empty List
}
pr pt t t
p=r;
}
64 12 17 24

Insert
void cll :: insert ( int pos, int n )
{
node *t ;
int i ;
t=p;
for ( i = 0 ; i < pos ; i++ )
{
if ( t -> link == p )
break ;
t = t -> link ;
}
p t t

64 12 17 24

Cont…

3
Cont… r = new node ;
r -> data = n ;
r -> link = t -> link ;
t -> link = r ;
}
r
p t 2

64 12 17 24

p t r

12 17 24 88

Delete Node
void cll :: del ( int n ) Node to be Deleted = 64
{
node *t, *prev, *r ; pt r pr r


t=p;
do
64 12 17
{
if ( t -> data == n )
{
if ( t == p )
{
r=p;
while ( r -> link != p )
r = r -> link ;
p = r -> link = t -> link ;
delete t ;
} Cont…

Cont… else // if t == p
{
prev -> link = t -> link ;
delete t ;
}
return ;
} // if t -> data == n
prev = t ;
t = t -> link ;
} while ( t != p )
cout << "Element Not Found." ;
} // del
Node to be Deleted = 17
p t t prev t

prev
64 12

17 24

4
Delete All Nodes
void cll :: deleteall( ) t=p;
{ while ( t -> link != p )
node *t , *last , *temp ; {
if ( p == NULL ) temp = t ;
return ; t = t -> link ;
t=p; last -> link = p = t ;
while ( t -> link != p ) delete temp ;
}
t = t -> link ;
last = t ; delete p ;
p = NULL ;
}
p t temp p t temp p t temp p t last

   
64 12 17 24

Display And Count


p t t

64 12 17 24

void cll :: display( ) int cll :: count( )


{ {
node *t ; node *t = p ;
if ( p == NULL ) int c = 0 ;
return ; do
t=p; {
do t = t -> link ;
{ c++ ;
cout << t -> data << " " ; } while ( t != p ) ;
t = t -> link ; return c ;
} while ( t != p ) ; }
}

5
Doubly Linked List
Yashavant Kanetkar
kanetkar@ksetindia.com

Objectives
Ω What are Doubly Linked Lists
Ω How are they different than Singly Linked Lists
Ω How to perform different operations on a Doubly Linked List

Doubly Linked List

11 2 14 17 N

N 11 2 14 17 N

struct dnode
{
dnode *prev ;
int data ;
dnode *next ;
}

1
DLL Operations
# include <iostream> l.insert ( 4, 66 ) ;
using namespace std ; l.insert ( 2, 96 ) ;
int main( ) l.display( ) ;
{ c = l.count( ) ;
int c ; cout << "count = " << c ;
dlinkedlist l ;
l.append ( 11 ) ; l.del ( 55 ) ;
l.append ( 2 ) ; l.del ( 2 ) ;
l.append ( 14 ) ; l.del ( 99 ) ;
l.append ( 17 ) ; l.display( ) ;
l.append ( 99 ) ; c = l.count( ) ;
l.display( ) ; cout << "count = " << c ;
l.addatbeg ( 33 ) ; return 0 ;
l.addatbeg ( 55 ) ; }
l.display( ) ;

dlinkedlist Class
class dlinkedlist
{
private :
struct dnode
{
dnode *prev ; int data ; dnode * next ;
} *p ;
public :
dlinkedlist( ) ;
~dlinkedlist( ) ;
void append ( int n ) ;
void addatbeg ( int n ) ;
void insert ( int pos, int n ) ;
void display( ) ;
int count( ) ;
void del ( int i ) ;
};

Ctor And Dtor


dlinkedlist :: dlinkedlist( )
{
p = NULL ;
}

dlinkedlist :: ~dlinkedlist( )
{
dnode *t = p ;
while ( p != NULL )
{
t = p -> next ;
delete p ;
p=t;
}
}

2
void dlinkedlist :: append ( int n )
{ Append
dnode *r , *t ;
r = new dnode ;
r -> data = n ; r -> next = NULL ;
if ( p == NULL ) Empty List
{ pr
r -> prev = NULL ; p = r ;
}
else N 11 N
{
t=p;
while ( t -> next != NULL )
t = t -> next ; Non-Empty List
r -> prev = t ; pt t r
t -> next = r ;
}
} N 2 14 N 11 N

Prepend
void dlinkedlist :: addatbeg ( int n )
{
dnode *t ;
t = new dnode ;
t -> prev = NULL ;
t -> data = n ;
t -> next = p ;
p -> prev = t ;
p=t;
}

p t p

N 11 N 2 14 17 N

void dlinkedlist :: insert ( int pos, int n )


{ Insert
int i ;
dnode *r, *q ;
q=p;
for ( i = 0 ; i < pos ; i++ )
{ q q
if ( q -> next == NULL )
break ; N 2 14 17 N
q = q -> next ;
}
11
r = new dnode ;
r -> data = n ; r
r -> prev = q ; r -> next = q -> next ;
if ( q -> next != NULL )
q -> next -> prev = r ;
q -> next = r ; What if q points to
} last node

3
void dlinkedlist :: del ( int n )
{
Delete
dnode *t ;
t=p;
while ( t != NULL )
{
if ( t -> data == n )
{
if ( t == p )
{
p = p -> next ;
p -> prev = NULL ;
} Node to be Deleted = 2
p t p

N 2 N 14 11 N
Cont…

Cont… else
{
t -> prev -> next = t -> next ;
if ( t -> next != NULL )
t -> next -> prev = t -> prev ;
} Node to be Deleted = 2
delete t ;
return ; t p
} // if
t = t -> next ;
} // while

N 2 N 14 11 N

printf ( "\nNo. not found." ) ;


} // d_delete Node to be Deleted = 11
p t

N 2 14

11 17 N

4
Stack
Asang Dani
asang@ksetindia.com

Objectives
Stack and its utilities
Stack as an Array
Push and Pop operations
Displaying stack elements

Stack

Top 20
Top 10 10
Top
Empty Push 10 Push 20

Top 20
10 Top 10
Top
Pop Pop Empty

1
Utility
· Store local variables in a function
· Manage function calls
· Conversion of Expressions
· Evaluation of Expressions
· Caching
push 510 display( )
{
int main( ) // code
{ }
505 display( ) ; pop 510
515
510 510 show( ) ; push 515 show( )
515 puts( ) ;
} {
// code
pop 515 }

#include <iostream>
Program
using namespace std ;
public :
const int MAX = 10 ; stack ( ) ;
void push ( int item ) ;
class stack int pop( ) ;
{ void display ( ) ;
private : int count ( ) ;
int arr [ MAX ] ; };
int top ;

int main ( ) Operations of Stack


{
stack s ;
s.push ( 11 ) ;
s.push ( 23 ) ;
s.push ( -8 ) ;
s.push ( 16 ) ;
s.push ( 7 ) ;
cout << "\n\nItem popped: " << s.pop ( ) ;
top 7
cout << "\nNo. of items : " << s.count ( ) ; top 16
cout << endl ; top -8
top 23
s.display ( ) ; top 11
} top = -1

2
stack :: stack( ) Implementation
{
int stack :: pop( )
top = -1 ;
{
}
if ( top == -1 )
{
void stack :: push ( int item )
cout << "Stack is empty" ;
{
return -1 ;
if ( top == MAX - 1 )
}
{
int data = arr[ top ] ;
cout << "Stack is full" ;
top -- ;
return ;
return data ;
}
}
top ++ ;
arr[ top ] = item ;
}

Implementation (2)
void stack :: display ( )
{
for ( int i = 0 ; i <= top ; i ++ )
cout << arr [ i ] << "\t" ;
cout << endl ;
}

int stack :: count ( )


{
return top + 1 ;
}

3
Stack as a Linked List
Asang Dani
asang@ksetindia.com

Objectives
Why Arrays are not enough
Advantages of linked lists
Stack as a Linked List
Operations on Stack

Stack As A Linked List


node data link

Push Pop

top 55 top 55

top 63 top 63

top 28 top 28

top 45 N top 45 N

1
Program
s.display ( ) ;
#include <iostream> t = s.count ( ) ;
cout << "Total items: " << t ;
using namespace std ;
item = s.pop ( ) ;
int main( ) cout << "\n\nItem: " << item ;
{
stack s ; s.display ( ) ;
int t, item ; t = s.count ( ) ;
cout << "Total items: " << t ;
s.push ( 45 ) ; }
s.push ( 28 ) ;
s.push ( 63 ) ;
s.push ( 55 ) ;

stack class
public :
class stack stack( ) ;
{ void push ( int item ) ;
private : int pop( ) ;
struct node void display ( ) ;
{ int count ( ) ;
int data ; ~stack( ) ;
node *link ; };
} * top ; stack :: stack( )
{
top = NULL ;
}

Push Operation
void stack :: push ( int item )
{
node *q ;
q = new node ;
q -> data = item ;
q -> link = top ; Stack
top = q ;
} top
q 28

45 N top
q

2
Pop Operation
int stack :: pop ( ) Pop


{
node *q ; int item ; 63 top
q
if ( top == NULL )


{
cout << "Stack is empty" ; 28 top
q
return -1 ;


}
45 N top
q = top ; q
item = q -> data ; top = N
top = q -> link ;
delete q ;
return ( item ) ;
}

void stack :: display ( ) Display And Count


{
node * q = top ;
while ( q != NULL )
{
cout << q -> data << "\t" ;
q = q -> link ; stack :: ~stack( )
}
{
}
node *q ;
int stack :: count ( )
while ( top != NULL )
{
node * q = top ; int c = 0 ; {
while ( q != NULL ) q = top ;
{
top = top -> link ;
q = q -> link ;
c++ ; delete q ;
} }
return c ;
}
}

3
Stack Expressions
Yashavant Kanetkar

Objectives
·Expressions of different forms

Expressions

A $ B * C - D +E /F / ( G + H ) Infix

AB$C*D-EF/GH+/+ Postfix

+-*$ABCD//EF+GH Prefix

1
Scan from L to R. Repeat step 1- 4 In To Post
Token Operation
operand Add to expression
( Push to stack
operator Pop oper. If P(Popped) >= P(Scanned) add to expr.
Push scanned operator to stack
) Pop till ( . Add popped token to expr. Delete )
Pop stack elements if any and add to expression
A+ ( B * C - (D / E $F ) * G ) *H
Tok. Stack Expression Tok. Stack Expression
A Empty A - +(- ABC*
+ + A ( +(-( ABC*
( +( A D +(-( ABC*D
B +( AB / +(-(/ ABC*D
* +(* AB E +(-(/ ABC*DE
C +(* ABC $ +(-(/$ ABC*DE

...Contd.

A+ ( B * C - (D / E $F ) * G ) *H

Tok. Stack Expression


$ +(-(/$ ABC*DE
F +(-(/$ ABC*DEF
) +(- ABC*DEF$/
* +(-* ABC*DEF$/
G +(-* ABC*DEF$/G
) + ABC* D EF$/G*-
* +* ABC*DEF$/G*-
H +* ABC*DEF$/G*-H
ABC*DEF$/G*-H*+

In To Post
A$ B * C - D + E /F / ( G + H )

Tok. Stack Expression Tok. Stack Expression


A Empty A / +/ AB$C*D-E
$ $ A F +/ AB$C*D-EF
B $ AB / +/ AB$C*D-EF/
* * AB$ ( +/( AB$C*D-EF/
C * AB$C G +/( AB$C*D-EF/G
- - AB$C* + +/(+ AB$C*D-EF/G
D - AB$C*D H +/(+ AB$C*D-EF/GH
+ + AB$C*D- ) +/ AB$C*D-EF/GH+
E + AB$C*D-E AB$C*D-EF/GH+/+

2
Infix to Postfix using
stack
Asang Dani
asang@ksetindia.com

Objectives

♦ Infix to Postfix Conversion


♦ Program for Infix to Postfix conversion
♦ Helper Functions
♦ Push( ) and Pop( ) functions

#include <iostream>
#include <cctype> Program
using namespace std ;

int main ( )
{ Infix
char expr [ MAX ] ; A $ B * C - D +E /F / ( G + H )
infix q ;
cout << "\nEnter an expression in infix form: " ;
cin.getline ( expr, MAX ) ;

q.setexpr ( expr ) ; Postfix


q.convert ( ) ; AB$C*D-EF/GH+/+

cout << "\nThe postfix expression is: " ;


q.show( ) ;
}

1
class infix
{
class infix
private :
char target [ MAX ] , stack [ MAX ] ;
char *s, *t ;
int top ;

public :

infix ( ) ;
void setexpr ( char *str ) ;
void push ( char c ) ;
char pop ( ) ;
void convert ( ) ;
int priority ( char c ) ;
bool isoperator ( char ch ) ;
void show( ) ;
};

constructor etc..
infix :: infix( )
{
top = -1 ;
strcpy ( target , "" ) ;
strcpy ( stack , "" ) ;
t = target ;
s = "" ;
}

void infix :: setexpr ( char *str )


{
s = str ;
}

void infix :: convert ( )


{
while ( *s != ‘\0’ )
{
if ( *s == ' ' || *s == '\t' ) {
s++;
continue ;
}
if ( isdigit ( *s ) || isalpha ( *s ) )
{
while ( isdigit ( *s ) || isalpha ( *s ) )
{
*t = *s ; Infix
s++; t++; A $ B * C - D +E /F / ( G + H )
}
} Postfix
if ( *s == '(' ) {
push ( *s ) ; AB$C*D-EF/GH+/+
s++;
} Contd...

2
...Contd. char opr ; Infix
if ( isoperator ( *s ) ) A $ B * C - D + E / F / ( G + H )
{
if ( top != -1 ) F +/ AB$C*D-EF
{ / +/ AB$C*D-EF/
opr = pop ( ) ;
while ( priority ( opr ) >= priority ( *s ) )
{
*t = opr ; t + + ;
opr = pop ( ) ;
if ( top == -1 )
break ;
}
if ( opr != -1 )
push ( opr ) ;
}
push ( *s ) ;
s++;
}
Contd...

...Contd. if ( *s == ')' )
H +/(+AB$C*D-EF/GH
{
) +/ AB$C*D-EF/GH+
opr = pop ( ) ;
while ( opr != '(' )
{
*t = opr ; t + + ;
opr = pop ( ) ;
}
s++;
} ) +/ AB$C*D-EF/GH+
} // while AB$C*D-EF/GH+/+
while ( top != -1 )
{
opr = pop ( ) ;
*t = opr ; pt + + ;
}
*t = '\0' ;
} // convert

Helper Functions
int infix :: priority ( char c ) int infix ::
{ isoperator ( char ch )
if ( c == '$' ) {
return 3 ; char str[ ] = "*+/%-$" ;
if ( c == '*' || c == '/' || c == '%' ) char *p ;
return 2 ; p = str ;
if ( c == '+' || c == '-' ) while ( *p != ‘\0’ )
return 1 ; {
return 0 ; if ( *p == ch )
} return 1 ;
p++ ;
}
return 0 ;
}

3
push( ) and pop( )
void infix :: push ( char c ) char infix :: pop ( )
{ {
if ( top == MAX - 1 ) char item ;
{ if ( top == -1 )
cout << "Stk. full." ; {
return ; cout << "Stk. empty" ;
} return -1 ;
top++ ; }
stack [ top ] = c ; item = stack [ top ] ;
} top-- ;
return item ;
}

4
Postfix Evaluation
Asang Dani
asang@ksetindia.com

Objectives
♦ Evaluation of Postfix form
♦ Example of evaluation of Postfix form
♦ Program for evaluation of Postfix form

Evaluate Postfix
Scan from L to R. Repeat step 1- 2
Token Operation
operand Add to stack
operator Pop stack into n1
Pop stack into n2
Perform n3 = n2 operator n1
Push n3
Pop stack to obtain result

1
An Example 4 2 $ 3*3 -8 4 / 1 1 + / +
Token Stack
4 4
2 4, 2
$ 16
3 16, 3
* 48
3 48, 3
- 45
8 45, 8
4 45, 8, 4
/ 45, 2
1 45, 2, 1
1 45, 2, 1, 1
+ 45, 2, 2
/ 45, 1
+ 46

#include <iostream> Program


#include <cstdlib>
#include <cmath>
#include <cctype>
using namespace std ;

int main( )
{
char expr [ MAX ] ;
cout << "\nEnter postfix expr. to be evaluated : " ;
cin.getline ( expr, MAX ) ;

postfix q ;

q.setexpr ( expr ) ;
q.calculate ( ) ;
q.show ( ) ;
}

const int MAX = 50 ; postfix class


class postfix int pop( ) ;
{ void calculate( ) ;
private : void show( ) ;
int stack [ MAX ] ; };
int top, nn ; postfix :: postfix( )
char *s ; {
top = -1 ;
public : }
void
postfix ( ) ; postfix :: setexpr ( char *str )
void setexpr ( char *str ) ; {
void push ( int item ) ; s = str ;
}

2
void postfix :: calculate( ) Evaluate Postfix
{
int n1, n2, n3 ; else
while ( *s ) {
{ n1 = pop( ) ;
if ( *s == ' ' || *s == '\t' ) { n2 = pop( ) ;
s++ ; switch ( *s )
continue ; {
} case '+' :
if ( isdigit ( *s ) ) n3 = n2 + n1 ;
{ break ;
nn = *s - '0' ; case '-' :
push ( nn ) ; n3 = n2 - n1 ;
} break ;

case '/' :
n3 = n2 / n1 ;
Evaluate Postfix
break ;
case '*' : push ( n3 ) ;
n3 = n2 * n1 ; } // else
break ; s++ ;
case '%' : } // while
n3 = n2 % n1 ; }
break ;
case '$' :
n3 = ( int )pow ( ( double ) n2 , ( double ) n1 ) ;
break ;
default :
cout << "Unknown operator" ;
exit ( 1 ) ;
} // switch

push( ) and pop( )


void postfix :: push ( char c ) char postfix:: pop ( )
{ {
if ( top == MAX - 1 ) char item ;
{
if ( top == -1 )
cout << "Stk. full." ;
{
return ;
cout << "Stk. empty" ;
}
return -1 ;
top++ ; }
stack [ top ] = c ;
item = stack [ top ] ;
}
top-- ;
void postfix :: show( )
return item ;
{ }
nn = pop ( ) ;
cout << "Result is: " << nn ;
}

3
Queue
Yashavant Kanetkar
kanetkar@ksetindia.com

Objectives
X What are queues
X Where are they used
X Basic operations on Queues

Windows & Queue

WM_PAINT WM_KEYDOWN

WM_CREATE WM_MOUSEMOVE

Message queue

Retrieved Messages

WinMain( ) Message loop

Dispatched Messages
Call Appropriate Handler

1
Operations On Queue
front rear

16 - 8 23 11 7

front rear rear Addition

16 - 8 23 11 7 13

front front rear Deletion

16 - 8 23 11 7 13

Queue's Use
# include <iostream> class queue
using namespace std ; {
const int MAX = 10 ; private :
int main( ) int arr [ MAX ] ;
{ int f, r ;
queue a ; public :
a.addq ( 23 ) ; queue( ) ;
a.addq ( 9 ) ; void addq ( int item ) ;
a.addq ( 11 ) ; int delq( ) ;
a.addq ( -10 ) ; };
int i = a.delq( ) ;
cout << "\ndeleted: " << i ;
}

Ctor
// initialises data members
queue :: queue( )
{
f = -1 ;
r = -1 ;
}

2
Add
void queue :: addq ( int item )
{
if ( r == MAX - 1 )
{
cout << "\nQueue is full" ;
return ;
}
r++ ;
arr [ r ] = item ;
f r f = -1
r = -1
if ( f == -1 )
23
f=0;
}
f r

23 9 11 -10 7 13 2 - 8 22 3

int queue :: delq( )


Delete
{
int data ;

if ( f == -1 )
{
cout << "\nQueue is Empty" ;
return -1 ;
}
data = arr [ f ] ; f f r
arr [ f ] = 0 ;
if ( f == r )
23 9 11 -10 7
f = r = -1 ;
else
f++ ; f r f = -1
return data ; r = -1
} 0 0 0 0 7

3
Circular Queue
Yashavant Kanetkar
kanetkar@ksetindia.com

Objectives
X Limitations of queues
X What are Circular Queues
X Implementation of Circular Queue

Problems
f r

5 -1 34 12 53 61 9 23 - 8 42

Soln. I - Shift Elements


f r

-1 34 12 53 61 9 23 - 8 42 42

Soln. II - Circular Queue


r f r

7 -1 34 12 53 61 9 23 - 8 42

1
Using Circular Queue
# include <iostream> class cqueue
using namespace std ; {
const int MAX = 10 ; private :
int main( ) int arr[ MAX ] ;
{
int f, r ;
cqueue q ;
q.addq ( 5 ) ; public :
q.addq ( -1 ) ; cqueue( ) ;
q.addq ( 34 ) ; void addq ( int item )
q.addq ( 12 ) ; int delq( ) ;
q.addq ( 53 ) ; void display( ) ;
cout << "\nElements in Q: " ; };
q.display( ) ;
int i = q.delq( ) ;
cout << "Item deleted: " << i ;
cout << "\nAfter deletion: " ;
q.display( ) ;
}

Constructor
cqueue :: cqueue( )
{
f = r = -1 ;
for ( int i = 0 ; i < MAX ; i++ )
arr[ i ] = 0 ;
}

Add Element
void cqueue :: addq ( int item )
{
if ( ( r == MAX - 1 && f == 0 ) || ( r + 1 == f ) )
{
cout << "Queue is full." ;
return ; f r f = -1
} r = -1
if ( r == MAX - 1 ) -8
r=0;
else r f r
r ++ ;
arr[ r ] = item ; 9 42 34 12 53
if ( f == -1 )
f r
f=0;
}
9 42 34 12 53

2
int cqueue :: delq( )
{ Delete Element
int i ;
if ( f == -1 )
{
cout << "Queue is empty" ; f = -1
r = -1
return -1 ;
}
i = arr[ f ] ; arr[ f ] = 0 ;
if ( f == r ) f f r
f = r = -1 ;
else
-08 42 34 12 53
{
if ( f == MAX - 1 )
f=0; f f r f = -1 f
else r = -1
f ++ ; 9 42 0 0 53
0
}
return i ;
}

Display
void queue :: display( )
{
cout << endl ;
for ( int i = f ; i <= r ; i++ )
cout << arr[ i ] << " " ;
cout << endl ;
}

3
Deque &
Priority Queue
Yashavant Kanetkar
kanetkar@ksetindia.com

Objectives

♦ What is a Dequeue
♦ Operations on a Dequeue
♦ What is a priority queue

Deque
f r

5 -1 34 12 53 61 9 23 - 8 42

f f r r

5 -1 34 12 53 61 9 23 - 8 42

f f r r

5 -1 34 12 53 61 9 23 - 8 42

1
Program

# include <iostream> cout << "\nItem extracted: " ;


using namespace std ; cout << a.delqatbeg( ) ;
const int MAX = 10 ; cout << "\nAfter deletion: " ;
int main( ) a.display( ) ;
{
dque a ; cout << "\nItem extracted: " ;
a.addqatend ( 17 ) ; cout << a.delqatend( ) ;
a.addqatbeg ( 10 ) ; cout << "\nAfter deletion: " ;
a.addqatend ( 8 ) ; a.display( ) ;
a.addqatbeg ( -9 ) ; }
a.addqatend ( 13 ) ;
a.display( ) ;
int n = a.count( ) ;
cout << "\nCount = " << n ;

dque Class
class dque
{
private :
int arr[ MAX ] ;
int f, r ;

public :
dque( ) ;
void addqatbeg ( int item ) ;
void addqatend ( int item ) ;
int delqatbeg( ) ;
int delqatend( ) ;
void display( ) ;
int count( ) ;
};

Ctor

dque :: dque( )
{
f = r = -1 ;
for ( int i = 0 ; i < MAX ; i++ )
arr[ i ] = 0 ;
}

2
Add At End
void dque :: addqatend ( int item ) r- - ; f- - ;
{ }
if ( f == 0 && r == MAX - 1 ) r++ ;
{ arr[ r ] = item ;
cout << "Deque is full." ; }
return ;
}
if ( f == -1 )
{
r=f=0; f r r
arr[ r ] = item ;
return ; 0 17 10 8 -9
}
if ( r == MAX - 1 ) f f r
{
for ( int i = f - 1 ; i < r ; i++ )
0 17 10 8 13
-9
arr[ i ] = arr[ i + 1 ] ;

arr[ k ] = arr[ k - 1 ] ;
Add At Begin k- - ;
void dque :: addqatbeg ( int item ) }
{ arr[ k ] = item ;
if ( f == 0 && r == MAX-1 ) f = k ; r++ ;
{ }
cout << "Deque is full." ; else
return ; {
} f- - ;
if ( f == -1 ) arr[ f ] = item ;
{ }
f=r=0; }
arr[ f ] = item ;
return ; f r
}
if ( r != MAX - 1 ) -8 42 34 12 53
{
int c = count( ) ; f f r r
int k = r + 1 ;
for ( int i = 1 ; i <= c ; i++ )
{ 17
9 42
9 34
42 34
12 12
0

Delete From Front


int dque :: delqatbeg( )
{
int item ;
if ( f == -1 )
{
cout << "Deque is empty." ;
return 0 ;
} f f r
item = arr[ f ] ;
arr[ f ] = 0 ; - 08 42 34 12 53
if ( f == r )
f = r = -1 ; f r f=-1
else r=-1
f++ ;
0 42 0 0 0
return item ;
}

3
Delete From End
int dque :: delqatend( )
{
int item ;
if ( f == -1 )
{
cout << "Deque is empty" ;
return 0 ;
} f r r
item = arr[ r ] ;
arr[ r ] = 0 ; - 8 42 34 12 53
0
r-- ;
if ( r == -1 ) f r f=-1
f = -1 ; r=-1
return item ; 42 0 0 0 0
}

Count And Display

void dque :: display( ) int dque :: count( )


{ {
cout << endl << "f->"; int c = 0 ;
for ( int i = f ; i <= r ; i++ ) for ( int i = f ; i <= r ; i++ )
cout << " " << arr[ i ] ; {
cout << " <-r" ; if ( arr[ i ] != 0 )
} c++ ;
}
return c ;
}

Priority Queue
Job Priority f r f r f r
2 2
9 4 2 9 2 9 2 8
8 2
3 3
f r
6 1
1 4
7 5 9 3 2 8
4 4
0 4 f r
5 2

9 3 2 8 6

4
Trees
Asang Dani

Objectives
·Trees
·Trees terminology
·Types of Trees

Data structures
Linear Non - Linear

· Arrays · Trees
· Linked Lists · Graphs
· Stacks
· Queues
Trees
RAHUL

SANJAY SAMEER NISHA


N N N N N

ABHA AJIT MADHU NEHA


N N N N N N N N N N N N

General Trees And Forest

A T1 T2 T3
A @ 99
ST1 ST2
K Z
D $ & 45 55
D S G C ^ 35
G M N H
C
H O P ~ 0 25
H #
15

Terminology · Binary Tree - Each node


has 0, 1, 2 children

A · A - Root node
· B, D, F - Nodes of left sub-tree
B C · C, E, G, H - Nodes of right sub-tree
· F, G, H - Leaf nodes
D E
· A is Father of B & C
F G H · E is right child C
· G is right descendant of A
· F is left child of D
· F is left descendant of A
· A is ancestor of D
· G & H are siblings, D and E aren’t
More Terminology
A

B C

D E

F G H

· Degree of a node is no. of nodes connected to it

· Level of root node is 0


· Level of any other node is 1 more than level of its father
· Depth of a binary tree is maximum level of a node

Strictly And Complete


A A

B C B C

D E D E F G

F G

Strictly Binary Tree Complete Binary Tree


Each non-leaf node has 2 Strictly binary tree with all
children leaf nodes at same level
Tree Traversal
Asang Dani

Objectives
·Traversal of Trees
· Reconstruction of Trees

Traversal
A

B C

D E

F G

Pre-order Traversal - Root - Left - Right A, B, D, E, F, G, C


In-order Traversal - Left - Root - Right D, B, F, E, G, A, C
Post-order Traversal - Left - Right - Root D, F, G, E, B, C, A
Exercise
3

2 7

8 9

4 1 6

Pre-order Traversal - Root - Left - Right 3, 2, 8, 4, 7, 9, 1, 6


In-order Traversal - Left - Root - Right 2, 4, 8, 3, 7, 1, 9, 6
Post-order Traversal - Left - Right - Root 4, 8, 2, 1, 6, 9, 7, 3

Reconstruction - I In - 4, 7, 2, 8, 5, 1, 6, 9, 3
Pre - 1, 2, 4, 7, 5, 8, 3, 6, 9
1
1

In: 4, 7, 2, 8, 5 In: 6, 9, 3 2 In: 6, 9, 3


Pre: 2, 4, 7, 5, 8 Pre: 3, 6, 9 Pre: 3, 6, 9

1 In: 4, 7 In: 8, 5 1
Pre: 4, 7 Pre: 5, 8

2 3 2 3

4 5 In: 6, 9 4 5 6
Pre: 6, 9

7 8 7 8 9

Exercise In - 2, 4, 8, 3, 7, 1, 9, 6
Pre - 3, 2, 8, 4, 7, 9, 1, 6
3
3

In: 2, 4, 8 In: 7, 1, 9, 6 In: 7, 1, 9, 6


2
Pre: 2, 8, 4 Pre: 7, 9, 1, 6 Pre: 7, 9, 1, 6

In: 4, 8
3 Pre: 8, 4 3

2 7 2 7

8 In: 1, 9, 6 8 9
Pre: 9, 1, 6
4 4 1 6
Reconstruction - II In - 5, 7, 20, 15, 9, 8, 4
Post - 5, 7, 9, 4, 8, 15, 20
20
20

In: 5, 7 In: 15, 9, 8, 4 In: 15, 9, 8, 4


Post: 5, 7 7
Post: 9, 4, 8, 15 Post: 9, 4, 8, 15
5 20
20
7 15
7 15
5 8
5 In: 9, 8, 4
Post: 9, 4, 8 9 4

Exercise In - D, B, F, E, G, A, C
Post - D, F, G, E, B, C, A
A

In: D, B, F, E, G In: C
Post: D, F, G, E, B Post: C B C

A
D In: F, E, G
Post: F, G, E
B C

D E

F G

Reconstruction - III Pre - 9, 3, 5, 1, 17, 2, 4


Post - 5, 1, 3, 4, 2, 17, 9
9
9

Pre: 3, 5, 1 Pre: 17, 2, 4 3 Pre: 17, 2, 4


Post: 5, 1, 3 Post: 4, 2, 17 Post: 4, 2, 17

5 1 9
9
17
3
3 17
2
Pre: 2, 4 5 1
5 1 Post: 4, 2
4
Exercise Pre - 16, 8, 2, 13, 10, 24, 19, 25
Post - 2, 10, 13, 8, 19, 25, 24, 16
16

Pre: 8, 2, 13,10 Pre: 24, 19, 22 16


Post: 2, 10, 13, 8 Post: 19, 25, 24
8 Pre: 24, 19, 25
16 Post: 19, 25, 24

8 24 2 Pre: 13, 10
Post: 10, 13

2 13 19 25

10
BST - I
Asang Dani

Objectives
· Representing trees using arrays & linked lists
· What are binary search trees

Array Representation
3 - Arrays
0 1 2 3 4 5 6 7 8 9
A arr A B C D E F G '\0' '\0' H
lc 1 3 5 -1 9 -1 -1 -1 -1 -1
B C
rc 2 4 6 -1 -1 -1 -1 -1 -1 -1

E 1 - Array 2 ( depth + 2 ) - 1
D F G
0 1 2 3 4 5 6 7 8 9
arr A B C D E F G '\0' '\0' H
H 10 11 12 13 14 15 16 17 18 19
'\0' '\0' '\0' '\0' '\0' '\0' '\0' '\0' '\0' '\0'
lc = 2 pos + 1
20 21 22 23 24 25 26 27 28 29 30
rc = 2 pos + 2
'\0' '\0' '\0' '\0' '\0' '\0' '\0' '\0' '\0' '\0' '\0'

1
Exercise
0 1 2 3 4 5 6 7 8 9 10 11 12
arr 3 2 7 -1 8 -1 9 -1 -1 4 -1 1 6
lc 1 - 1 - 1 - 1 9 - 1 11 - 1 - 1 - 1 - 1 - 1 - 1
3 rc 2 4 6 - 1 - 1 - 1 12 - 1 - 1 - 1 - 1 - 1 - 1

2 7

8 9 0 1 2 3 4 5 6 7 8 9
arr 3 2 7 -1 8 -1 9 -1 -1 4
10 11 12 13 14 15 16 17 18 19
4 1 6 -1 1 6 -1 -1 -1 -1 -1 -1 -1
20 21 22 23 24 25 26 27 28 29 30
-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1

Linked Representation
A

B C

N D N E N N F N N G N

N H N struct btnode
{
struct btnode *lc ;
char data ;
struct btnode *rc ;
};

Binary Search Tree


10 10, 6, 8, 15, 20, 7, 13, 5

Greater goes to right


6 15
Smaller goes to left
In-order gives ascending order
5 8 13 20 5, 6, 7, 8, 10, 13, 15, 20

2
Exercise
V, L, A, Y, U, W, D, Z, X

L Y

A U W Z

D X

3
Binary Search Trees - II
Asang Dani
asang@ksetindia.com

Objectives

 Inserting elements in a BST


 Inorder, preorder & postorder traversal
 Comparing two trees

Program
#include <iostream>
using namespace std ;

int main ( )
{
btree bt ;

bt.insert ( 10 ) ;
bt.insert ( 6 ) ;
bt.insert ( 8 ) ;
bt.insert ( 15 ) ;
bt.insert ( 20 ) ;

bt.traverse ( ) ;
}

1
class btree
{
class btree
private : btree :: btree( )
struct btnode { {
btnode *lc ; root = NULL ;
int data ; }
btnode *rc ;
} *root ; void btree :: insert ( int num )
{
public : insert ( &root, num ) ;
btree( ) ; }
void insert ( int num ) ;
static void insert ( btnode **sr, int num ) ;
void traverse ( ) ;
static void inorder ( btnode *sr ) ;
static void preorder ( btnode *sr ) ;
static void postorder ( btnode *sr ) ;
static void del ( btnode *sr ) ;
~btree( ) ;
};

void btree :: insert ( btnode **p, int num ) insert Empty


{ *p
if ( *p == NULL )
{ N 10 N
*p = new btnode ;
Non-empty
( *p ) -> lc = NULL ; *p
( *p ) -> data = num ;
( *p ) -> rc = NULL ; N 10 N
}
*p N 6
else N N 15 N
{ *p N
if ( num < ( *p ) -> data ) 8 N *p
insert ( &( ( *p ) -> lc ), num ) ;
else
insert ( &( ( *p ) -> rc ), num ) ;
}
}

void btree :: inorder ( btnode *p )


{
if ( p != NULL )
inorder, preorder
{
inorder ( p -> lc ) ;
cout << "\t" << p -> data ;
inorder ( p -> rc ) ; p
}
} p 10
void
btree :: preorder ( btnode *p ) N 6 N 15 N
{ p N 8 N p
if ( p != NULL ) {
cout << "\t" << p -> data ;
preorder ( p -> lc ) ;
preorder ( p -> rc ) ;
}
}

2
void btree :: postorder ( btnode *p )
{
postorder
if ( p != NULL )
{
postorder ( p -> lc ) ;
postorder ( p -> rc ) ; p
cout << "\t" << p -> data ;
} p
 10


}
N 6 N 15 N
void btree :: del ( btnode *p)
{
if ( p != NULL )
{
p

N 8 N p

del ( p -> lc ) ;
btree :: ~btree ( )
del ( p -> rc ) ;
{
delete p ;
del ( root ) ;
}
}
}

Compare Trees
#include <iostream> bool i ;
using namespace std ; btree :: compare (
bt1, bt2, i ) ;
int main( ) if ( i == true )
{ cout << "Equal" << endl ;
btree bt1, bt2 ; else
bt1.insert ( 5 ) ; cout ( "Unequal" << endl ;
bt1.insert ( 3 ) ; }
bt1.insert ( 10 ) ;
void btree :: compare (
bt1.insert ( 4 ) ;
bt1.insert ( 2 ) ; btree& bt1 , btree& bt2 ,
bt2.insert ( 5 ) ; bool& flag ) {
bt2.insert ( 3 ) ;
bt2.insert ( 10 ) ; compare ( bt1.root , bt2.root,
bt2.insert ( 4 ) ; flag ) ;
bt2.insert ( 2 ) ;
}

Compare func.
void btree :: compare ( btnode *p, btnode *q, bool& flag )
{
flag = false ;
if ( p == NULL && q == NULL ) p 5
flag = true ;
if ( p != NULL && q != NULL )
{ 3 10
if ( p -> data != q -> data )
flag = false ; 2 4 7
else
{
compare ( p -> lc, q -> lc, flag ) ;
if ( flag != false )
compare ( p -> rc, q -> rc, flag ) ;
}
}
}

3
Binary Trees
Asang Dani
asang@ksetindia.com

Objectives
How to perform insertion on binary trees
How to delete a node from a binary tree
How to search a node in a binary tree

Successor And Predecessor


In - 5, 7, 9, 10, 11, 12, 14
11 Pre - 11, 7, 5, 10, 9, 14, 12
Post - 5, 9, 10, 7, 12, 14, 11
7 14
· In - order successor of 7 is 9
· In - order predecessor of 7 is 5
5 10 12
· Pre - order successor of 5 is 10
· Pre - order predecessor of 5 is 7
9
· Post - order successor of 12 is 14
· Post - order predecessor of 12 is 7

In - order successor of a node with


two child is always a leaf node or a
node with only right child

1
Program
#include <iostream>
using namespace std ;
bt.remove ( 14 ) ;
int main( ) bt.remove ( 7 ) ;
{ bt.remove ( 5 ) ;
btree bt ;

bt.insert ( 11 ) ; cout << "\nBinary Tree: " ;


bt.insert ( 7 ) ; bt.display ( ) ;
bt.insert ( 10 ) ; }
bt.insert ( 14 ) ;
bt.insert ( 5 ) ;
bt.insert ( 9 ) ;
bt.insert ( 12 ) ;
cout << "\nBinary Tree: ";
bt.display ( ) ;

class btree {
private : class btree
struct btnode {
btnode *lc ; btree :: btree( )
int data ; {
btnode *rc ; root = NULL ;
} *root ; }
static void del ( btnode *sr ) ;
void btree :: insert ( int num )
public : {
btree( ) ; insert ( &root, num ) ;
void insert ( int num ) ; }
void remove ( int num ) ;
void display( ) ;
static void insert ( btnode **sr, int ) ;
static bool search ( btnode **sr, int n, btnode **par, btnode **x ) ;
static void rem ( btnode **sr, int ) ;
static void inorder ( btnode *sr ) ;
~btree( ) ;
};

void btree :: insert ( btnode **pt, int num ) Empty


{
btnode *t , *p, *c ; insert *pt t
t = new btnode ;
N 11 N
t -> data = num ;
t -> rc = t -> lc = NULL ; Non-empty
pc c = N
if ( *pt == NULL )
*pt = t ; p
else N 11 N
{
p = c = *pt ; t N 7 N N 14 N
while ( c != NULL ) c
{ t N 10 N t
p=c;
num < p -> data ? ( c = p -> lc ) : ( c = p -> rc ) ;
}
num < p -> data ? ( p -> lc = t ) : ( p -> rc = t ) ;
}
}

2
void btree :: rem ( btnode **pt, int num ) *pt
{
btnode *p, *c, *csucc ;
bool found ; 11

if ( *pt == NULL )
7 14
{
cout << "\nTree is empty" ;
return ;
5 10 12
}
p = c = NULL ;
found = search ( pt, num, &p, &c ) ; 9

if ( found == false ) rem function


{
cout << "\nData not found" ;
return ;
} Contd...

...Contd

if ( c -> lc != NULL && c -> rc != NULL )


{
p=c; *pt
csucc = c -> rc ;
while ( csucc -> lc != NULL ) pc 11
{
p = csucc ;
9
7 14
csucc = csucc -> lc ; p csucc
}
c -> data = csucc -> data ; 5 10 12
c
c = csucc ;
}
9 csucc

Contd...

...Contd 11
if ( c -> lc == NULL && c -> rc == NULL )
t = NULL ; 10 12
btnode *t
if ( c -> lc == NULL && c -> rc != NULL ) 9
t = c -> rc ; p
if ( c -> lc != NULL && c -> rc == NULL )
t = c -> lc ; cp 11
p
if ( p -> lc == c )

else
p -> lc = t ;

p -> rc = t ;
11 c
 c 7 t 14

}
delete c ;
10

t 14 5 10 12

9
12 9

3
bool btree :: search ( btnode **pt, int num, btnode **p,
btnode **pc )
{ q *pt
btnode *q ;
q = *pt ; *p
q *p 11
*p = NULL ;
while ( q != NULL )
{ 7 14
q
if ( q -> data == num )
{
5 10 12
*pc = q ;
return true ;
} *pc
9
*p = q ;
num < q -> data ? ( q = q -> lc ) : ( q = q -> rc ) ;
}
return false ;
} search function

void btree :: remove ( int num )


{
remove, etc.
rem ( &root, num ) ;
}
btree :: ~btree( )
void btree :: display( ) {
{ del ( root ) ;
inorder ( root ) ; }
}
void btree :: del ( btnode *sr )
void btree :: inorder ( btnode *sr ) {
{ if ( sr != NULL )
if ( sr != NULL ) {
{ del ( sr -> lc ) ;
inorder ( sr -> lc ) ; del ( sr -> rc ) ;
cout << sr -> data << "\t" ; }
inorder ( sr -> rc ) ; delete sr ;
} }
}

4
Graphs
Yashavant Kanetkar

Objectives
· What are graphs
· The terminology associated with graphs
· Representation of graphs
· Adjacency lists

Graphs 1
1

2 3 2

4
3

Undirected Graph Digraph


· Graph is set of v & e
v - vertices (finite & non-empty), e - edges (pair of vertices)
· Undirected graph - edge is unordered, (1, 2) & (2, 1) are same
· Digraph - edge is ordered, <1, 2> & <2, 1> are different
· In <1, 2> 1 is tail and 2 is head
· In undirected graph 1 and 2 are adjacent
· In undirected graph edge (1, 2) is incident on 1 & 2
· In digraph 2 is adjacent to 3, while 3 is adjacent from 2
· In digraph edges <1, 2> and <2, 1> are incident to 1 & 2

1
More Terminology
1
1 4 1 2

2
2 3
2 3
3 Strongly connected
components

· Path - from 1 to 3 is sequence of vertices


1, 4, 3 with edges (1, 4), (4, 3)
· Simple path - starting & ending vertex distinct. 1, 4, 3
· Cyclic path - starting & ending vertex is same. 1, 2, 4, 1
· Connected - if there is a path from v1 to v2
· Strongly connected - if there is a path from v1 to v2 and v2 to v1.

Graph Representation
1 1

2 3
2
Store only
4 upper triangular
1 2 3 4 3
1 0 1 0 1 1 2 3
2 1 0 1 1 1 0 1 0
3 0 1 0 0 2 1 0 1
4 1 1 0 0 3 0 0 1

Adjacency Matrices

Adjacency List
V1 2 4 N
1
V2 1 3 4 N
2 3
V3 2 N
4
V4 1 2 N

1
V1 2 N

2
V2 1 3 N

V3 3 N
3

2
Exercise 1

V1 2 3 N 2 3

V2 1 4 5 N 4 5 6 7
V3 1 6 7 N
8
V4 2 8 N 1 2 3 4 5 6 7 8
1 0 1 1 0 0 0 0 0
V5 2 8 N 2 1 0 0 1 1 0 0 0
3 1 0 0 0 0 1 1 0
V6 3 8 N 4 0 1 0 0 0 0 0 1
5 0 1 0 0 0 0 0 1
V7 3 8 N 6 0 0 1 0 0 0 0 1
7 0 0 1 0 0 0 0 1
V8 4 5 6 7 N 8 0 0 0 1 1 1 1 0

3
Adjacency
Multilist
Yashavant Kanetkar

Objectives
·Adjacency matrices
·Adjacency multilists
·Orthogonal representation of graphs

Adjacency Multilist
1 V1 2 3 4 N
V2 1 3 4 N
2 3
V3 1 2 4 N
4 V4 1 2 3 N

Next link Next link


m Vi Vj for Vi for Vj

1 V1 E1 1 2 E2 E4
E1 E2
E3 V2 E2 1 3 E3 E4 V1: E1-> E2 -> E3
2
E4
3 E3 1 4 N E V2: E1-> E4 -> E5
5
V3
E5 E6 E4 2 3 E5 E6 V3: E2-> E4 -> E6
4 V4
E5 2 4 N E V4: E3-> E5 -> E6
6

E6 3 4 N N

1
Adjacency Multilist
1 V1 2 N
E1 E2 V2 1 3 N

2 V3 2 N

E4 E3
Next link Next link
3 m tail head for tail for head

V1h E1 1 2 N E4 V1h: E2
V1t V1t : E1
V2h E2 2 1 E3 N V : E1 -> E4
2h
V2t
E3 2 3 E2 N V2t : E2 -> E3
V3h V3h: E3
V3t E4 3 2 N E1 V3t : E4

E2
Exercise
E3 1 6
E1 V1h E1 1 5 E2 E6
E9 E10 E8 V1t E2 1 6 E1 E8
2 5 V2h
E6 V2t E3 2 1 E4 N
E4 E7
3 4 V3h
E5 V3t E4 2 3 E3 N
V1h: E3 V4h 3 4 E6 N
E5
V1t : E1 -> E2 V4t
V2h: E9 V5h E6 3 5 E5 E7
V2t : E3 -> E4 V5t E7 4 5 E8 E10
V3h: E4
V3t : E5 -> E6 E8 4 6 E7 E2
V4h: E5 E9 5 2 N N
V4t : E7 -> E8
V5h: E1 -> E6 -> E7 -> E10 E10 6 5 N E1
V5t : E9

Orthogonal Representation
1 2 3
1
1 0 1 0
2 1 0 1
2
3 0 0 0
col. link row link
3 tail head for head for head

head node 1 2 3

1 1 2 N N

2 2 1 N 2 3 N N

3 N

2
Exercise
1

2 4

head node 1 2 N 3 4

1 1 4 N

2 2 1 N 2 3 2 4 N N

3 N

4 4 3 N N

Exercise
Give all graphical representations for the following graph

1 1 2 3 4 5
2
1 0 1 1 0 0
3 5 2 1 0 0 0 0

4 3 0 1 0 0 0
4 0 0 1 0 1
5 0 1 0 1 0

Adjacency Matrices

Adjacency List

1 2 V1 2 3 N

V2 1 N
3 5

4 V3 2 N

V4 3 5 N

V5 2 4 N

3
1 E1
E3
Adjacency Multilist
E2 2
E4
E8
3 E7 5
V1h E1 1 2 E2 E4
E5 4 V1t
E6 E2 1 3 E1 E5
V2h
V1h: E3 V2t E3 2 1 N N
V1t : E1 -> E2 V3h
E4 3 2 N E8
V2h: E1 -> E4 -> E8 V3t
V2t : E3 V4h E5 4 3 E6 E2
V3h: E2 -> E5 V4t
E6 4 5 E5 N
V3t : E4 V5h
V4h: E7 V5t E7 5 4 E8 N
V4t : E5 - > E 6
V5h: E6 E8 5 2 E7 E1
V5t : E7 -> E8

1 E1
E3
Adjacency Multilist
E2 2
E4
E8
3 E7 5
V1h E1 1 2 E2 E4
E5 4 V1t
E6 E2 1 3 E1 E5
V2h
V1h: E3 V2t E3 2 1 N N
V1t : E1 -> E2 V3h
E4 3 2 N E7
V2h: E1 -> E4 -> E7 V3t
V2t : E3 V4h E5 4 3 E6 E2
V3h: E2 -> E5 V4t
E6 4 5 E5 N
V3t : E4 V5h
V4h: E8 V5t E7 5 2 E8 E1
V4t : E5 - > E 6
V5h: E6 E8 5 4 E7 N
V5t : E7 -> E8

Orthogonal
1 1 2 3 4 5
2 1 0 1 1 0 0
2 1 0 0 0 0
3 5 3 0 1 0 0 0
4 0 0 1 0 1
4 5 0 1 0 1 0
head node 1 2 3 4 5

1 1 2 1 3 N

2 2 1 N

3 3 2 N

4 4 3 N 4 5N N

5 5 2 N 5 4 N N

4
Depth First Search
Asang Dani
asang@ksetindia.com

Objectives
Depth First Search Algorithm
Depth First Search Example
Depth First Search Program

Depth First Search·· Visit a vertex, mark it visited


Visit its adj. unvisited vertex
V1 2 3 N · Rep. 1-2 till all adj. Ver. visited
· Go back, repeat 1, 2 & 3
V2 1 4 5 N

V3 1 6 7 N 1

V4 2 8 N 2 3

V5 2 8 N
4 5 6 7
V6 3 8 N

V7 3 8 N 8

V8 4 5 6 7 N

1
Exercise
V1 2 8 N

V2 1 3 8 N
1 2 3
V3 2 4 8 N

V4 3 7 N 7 8

V5 6 7 N
6 5 4
V6 5 N

V7 4 5 8 N

V8 1 2 3 7 N

Program
# include <iostream> v1 = g.add ( 1 ) ;
using namespae std ; v2 = g.add ( 4 ) ;
v3 = g.add ( 5 ) ;
int main( ) arr[ 1 ] = v1 ;
{ v1 -> next = v2 ;
node *arr [ MAX ] ; v2 -> next = v3 ;
node *v1, *v2, *v3 ; v1 = g.add ( 1 ) ;
graph g ; v2 = g.add ( 6 ) ;
v1 = g.add ( 2 ) ; v3 = g.add ( 7 ) ;
v2 = g.add ( 3 ) ; arr[ 2 ] = v1 ;
arr[ 0 ] = v1 ; v1 -> next = v2 ;
v1 -> next = v2 ; v2 -> next = v3 ;
v1 = g.add ( 2 ) ;
v2 = g.add ( 8 ) ;
arr[ 3 ] = v1 ;
v1 -> next = v2 ; Contd...

...Contd
v1 = g.add ( 2 ) ; arr[ 7 ] = v1 ;
v2 = g.add ( 8 ) ; v1 -> next = v2 ;
arr[ 4 ] = v1 ; v2 -> next = v3 ;
v1 -> next = v2 ; v3 -> next = v4 ;
v1 = g.add ( 3 ) ; node *v4
v2 = g.add ( 8 ) ; g.dfs ( 1, arr ) ;
arr[ 5 ] = v1 ;
for ( i = 0 ; i < MAX ; i++ )
v1 -> next = v2 ;
g.del ( arr[ i ] ) ;
v1 = g.add ( 3 ) ; } int i
v2 = g.add ( 8 ) ;
arr[ 6 ] = v1 ;
v1 -> next = v2 ;
v1 = g.add ( 4 ) ;
v2 = g.add ( 5 ) ;
v3 = g.add ( 6 ) ;
v4 = g.add ( 7 ) ;

2
struct node class graph
{ graph :: graph( )
int data ;
{
node *next ;
for ( int i = 0 ; i < MAX ; i++ )
}; visited [ i ] = false ;
}
class graph
node * graph :: add ( int val )
{
{
private :
node *n ;
bool visited [ MAX ] ;
n = new node ;
public : n -> data = val ;
graph ( ) ; n -> next = NULL ;
void dfs ( int v, node **p ) ; return n ; New Node
node* add ( int val ) ; } n
void del ( node *n ) ;
};
5 N

void graph :: dfs ( int v, node **p ) 1


{
struct node *q ;
dfs ( )
2 33
visited [ v - 1 ] = true ;
cout << v << "\t" ;
q=*(p+v-1); 4 5 6 7
while ( q != NULL )
{
if ( visited [ q -> data - 1 ] == 0 )
dfs ( q -> data, p ) ; 8
else q
q = q -> next ; p
}
} arr[ 0 ] 2 3 N
q q
1 2 4 8 5 6 3 7
arr[ 1 ] 1 4 5
1 2 3 4 5 6 7 8
arr[ 2 ] 1 6 7
01 01 01 1
0 0
1 0
1 1
0 0
1

void graph :: del ( node *n ) del( )


{
node *t ;
while ( n != NULL ) n n t t = NULL
{
t = n -> next ;
delete n ;
n=t;
arr[ 0 ]

arr[ 1 ]

2

1
3

4
N

5 N
}
} arr[ 2 ] 1 6 7 N

arr[ 3 ] 2 8 N

arr[ 4 ] 2 8 N

arr[ 5 ] 3 8 N

3
Breadth First Search
Asang Dani
asang@ksetindia.com

Objectives
Breadth First Search Algorithm
Breadth First Search Example
Breadth First Search Program

Breadth First Search 1

V1 2 3 N 2 3

V2 1 4 5 N 4 5 6 7

V3 1 6 7 N
8
V4 2 8 N 1 2 3 4 5 6 7 8

V5 2 8 N · Visit a vertex, mark it visited


· Add it to queue
· Visit its adj. unvisited vertex
V6 3 8 N · Add it to queue
· Rep. 3-4 till all adj. Ver. Visited
V7 3 8 N · Pick a vertex from queue
· Rep. 1-6 till q becomes empty
V8 4 5 6 7 N

1
Exercise
V1 2 8 N
1 2 3
V2 1 3 8 N

7 8
V3 2 4 8 N

V4 3 7 N
6 5 4
V5 6 7 N

V6 5 N 1 2 8 3 7 4 5 6

V7 4 5 8 N

V8 1 2 3 7 N

#include <iostream>
#include <cstdlib>
public : class graph
graph( ) ;
using namespace std ; void bfs ( int v, node **p ) ;
node * add ( int val ) ;
const int MAX = 8 ; void addqueue ( int v ) ;
struct node int delqueue ( ) ;
{ static bool isempty ( ) ;
int data ; void del ( node *n ) ;
node *next ; };
};

class graph graph :: graph( )


{ {
private : for ( int i = 0 ; i < MAX ; i++ )
bool visited [ MAX ] ; visited [ i ] = false ;
int q [ MAX ] ; f = r = -1 ;
int f, r ; }

bfs 1 1
void graph :: bfs ( int v, node **p )
{ 2 3
1 2 3 4
node *u ; 01 0 0 0
visited[ v - 1 ] = true ; 4 5 6 7
cout << v << "\t" ; queue
addqueue ( v ) ; 1
while ( isempty ( ) == false ) 8
{ u
v = delqueue ( ) ; *p
u=*(p+v-1);
arr[ 0 ] 2 3 N

arr[ 1 ] 1 4

arr[ 2 ] 1 6
Contd...

2
...Contd while ( u != NULL ) 1 2 3 4 5 6 7 8
{
if ( ! visited [ u -> data - 1 ] ) queue
{
addqueue ( u -> data ) ; 2 3 4 5
visited [ u -> data - 1 ] = true ;
cout << u->data << "\t" ;
}
u = u -> next ; 01 01 01 10 01 01 01 01
}
1 u u
} *p
}
2 33 arr[ 0 ] 2 3 N
u u u
arr[ 1 ] 1 4 5
4 5 6 7
arr[ 2 ] 1 6 7
8 2 8 N
arr[ 3 ]

addqueue( )
addqueue ( int vertex )
{
if ( r == MAX - 1 )
{
cout << "\Full." ;
exit( ) ;
}

r++;
q [ r ] = vertex ;

if ( f == - 1 )
f=0;
}

delqueue( ) & isempty( )


int graph :: delqueue ( ) bool graph :: isempty ( )
{ {
int data ; if ( f == - 1 )
return true ;
if ( f == - 1 ) return false ;
{ }
cout << "\nEmpty." ; node* graph :: add ( int val )
exit( ) ; {
} node *newnode = new node ;
newnode -> data = val ;
data = q [ f ] ;
return newnode ;
if ( f == r ) }
f = r = -1 ;
else
f++;
return data ;
}

3
Spanning Tree
Asang Dani

Objectives
· Spanning Tree
· Cost of Spanning Tree
· Kruskal’s Algorithm to determine minimum cost
Spanning Tree

Spanning Tree
X Undirected tree
X Contains edges necessary to connect all vertices

1 1 1

2 5 3 2 5 3 2 5 3

4 4 4
Spanning Trees
1 1

2 5 3 2 5 3

4 4
DFS ST BFS ST

1
Calculating Cost
4
1 4
7 2 1

2 3
3
4 4 4
1 4 1 4 1 4 1 4
1 2 7 1 7

2 3 2 3 2 3 2 3
3 3 3 3
4
1 4
Minimum Cost
2 1 Spanning Tree
2 3

Kruskal’s Algo • Insert edges in inc. order of cost


• Reject if it forms a cyclic path

4 Edge Cost Tree Action


1 4
1 4
7 2 1 4-3 1 1 Included
2 3 2 3
3

1 4
4
1 4 4-2 2 2 1 Included
2 1 2 3

2 3 4
3-2 3 1 4 Rejected
Minimum Cost 2 1
Spanning Tree 4-1 4 2 3 Included
3

Exercise Edge Cost Tree Action


A
A
13 10 B C
9 B-C 9 9 Included
B C
20 D

40 D 35 E
14
A
10
E B C
A-C 10 9 Included
D

Contd...

2
...Contd A Edge Cost Tree Action
13 10
9 A
B C 13 10
20 A-B 13 Rejected
B C
D 9
40 35
14 D
E-D 14 14 Included
E
E

A A
10 10
B 9 B C
C B-D 20 9 Included
20 20 D
D
14
14
Min. E
Cost ST E

3
Dijkstra’s
Algorithm
Asang Dani

Objectives
· Dijkstra’s Algorithm to determine minimum cost
Spanning Tree
· AOV Network
· Exercise

Dijkstra’s Algorithm
7
4
1 4
2
5 7 1

2 3
3

1 2 3 4 1 2 3 4

1 7 5 1 11 12 - -
8

2 7 2 2 21 - - 24
8

3 3 3 - 32 - -
8

8
8

4 4 1 4 41 - 43 -
8
8

Contd...

1
...Contd 7
4
1 4
2
5 7 1

2 3
3
1 2 3 4 1 2 3 4
1 7 5
8 8 8

1 11 12 - -
2 7 2 2 21 - - 24
8

3 3 3 - 32 - -
8 8
8

4 4 1 4 41 - 43 -
8

1 2 3 4 1 2 3 4
1 7 5
8 8 8

1 11 12 - -
2 7 12 2 2 21 212 - 24
3 3 3 - 32 - -
8 8
8

4 4 9 1 4 41 412 43 -

...Contd 7
4
1 4
2
5 7 1

2 3
1 2 3 4 3
1 2 3 4
1 7 5
8 8 8

1 11 12 - -
2 7 12 2 2 21 212 - 24
3 3 3 - 32 - -
8 8
8

4 4 9 1 4 41 412 43 -

1 2 3 4 1 2 3 4
1 7 5 7
8 8 8

1 11 12 - 124
2 7 12 2 2 21 212 - 24
3 10 3 5 3 321 32 - 324
4 4 9 1 11 4 41 412 43 4124

...Contd 7
4
1 4
2
5 7 1

2 3
3
1 2 3 4 1 2 3 4
1 7 5 7
8 8 8

1 11 12 - 124
2 7 12 2 2 21 212 - 24
3 10 3 5 3 321 32 - 324
4 4 9 1 11 4 41 412 43 4124
1 2 3 4 1 2 3 4
1 7 5 7
8 8 8

1 11 12 - 124
2 7 12 2 2 21 212 - 24
3 10 3 5 3 321 32 - 324
4 4 4 1 6 4 41 432 43 4324

2
...Contd 7
4
1 4
2
5 7 1

2 3
3
1 2 3 4 1 2 3 4
1 7 5 7
8 8 8

1 11 12 - 124
2 7 12 2 2 21 212 - 24
3 10 3 5 3 321 32 - 324
4 4 4 1 6 4 41 432 43 4324
1 2 3 4 1 2 3 4
1 7 5 8 7 1 11 12 1243 124
2 6 6 3 2 2 241 2432 243 24
3 9 3 6 5 3 3241 32 3243 324
4 4 4 1 6 4 41 432 43 4324

20 Exercise
8
E F
15 6 E F G E F G
G
7 8
8

E 15 E - EF EG
20 6
8

F F FE - FG
7 GE
8

G G - -

E F G E F G
8
8

E 15 E - EF EG
F 20 28 6 F FE FEF FG
G 7 15 22 G GE GEF GEG

Contd...

...Contd
20
8
E F
15 6
G
7
E F G E F G
8
8

E 15 E - EF EG
F 20 28 6 F FE FEF FG
G 7 15 22 G GE GEF GEG

E F G E F G
E 28 8 14 E EFE EF EFG
F 20 28 6 F FE FEF FG
G 7 15 21 G GE GEF GEFG
Contd...

3
...Contd 20
8
E F
15 6
G
7
E F G E F G
E 28 8 14 E EFE EF EFG
F 20 28 6 F FE FEF FG
G 7 15 21 G GE GEF GEFG

E F G E F G
E 21 8 14 E EFGE EF EFG
F 13 21 6 F FGE FGEF FG
G 7 15 21 G GE GEF GEFG

Sub. No.
S1
Prereq.
None
Sub. No.
S8
Prereq.
S4
AOV N/W
S2 S1, S14 S9 S3 Activity On Vertex Network
S3 S1, S14 S10 S3, S4
S11 S10 V - Activity / Task
S4 S1, S13 E - Precedence Relation
S12 S11
S5 S15 S13 None
S6 S3 S14 S13
S7 S3, S4, S10 S15 S14
S13 S14 S15 S5

S4 S8 S2 S9

S1 S3 S6
Precedence
Activity
S7
S10
S11 S12

Exercise - I
Vertex Prerequisite V2
V1 None
V2 V1
V3 V1
V1 V3 V5
V4 V1
V5 V2, V3, V4
V6
V6 V3, V4

V4

4
Exercise - II
Vertex Prerequisite V2
V1 None
V2 V1
V3 V1, V6
V1 V3 V5
V4 None
V5 V2, V3, V4
V6 V4, V5
V4 V6

Not Feasible

You might also like