oDEngineers.co
Mayuranand Classes
8403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. tl 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. V 6517 3281
DATA STRUCTURES
DETAILED SYLLABUS
(1) Introduction inC :
0
0
(2) Lists:
! ADT
! Representation
! Operations
! Examples
! Applications
Queues
! ADT
! Representation
! Operations
! Circular and Priority Queues
! Examples
! Applications
Other Lists and their Implementations
(3)Linked Lists :
0
0
0
ADT
Dynamic Memory and Pointers
Dynamic Representation
! Insertion and Deletion of Nodes
! Linked Stacks and Queues
! Lin ked Lists as Data Structure
! Array Implementation of Linked List
! Comparison of Dynamic and Array Representations
(4) Recursion:
.0
0
0
0
oDEngineers.colpg.j
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bani<, Zaver Road, Mulund (W), Mumbai 80. if 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, ~ctor 17, Vashi, Navi Mumbai. ir 6517 3281
84
B216/21
LIST OF EXPERIMENTS
(1)
(2)
(3)
(4)
(5)
(6)
. CH. 1.
CH. 2.
List
CH. 3.
Linked List
CH. 4.
Recursion
CH. 5.
Binary Tree
TOTAL
34
16
18
96
164
20
36
16
14
82
168
30
40
10
60
145
20
10
so
60
140
20
20
38
58
140
20
40
80
148
MAY
2006
(7 Qstns.)
22
14
15
16
77
144
AVERAGE
MARKS
24
16
31
74
150
JUNE
2003
Introduction
to 'C'
(10 Qstns.)
DEC
2003
(10 Qstns.)
APRIL
2004
(7 Qstns.)
NOV
2004
(7 Qstns.)
MAY
2005
(7 Qstns.)
DEC
2005
(7 Qstns.)
Com
Mayuranand Classes
6525 7069
li. lr 6517 3281
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai, 80. V 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. V 6517 3281
(oATA STRUCTURES)
3tion
!rtion and .
INDEX
.C h. No.
ree
Topic
Page Nos.
TOTAL
1.
Introduction to 'C'
1 13
168
2 ..
Lists
14 29
145
3.
Linked Lists
3047
140
4.
4879
164
140
148
144
150
I
t
I
r
1:
Pg. ii
,f
B41
B216/21"
STI
Q.l.,
Ans.:
In ne
togetr
becau
For )c
at lee:
en cap
unit, <
by YOI
So, n
togett
builti
Struc
put ar
other
struct
struct
{
};
struc
birtht
birth!
birth
Now,
defh
therr
we c
Strw
.nam
like
calle
neec
put .
proc
in a
vari<
we'r
builc
the :
oDEngineers.col
To;
key'
stru
Com1
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. if 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281
DATA STRUCTURES
CHAPTER 1 : INTRODUCTION TO 'C'
So, now that we have some belief that it's a good idea to put data members
together somehow, how do we go about accomplishing this task ? Easy ! 'C' has a
builtin method for working with sets of data, and they are called structures.
Structures, as the name implies, are containers for varying kinds of data. You can
put any kind of data within a structure : integers, characters, pointers, arrays, even
other structures, i f you like. Let's take a look at a small example to see how
structures work.
struct dob
{
int month;
int day;
int year;
};
oDEngineers.colpg:!
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. V 3251 4726, 6525 7069
~216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector .17, Vashi, Navi Mumbai. V 6517 3281
84
B216/21
tell the compiler we want it to create a dob structure, and then give it a variable
name .we can use to access the structure, which we called birthday.
You m
you cc
If we '
Finally, how do we access the members of a structure ? Well, that's easy. 'C' has a
builtin operator, called the dot operator. The dot operator is just that, .a dot, or
more properly, a period. So, we use the name of the structure (the variable name,
not the structure name), followed by the dot operator, and then the name of the
variable structure member we want to access. This is just like using an.y other
variable, so you can do anything with a structure member that you can do with a
variable.
for bo
Let's take it a step further and work through a small example program.
Create a new 'C' source file named struct.c.
used t
As far
The d
variat
time.
D,
Q. 2.
II C Source File
Ans.:
#include <stdio.h>
Point'
mem
struct dob
So, v
know
Point
allow
};
chan
struct Pers{)n
A po
point
char name[20];
Decl;
int height;
int
void
:.~
};
cha1
Basi
nam
are
int,
wan
clrscr( ) ;
II
Wel l
vari
SUP I
pro ~
/ '!?X!
Up
me1
pro
me;
getch();
}
are
Hm
Unions:
Well, structure is the first and probably most popular way to group data members
together in 'C'. But it is not the only way of grouping data together. Suppose we
want to use either an integer, or a floating point number to store a number, but we
don't want to use both. Well, instead of declaring two variables, we could put them
together in what is called a union in 'C'. Unions are like structures in that they
combine data members together in a single block. But the difference is that we can
only use one variable in the union at a time. This is because the variable space for
all the variables are defined on top of one another. So using any one of the
...   !  L . I  
. .~
II~~~'
~L 
   
 ~
_ II.___. _
oownloaded from
If ~
eve
am
me
ThE
me
me
me
_ .._ . _
FaaDoDEngineers.col
Cor
.
6525 7069
i. 6517 3281
a variable
' 'C' has a
, a dot, or
1ble name,
me of the
any other
do with a
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. it 3251 4726, 65257069
B~216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. ir 6517 3281
You may be asking yourself, why would anyone want to create a structure where
you could only use one variable ? Well, the answer is easy : memory management.
If we need to store two different kinds of data, there is no reason to reserve space
for both kinds. We can just reserve space for the largest one, and save the space
used by the smaller one.
As far as using unions, they are used in exactly the same manner as structures.
The dot operator accesses their member variables or in this case, their member
variable, singular. Remember we 'can only use one piece of the union at any one
time.
void *ptr;
II
char *ptr;
/~!:!.~!11!~ ~.C!m~JI.II.()_c:atio_n..
=..
Up until this time, we have used what is referred to as static memory. Static
If you said Dynamic Memory Allocation, that's right. Dynamic memory won't fix
everything. We will always need an amount of finite static memory, but this
amount is usually. much less than we need. This is why we still have static
memory.
~can
The two functions we will be employing 'in our dynamic memory allocation tasks are
malloc() and free().
e for
malloc() meaning memory allocation, and free, well, that should be ohvirHS. Our
the
Pg. 2
m~
Mayuranand Classes
8403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. ir 3251 47.~6i. 6525 7069
8216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector17, Vashi, Navi Munibai. V 6517 3281
B211
Let's discuss the syntax of malloc(). It takes a single argument, a long integer
representing the number of bytes we want to allocate from the heap. Note that the
heap is what we call all the memory we don't reserve by default. So, for example,
to allocate memory for an array of characters for a 40 character string., we would
do malloc( 40); There's more to it, obviously.
The
The
The
To allocate memory though, we must have a pointer so we can know where the
memory will be at when it gets allocated. Let's look at a small code example :
ret
fun<
A fL
malloc() allocates size bytes and returns a pointer to the allocated memory. The
memory is not cleared.
free() frees the memory space pointed to by ptr, which must have been returned
by a previous call to malloc(), calloc() or realloc(). If ptr is NULL, no operation is
performed.
Fur
Wh;
The
Fun
sep
Pal
calloc() allocates memory for an array of nmemb elements of size bytes each arid
returns a pointer to the allocated memory. The memory is set to zero.
ThE
realloc() changes the size of the memory block pointed to by ptr to size bytes.
The contents will be unchanged to the minimum of the old and new sizes; newly
allocated memory will be uninitialized. If ptr is NULL, the call is equivalent to
malloc(size); if size is equal to zero, the call is equivalent to free(ptr). Unless ptr is
NULL, it must have been returned by an earlier call to malloc(), calloc() or realloc().
In'
she
In
ThE
are
Pa~
Let
Return values :
voi
For calloc() and malloc(), the value returned is a pointer to the allocated
memory, which is suitably aligned for any kind of variable, or NULL if the request
fails.
If,
int
Bu
pa
Ans.: Functions :
thE
Why should we make functions in our programs when we can just do it all under
main ? Think for a minute about highend stereo systems. These stereo systems
do not come in an allinone package, but rather come in separate components :
preamplifier, amplifier, equalizer, receiver, cd player, tape deck, and speakers.
The same concept applies to programming. Your programs become modularized
and much more readable if they are broken down into components.
This type of programming is known as topdown programming, because we first
analyze what needs .to be broken down into components. Functions allow us to
create topdown modular programs. Each function consists of a name, a return
type, and a possible parameter list. This abstract definition of a function is known
as its interface. Here are some sample function interfaces :
char *strdup (char *s)
Ttl
Th
co
su
All
#i
#c
sa 1
us
oDEngineers.col
Co
Mayuranand Classes
6525 7069
Ji.
6517 3281
8403/407, Konark Darshan, Above UTI Bank, laver Road , Mulund (W), Mumbai 80. V 3251 4726, 6525 7069
8216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. W 6517 3281
The first function header takes in a pointer to a string and outputs a char pointer.
>ng integer
1te that the
r example,
, we would
where the
pie :
string
Function Prototype :
mory. The
What are function prototypes ? Function prototypes are abstract function interfaces.
These function declarations have no bodies; they just have their interfaces.
returned
1eration is
1
Function prototypes are usually declared at the top of a 'C' source file, or in a
separate header file.
each and
There are two ways that parameters are passed into functions. The two that we
should be concerned with are Pass by Value and Pass by Reference.
ze bytes.
~s; newly
talent to
~ss ptr is
ealloc().
tllocated
request
{
int tmp = 0;
tmp = x;
suitably
if the
' is left
~
= y;
= tmp;
}
If, you were to simply, pass in parameters to this swapping function that swaps two
integers, this would fail horribly. You'll just get the same values back.
But thankfully, you can circumvent this pass by value limitation in 'C' by simulating
pass by reference. Pass by reference changes the values that are passed in when
the function exits. This isn't how 'C' works technically but can be thought of in the
same fashion. So how do you avoid pass by value side effects? The answer is,by
using pointers and in some cases using macros.
under
'Stems
ents :
akers.
arized
The 'C' Preprocessor (CPP) is not part of the compiler, but is a separate step in the
compilation process. In simplistic terms, a 'C' Preprocessor is just a text
substitution tool. We'll refer to the 'C' Preprocessor as the CPP.
e first
us to
eturn
nown
~.
Pg.4
#include
#define
#undef
Undefines
a preprocessor macro
DEngineers.c
Pg. 5
. Mayuranand Classes
B403 I 407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. ir 3251 4726, 6525 7069
8216/217 Vardhman Chambers, Ab()ve UTI Bank, Nr Babubhai Jagjeevandas,Sector 17, Vashi, Navi Mumbai. if 6517 3281
. ~ifndef
#if
#else
#elif
#endif
, ,.~
B403
B216/217,
macro <
later.
Note:
Functiol
passed
The C
directiv
sot
Q.4. E
Tells the CPP to replace instances of MAX_ARRAY_LENGTH with 20. Use #define for
'
constants to increase readability. Notice the absence of the ; .
(1) m
#include <stdio.h>
(3) ftt
#include "mystring.h"
(4) fp
Tells the CPP to get stdio.h from system libraries and add the text to this file.
The next line tells CPP to get mystring.h from the local directory and add the text
to the file. This is a difference you must take n()te of.
(5) fs
#undef MEANING_OF_LIFE
(7) fr
#define MEANING_OF_LIFE 42
(8)
Ans.:
#ifndef IROCK
(1) n
(2) fr1
(6)
f\1
f~
n
T
(2) fl
11
h
Parameterised Macros :
One of the powerful functions of the CPP is the ability to simulate functions using
parameterized macros. For example, we might have some code to square a
number:
(3) f
J.
int square(int x)
t
return
x * x;
(4) f
}
We can instead rewrite this using a macro:
#define square(x) ( (x)
* (x))
A few things you should notice. First square(x) The left parentheses must "cuddle"
with the macro identifier. The next thing that should catch your eye are the
parenthesis surrounding the x's. These are necessary.
This is a fundamental difference between macros and functions. You don't have to
worry about this with functions, but you must consider this when using macros.
{5)
Remember. that pass by value vs. pass by reference issue earlier ? I said that you
.could go around this by using a macro. Here is swap in action when using a macro :
#define swap(x, y) { int tmp
= x; x = y; y = tmp }
Now we have swapping code that works. Why does this work ? It is because the
CPP iust simolv rPnl;:tf'PC: t~vt \A/hai"Q\IQI" C'\AI:lr'\ ie ,.~ll.o..l +h" rnn ... :II    1    .LL
Comp
Mayuranand Classes
;, 6525 7069
lai. a 6517 3281
8403/407, Konark Darshan. Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. V 3251 4726, 6525 7069
8216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Ja~Jeevandas, Sector 17, Vashi, Navi Mumbai. ir 6517 3281
macro call with the defined text. We'll go into how we can .do this with pointers
later.
Note:
Functions allow for modular programm ing. You must remember that all parameters
passed into function in Care passed by value!
The C preprocessor allows for macro definitions and other precompilation
directives. It is just a text substitution tool before the actual compilation begins .
.+
(1) malloc()
(2) free()
(3) ftell()
( 4) fprintf()
this file.
d the text
>
(5) fscanf()
(6) fwrite()
(7) fread()
(8) fseek():
Ans.:
(1) mallo(:() :
malloc() allocates size bytes and returns a pointer to the allocated memory.
The memory is not cleared .
(2) free() :
It frees the memory space pointed to by a given pointer say ptr, which must
have been returned by a previous call to malloc(), calloc() or realloc().
If ptr is NULL, no operation is performed.
,
(3) ftell() :
ns using
quare a
Prototype:
long ftell( FILE *stream);
 The ftell() function obtains the current value of the file position indicator for
the stream pointed to by stream.
( 4) fprintf() :
Prototype:
int fprintf(FILE *stream, const char* format, ..... );
cuddle"
!re the
(5) fscanf() :
tave to
)S.
prototyp(3 :
1at you
1acro :
1
._._
se the
:e the
Pg. 6
,.
Data is read from a file using fscanf(). This function is very similar to
scanf(), which is .used to read from standard in.put, stdin. fscanf() has one
additional argument t o specify th e stream to read from. Remember that the
oownl;d~<t~~l81~;ni0Enginlers.c 1?9.7
rrI
, I
rj
r!
,I
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank,.Zaver Road, Mulund (W), Mumbai 80. tl 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, NrBabubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281
. ,~ j
J!
l]
B21E
+
(6) fwrite{) :
,jj
Q.
Prototype:
out
Ans
The fwrite() function writes, from the array pointed to by ptr, up to nitems .
members whose size is specified by size, to the stream pointed to by stream.
The fileposition indicator for the stream (if defined) is advanced by the
number of bytes successfully written. If an error occurs, the resulting value of
the fileposition indicator for the stream is indeterminate.
;~
li
alw;
as
VOIL
two
It
thrc
the
It i
sta t
Thi:
wht
Q.
by
An
wo
bu1
ne<
For
tra
filE
Fo
FI
(8) fseek() :
Prototype:
I deletion of element
aDEngineers.c
Lil
Li~
to
(1
Mayuranand Classes
6525 7069
B403/407, Konark Oarshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. ir 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr BabubhaLJagjeevandas, Sector 17, Vashi, Navi Mumbai. V 6517 3281
>;
to nitems
>ointed to
'anced by
ing value
a partial
members
offile is
1ts of the
f a read
s set to
Ans. : Functions such as scanf and printf are console oriented 1/0 functions which
always use the terminal (keyboard and screen) as the target place. This works fine
as long as the data is small. However, many reallife problems involve large
volumes of dada and in such situation; the console oriented 1/0 operations pose
two major problems.
It becomes cumbersome and time consuming to handle large volumes of data
through terminals. The entire data is lost when either the problem is terminated or
the computer is turned off.
It is therefore necessary to have a more flexible approach where data can be
stored on the disks and read whenever necessary, without destroying the data.
Thi~ method employs the concept of files to store data. A file is a place on the disk
where a group of related data is stored.
=d to by
g offset
K_SET,
File, the
I to the
List of library functions used for file input and output (I/0). These routines are used
. to open and close files and read and write files using formatted I/0.
(1) fopen() :
fopen() is used to open a file for formatted I/0 and to associate a stream
with that file. A stream is a source or destination of data. It may be a buffer in
memory, a file or some hardware device such as a port. The prototype for
fopen()is :
FILE *fopen(const char *filename, const char *mode);
'C'.
Pg . 8
Use
Open or create for writing. Append (write after) any previous contents.
r+
w+
Open or create file for update. Truncate (discard) any previous data.
a+
Open or create file for update. Append (write after) any previous data.
Pg. 9
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. if' 3251 4726, 6525 7069
B216/217Vardhman Chambers, AboveUTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. tif 6517 3281
{2) fclose() :
(3) fprintf() :
Data is written to a file using fprintf(). This function is very similar to
printf(). printf() was used to write to standard output, stdout. fprintf() has
one additional argument to specify the stream to send data. Its prototype is :
B403
B216/217 \
The out1
scanf()
output ~
the inpL
conside1
stdin is
and std
Thus,
tr
inti;
scanf ("
fprintf (
will sen
appear
structu1
beginni
( 4) fscanf() :
Data is read from a file using .f scanf(). This function is very similar to
scanf(), whiCh is used to read from standard input, stdin. Fscanf has one
additional argument to specify the stream to read from . Remember that the
argument to store data must be pointers. The prototype for fscanf() is:
(5) fgetc() :
int fgetc{FILE *stream);
This function returns the next character in the input stream, or EOF if the end
of the file is encountered. It returns int rather than char because the "end of
fHe", EOF, character must be handled. EOF is an int and is too large to fit in a
char variable.
co~
Q. 9.'
to do I
Ans.:
string
There i
a buffe
Writin
fwrite
approp
buffer
being i
fputc() writes a single character to the output stream. It returns EOF on failure.
Low le
(6) fputc() :
(1)
(7) fgets() :
s:
di
(2)
01
The fo
'C' pro
#inclu
#inclu
#inclu
void n
{
Ans. :_When a C program begins execution, the following data steams pointers to FILE
structure) will be automatically opened (these files are constants and not variables).
Name
c
f!
Meaning
stdin
if
stdout
stderr
stdaux
stdprn
aDEngineers.c
Compil
Mayuranand .C lasses
B403 I 407, Konark Darsllan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. il 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281
The output of a function like printf() goes to the stream stdout~ A function like
scanf() receives its input from the stream stdin. . We can write to any of the
output steams by using functions lie fputc(), fputs{) etc. and read from any of
the input streams by using functions like fgetc(), fgets() etc. These streams are
considered to be files. Usually, stdout and stderr are connected to the screen,
stdin is connected to the keyboard, stdaux is connected to the serial port coml,
and stdprn is connected to the parallel port lptl.
y similar to
:printf{) has
ototype is :
r a negative
f similar to
will send the output to the printer. If the printer is online, the number entered will
appear on the paper. Note the use of stdprn, instead of the pointer to the FILE
structure which is obtained through fopen. Since stdprn is already opened at the
beginning of program execution, there is no need to open it again.
Q. 9. What do you understan~ by low level disk I/0 ? Write a 'C.' function
to do low level copy of a file.
F if the end
the "end of
e to fit in a
::>n failure.
Ans. : In low level disk I/0, data can not be written as individual characters, or as
string or as formatted data, as is possible using high level disk I/0 functions.
There is only one way data can be written or read in low level disk I/O functions, as
a buffer full of bytes.
Writing a buffer full of data resembles the fwrite() function. However, unlike
fwrite(), the programmer must set up the buffer for the data, place the
appropriate values in it before writing, and take them out after reading. Thus, the
buffer in low level I/0 functions are very must a part of the program, rather than
being invisible as in high level disk I/0 functions.
Low level disk I/0 functions offer following advantages :
(1) Since these functions parallel the methods that MSDOS uses to write the
disk, they are more efficient than the high level disk I/0 functions.
end of file
: character
1ated be a
read. This
(2) Since there are fewer layers of routines to go though, low level I/0 functions
operate faster than their high level counterparts.
'C' program :
#include <stdio.h>
#include <stdlib.h>
#include <process. h >
void main(int argc, char *argv[ ])
!ams?
s to FILE
)les).
char ch;
fs = fopen(argv[l], "r");
if ( !fs)
{
printf ("Error ! ! Unable to open file in read mode ... \n");
:put)
Pg. 10
exit( G);
oDEngineers.colpg.u
Mayuranand Classes
8403/407, Konark Oarshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. V 32514726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. it 6517 3281
84
8216/21
The fi1
ft = fopen(argv[2], "w");
As sta
staten
type 1
subse
if( !ft)
{
printf ("Error !! Unable to open file in write mode .. . \n");
exit(O);
'The s
does1
r ope 1
wop
a ope
fputc(ch,ft);
fclose(fs);
Note
enclo
fclose(ft);
Wher
Wher
note
Whe1
A filE
If th
cont~
Con~
File
pl
target. txt
p2 =
.argv[ 1]
argv[2]
(opened
in . read
mode)
(opened
in write
mode)
The
resL
file.
filecopy
source.txt
argv[O]
Q. 10. What is meant by opening a data file ? What are different file modes ?
Ans. : If we want to store data in a file in the secondary memory, we must specify
certain things about the file, to the operating system. They include;
(1) Filename
Mar
r+
w+
a+
We
on,
Student.c
Text.out
Data structure of a file is defined as FILE in the l,ibrary of standard I/0 function
definitions. Therefore, all files should be deelared as type FILE before they are
used. FILE is a defined data type.
FILE *fp;
fp
= fopen
("filename", "mode");
Co
V 9517 3281
Mayuranand Classes
B403/407, Konark Oarshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. V 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. V 6517 3281
The first statement declares the variable fp as a "pointer to the data type FILE".
As stated earlier, FILE is a structure that is defined in the 1/0 library. The second
statement opens the file named filename and assigns an identifier to the FILE
type pointer fp. This pointer which contains all the information about the file is
subsequently used as a communication link between the system and the program.
The second statement also specifies the purpose of opening this file. The mode
does this job. Mode can be one of the following :
r open the file for reading only.
on the
When the purpose is 'appending' the file is opened with the current contents safe.
A file with the specified n~me is created if the file does not exist.
If the purpose is 'reading', and if it exists, then the file is opened with the current
contents safe; otherwise an error occurs.
After the
copied to
pl
= fopen("data", "r");
p2 = fopen("result"; "W");
The file data is opened for reading and results is opened for writing. In case, the
results file already exists, its contents are deleted and the file is open~d as a new
file. If data file does not exist, an error will occur.
Many recent compilers include additional modes of operation. They include :
modes?
:;t specify
r+ The existing file is opened to the beginning for both reading and writing.
w+ Same as w except both for reading and writing.
a+ Same as a except both for reading and writing.
We can open and use
on the system we use.
perating
with the
function
hey are
He. For
Pg. 12
oDEngineers.col
13
Pg.
y,:
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. if 3251 4726, 6525 7069,
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas,Sector 17, Vashi, Navi Mumbai. if 6517 3281
I:
.
~
i
!
!
8
B216/:
.
DATA STRUCTURES
CHAPTER 2 : LIST : ADT
Data are simply value or set of values. A data item refers to a single unit of
values. Data may be organized in man different ways; the logical or mathematical
model of a particular organization of data is called data structure.
The choice of a particular data model depends on two considerations :
The I
conv
ADT
(i) t
(ii) 1
(iii) I
(iv) I
1.
It must be rich enough in structure to mirror the actual relationship of the data
in the real world.
(v) I
2.
The structure should be simple enough that one can effectively process the
data when necessary.
The
stacl
SIZE
at st
To tt
is a
(top
Inse
stac
ImJ
#de
int
I* c
voic
+ LIST
I*
int
where, n > 0 and each ai is of type element type , The number n is said to be
length of the list. Assuming n > = 1, we say that a1 is the first element and an is
the last element.
+ . STACK
Q. 3. Explain the data structure stack. What are the different operations
performed on a stac.k ?
Ans.: A stack is a special kind of list in which all insertions and deletions take
place at one end, called the top. Other names for a stack are push_down list or
LIFO or last in first out list.
DEngineers.c
Co r
6, 6525 7069
bai.
a 6517 3281
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. S 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. V 6517 3281
The model of a stack is books on the floor or dishes on a shelf where it is only
convenient to remove the top object or add a new one above the top.
ADT in the stack family often includes the following five operations :
ng/e unit of
tathematica/
To test whether the stack is empty, we ask if (top <:: ~). If not, the topmost element
is at stack[top]. Checking whether the stack is full can be done by asking if
(top >= MAXISIZE 1). Initially, top should be set to 1, i.e., top= 1.
Insertion of element in a stack is PUSH operation and deletion of element from a
stack is POP operation.
Implementation :
leclaration
3 type. In
hide them
#define MAXSIZE 5
int stack[MAXSIZE], top= 1;
I*
~oid
I*
a stack *I
global declaration
*I
push(int x)
cs, where
elements
else
stack[+ +top] = x;
}
:ype. We
int t =
<)>;
1s take
1
return stack[top];
}
list or
Pg. 14
Pg. 15
May~ranand Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. W 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. tr 6517 3281
B
B216/~
+PI
void print_stack( )
C1
void
inti;
}
int
For array based implementation of stack, we define the abstract data type STACK
by
#define STACKSIZE 100
typedef struct
{
int a[STACKSIZE];
//a is a stack
int top;
} stack;
Now 'stack' is user defined data type.
To create a stack we have to declare a variable as follows :
stack s1;
0 1 2
members l
voi
99
'1111111
r..
L............... ~ . I~.
top
1100~~..
voi
1000 sl
(say address)
Q.
P > a[ ]
AI
(tl
p >top
FI
Cnrnnil.o,.. h,, o."f'
o~alf""h
c,....,~""'
........
~.
DEngineers.c
Cc
Mayuranand Classes
;525 7069
ff 6517 3281
B403 I 407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. ir 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281
C  Implementation
void push(stack *s, int x)
{
if (s >top>= STACKSIZE 1)
printf ("Stack overflow \n");
else
{
s > top++;
s > a[s > top] = x;
}
int pop(stack *s)
{
~STACK
int x;
if(s >top<= 1)
printf ("Stack underflow \n");
else
x=
s > top;
return
x;
}
}
{
s >top= 1;
}
{
i_nt i; . .
for (i = s >top; i >= 0; i.:.)
printf (" 0/od \n", s > a[i]);
QUEUES
DEngiDIIfS.C
Pg.
17
Mayuranand Classes
8403/407, Konark Oarshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai  80. ir 3251 4726, 6525 7069
8216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vaslii, Navi Mumbai..ir 6517 3281
B403
8216/217\
stack, the substantial difference be.ing that insertions go at end of the list, rather
than beginning and that traditional terminology for stacks and queue is different
ADT in queue family includes the following five operations :
sou
Set fron
1.
Empty'
Scenar
ENQUEUE(X, Q) : Insert element X at the end of the queue Q (i.e. at rear end)
4.
DEQUEUE(Q) : Delete first element of the queue Q (i.e. from front end)
QSIZE:
CIRCULAR QUEUES
Status
Condn
Seen a
(a)
max1 max2
2
In
thi~
Statu
Cond
Circular queue
Seen
to=~:Qax1
r
l .
.
Occupied
front
(a)
max2
rear
Unwinding
(b)
i= i
(c)
+ 1;
Cor= .........
I"\~
r"\.!L
.... _L_L __ _
DEngineers.c
Com
Mayuranand Classes
5525 7069
. ir 6517 3281
8403 I 407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. V 3251 4726, 6525 7069
8216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. tr 6517 3281
Iist, rather
s . different
BOUNDARY CONDITIONS
Empty or Full ?
Set front = ~ and rear = 1
Scenario Cil :
~ar
end)
QSIZE = 5
1d)
I
1
rear = 1 front =
' thinking
re added
:ail (rear)
;tay in a
:s of the
'Y is fully
Sce.nario {Ill :
(a)
I~
.i
1
1
front =
rear = 4
Q>
In this case, go no adding elements one by one till rear reached to QSIZE  1.
~cenario
(a)
{III} :
~~~
0
front=
(b)
(i)
add 10
(ii)
add 20
r.
(iii)
add 30
rear=
(iv)
add 40
Operations .:
~
2
r 1
front =
(c)
rear = 3
~~
l l
0
Operations :
Operations :
(i)
add 50
(ii) add 60
(iii) add 70
rear= front =
>g. 18
IP9.19
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, laver Road, Mulund (W), Mumbai 80. ir 3251 4726, 6525 7069
B216/217 Vardhman Chambers; Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. ft 6517 3281
84C
. B216/21i
OPI
. Q~ 6. E
Ans.:
C Cot
#defin1
Scenario CIVl :
(a)
int q[Q
Operations :
(i)
front=
!*
add 10
Alg ~
void cr
(ii) add 20
(iii) add 30
rear= 2
c1>
IXl
(b)
Operations :
(i) delete (Q), 10 is removed
l l
front = 2
I*
Als
void ir
{
rear = 2
==
rear) then
Conditions in I and III scenarios are same but decisions are exactly opposite.
Now if we look properly, both the scenarios are same i.e. front is followed by
rear.
1*
The expression is
int de
Al1
But above expression is true in Ist scenario too but queue is empty in this case.
Now let us make condition for FULL QUEUE and EMPTY QUEUE.
FULL QUEUE:
==
DEngineers.c
Com~
Mayuranand Classes
,6525 7069
ai. ir 6517 3281
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. tr 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. tif 6517 3281
#define QSIZE 3
int q[QSIZE], front, rear;
I*
*I
void create_queue( )
{
int front = Q>;
int rear= 1;
}
1))
owed by
}
} .
int x;
>case.
x = q[front];
if( front ! = rear)
front = (front + 1) 0/o QSIZE;
else
{
I* Q is now empty *I
create_ queue( ) ;
}
return x;
}
}
Pg. 20
aDEngineers.c
Pg. 21
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai  80. if 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. V 6517 3281
B
B216/~
CI
Func
!* Cr
(i)
void<
create queue
I* Fl
typedef struct
void
int a[QSIZE];
int front;
int rear;
.} queue;
Now 'queue' is user defined data type.
Declare a varieb1e of the type queue.
II q is a variable
I I qptr is queue pointer
queue q;
queue *qptr;
Memory Representation :
I* F
queue
1
front
,'
int d
rear
,r~
q 1000
I
I
qptr = &q;
I
\
\
\
'
'poooo
qptr
Com
Mayuranand Classes
6525 7069
li.. 6517 3281
B40~ /407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80.
C  Implementation :
nentation.
Functions:
{
q > front =
~;
I* x
*I
if(((q > rear+ 1) /o QSIZE == q > front) && ( q > rear> 1))
0
}
}
{
int x;
if(q >rear<= 1)
printf("Queue is Empty \n");
else
I*
I*
q > front
*I
= <1>;
q >rear= 1;
}
return x;
//end
else
}
22
Pg.
oDEngineers.c IP9.23
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80; W 3251 4726, 6525 7069
B216/217 Varqhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. ir 6517 3281
8B216/2
iiiiiiiiiiiiiii
Q. 9.
Ans.:
else
The
perfo1
one's
may I
a tim,
multi I
must
Many
inti;
if(q > rear<= 1)
printf("Queue is Empty \n");
+ 1) 0 /o QSIZE;
}
printf(" 0/od \n", q > a[i]);
I* end of else *I
Requ
than
pr
nE
se
'The
PI
PRIORITY QUEUE
Q~
Ans.: A priority queue is a collection of elements such that each element has
assigned a priority and such that the order in which elements are deleted and
processed comes from the following rules:
(i) An element of higher priority is processed before any' element of lower priority.
(ii) Two elements with the same priority are processed according to the order in
which they were added to. the queue.
Q. 11
Ans.
tom
(1)
(2)
There are various ways of maintaining a priority queue in memory. The ease or
difficulty in adding elements to or deleting them from a priority queue clearly
depends on the representation that one chooses.
(3)
The priority queue is a data structure in which the intrinsic ordering of the elements
d6es determine the results of its basic operation.
(1) I
There. are two types of priority queues : an ascending priority queue and a
descending priority queue.
An ascending priority is a collection of items into which items can be inserted
arbitrarily and from which only the smallest item can be removed.
A descending priority queue is similar but allows deletion of only largest item.
A priority queue can be represented by a binary tree. One of the methods is binary
tree sort Which uses binary search tree.
Infi~
We c
two
preo
Ther
can
prefi
..
Com~
Mayuranand Classes
8403/407, Konark Darshan, Above UTI Bank, laver Road, Mulund (W), Mumbai 80. tr 32514726,6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. 6517 3281
6525 7069
ai. a ss17 3281
I
print a file
send an email
Print server :
Maintains a queue of print jobs
';
Disk server :
Maintains a queue of print input
output requests
Scheduler :
Maintains a queue of processing awaiting a slice of machine time
nent has
eted and
Q.
riority.
Ans.: Three applications of stacks are presented here. These examples are central
to many activities that a computer must do and d,eserve time spent with them.
order in
( 1) Expression evaluation
(3)
lements
We are accustomed to write arithmetic expressions with the operation between the
two operands : a. + b or c I d. If we write a + b
c, however, we have to apply
precedence rules to avoid the ambiguous evaluation (add first or multiply first?).
nserted
binary.
There's no real reason to put the operation between the variables or values. They
can just .as well precede or follow the operands. You should note the advantage of
prefix and postfix: the need for precedence rules and parentheses are eliminated.
Infix
Prefix
Postfix
d by a
e root.
a+ b
+a b .
ab+
a+ b * c
+a*bc
ab c * +
:ree is
:d, the
(a + b) * (c d)
*+abed
ab+cd*
b*b4*a*c
40 3 * 5 + 1
Postfix expressions are easily evaluated with the aid of a stack.
Pg.
24
IP9.2s
Mayuranand Classes
8403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. ir 3251 4726, 65257089
B216/217 Vardhman Chambers, Above UTf Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai.
6517 328'1
840:
B216/217
Each pr
contain
(4) Replace the two operands and operator ~ith the: calculated value (three
symbols are replaced with one operand)
(5) Continue scanning until only a value remainsthe result of the expression
A more formal algorithm :
create a new stack
while (input stream is not empty)
{
token = getNextToken();
if (token instanceof operand)
{
push(token);
}
opl =pop();
lose'
Jose~
the~
push( result);
cave
prefe
arOU I
keen
return pop();
Demonstration with 2 3 .4 +
In tl1
*5
are
mth
(2) Backtracking:
Backtracking is used in algorithms in which there are steps along some path (state)
from some starting point to some goal. Find your way through a maze. Find a path
from one point in a graph (roadmap) to another point. Play game in which there
are moves to, be made (checkers, chess).
In all of these cases, there are choices to be made among a number of options.
the
occu
mbe r
plac
Now
plac
1 need
to
wee
y=
Consider the maze. At a point where a choice is made, we may discover that the
choice leads to a deadend. We want to retrace back to that decision point and then
try the other (next) alternative.
Again, stacks can be used as part of the solution. Recursion is another, typically
more.favored, solution.
aasl
posi
vaiL
WOL
obtc
For
fin a
the1
The
ma'
,....~'
L ..
"'1!
n_.:. __ ._ n..&..l
n
"\C
oDEngineers.col
ColT
525 7069
it 6517"3281
Mayuranand Classes
8403/407, Konark Darshan, Above UT18ank, Zaver Road, Mulund (W), Mumbai 80. R '3251 4726, 6525 7069
8216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. R 6517 3281
Each program that is running in a computer system has its own memory allocation
containing the typical layout as shown below.
Object Heap
operands
ue (three
Unused
Memory
;sion
,,
,
,,
,
,,
,,"
Method n
. Activation Record
,
,,
,,
,
,,
,,
Parameters
Method 3
Activaticm Record
Call
Stack
Return Address
. (PC value)
Method 2
Activation Record
Static vars
...
' ...
' ...
''
Byte codes
OS
JVM
Method 1
Activation Record
'
Local vars
....... ...
.......
Previous base
pointer
~eturn
value
Program Counter
(state)
a path
1 there
ptions.
eed to
at the
then
'ically
!mory
~rs, a
~ etc.
Pg. 26
In the general case n men are arranged in a circle which is closed up as individuals
are picked out. Beginning anywhere, we continually go round, picking out each
mth man until only r are left. Let one of these be the man who originally occupied
the pth place. Then had we begun with n + 1 men, he would have originally
occupied the (p + m)th place when p + m is not greater than n + 1, and the (p +
m  n  1)th place when p + m is greater than n + 1. Thus, provide_d there are to
be r men left, their original positions are each shifted forwards along the circle m
places for E!ach addition of a single man to the original group.
Now supp,pse that with n men the last survivor (r = 1) occuple,d.: originally the pth
place, atid that witt)..n + x men the last survivor occupied the Yth place. Then, if
we COnfine OUrseiVe$tO the lowest value Of X which makes y less than m, we have
y
p + mx)  ( n + x).
=(
Based on this theorem we can, for any specified value of n, calculate rapidly the
position occupied by the last survjvor of the company. In effect, Tait found the
vaJues of n for which a man occupying a given position p, which is less than m,
would be the last survivor, and then, by repeated applications of the proposition,
obtained the position of the survivor for intermediate values of n.
For instance, take the Josephus problem in which m=3. Then we know that the
final survivor of 41 men occupied originally the 31st place. Suppose that when
there had been (41+x) men, the survivor occypied originally the yth place.
Then, if we consider only the lowest value of x which makes y less than m, we have
y
(31 + 3x)  (41 + x) = 2x  10. Now, we have to take a value of x which
makes y positive and less than m, that is, in this case eoual to lor 2. This is x = 6,
aDEngineers.c
9 27
'
Mayuranand Classes
B403/407, Konark Oarshan; Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. il 6517 3281
B4C
B216/21i
meh,
wl
r = 1;
!** e
queue[r]
main I
= i; .
{
inti;
e;
i
= queue[ f);
f++;
if (f >=MAX)
f = 1;
. return i; .
}
{
register inti;
e = n;
for (i
= 1; i <= n;
i++)
queue[i] = i;
= 1;
r, = n;
II
II
i = 1;
Com
.
;525 7069
6517 3281
Mayuranand ,Classes
while ( e ! = 1)
sen would
the
the same
L Hence,
~men,
if(i != v)
place.
i++;
insert( remove());
}
else
{
remove();
i = 1;
}
}
I**
**I
main( )
{
int n, m, p;
clrscr(); .
printf ("Enter numbers of sol ... \n .. };
scanf (" 0/od", &n);
printf ("Enter value of m \n");
scanf {" 0/od", &m);
p = josephus(n, m);
printf ("The last man survived was at position no = 0/od \n .. , p);
putchar ('\n');
return 0;
}
vor
*/
Pg. 28
oDEngineers.col
Pg. 29
Mayuranand Classes
B403 i 407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80 ..if 32514726, 6525 7069
8216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, NaviMumbai. ir 6517 3281
DATA STRUCTURES
CHAPTER 3 : LINKED LIST
BB216/2
LI
Data
One
disad
C provides powerful facilities for processing pointers and standard functions for
requesting additional memory and for releasing memory during program execution.
Fore
( i) I'
~
(ii)
. ~TATIC AND
DYNAMIC VARIABLES
Anot
a fie l
in th
merr
of de
Lin~
whe
into
secc
next
+I
Note that if static variable is declared within a function, then spa.ce is allocated
when the function executes and is destroyed when function terminates whereas if a
dynamic variable is created in a function, then it can continue to exist even after
function terminates.
'C' NOTATION
'C'
char *p;
If node denotes the type of items in which we are interested, then we declare a
pointer type that is bound to type node with the declaration :
c
ty~
} node;
node *q;
}
ty
Ans.: The creation and destruction of dynamic variables is done with standard
functions in 'C'. Ifp has been declared as a pointer to type node, then the statement
= (node*) malloc(sizeof(node));
creates a new dynamic variables of type 'node' and assigns its location to the
pointer p. The library function malloc allocates a block of memory or it returns
NULL if there is not enough space. .
,
When a dynamic variable is no longer needed, the function call free(p); returns the
space used by the dynamic variable to which p points to the system.
DEngineers.c
c
Mayuranand Classes
6, 6525 7069
)8i. 2 6517 3281
B403 I 407, Konark Darshan , Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. ir 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. ir 6517 3281
LINKED LIST
Data processing frequently involves storing and processing data organized into list.
One way to store such . data is by means of array but arrays have certain
disadvantages.
Jnctions for
' execution.
For e.g.
(i) It is relatively expensive to insert and delete element in an array.
(ii) Since an array usually occupies a block of memory space, one cannot simply
double or triple the size of an array when additional space is required. For this
reason, arrays are called static data structure.
>me in two
1ile writing
1 they are
;tatic; the
heir space
program
lpiled, but
Another way of storing a list in memory is to have each element in the list contain
a field, called a link or a pointer, which contains the address of the next element
in the list. Thus, successive element in the list need not occupy adjacent space in
memory. This will make it. easier to insert and delete elements in the list. This type
of data structure is called a linked list.
linked list or oneway list a linear collection of data elements, called nodes,
where the linear order is given by means of pointers. That is, each node is divided
into two parts : the first part contains the information of the element and the
second part called the link field or next pointer field, contains the address of the
next node in the list.
~n.
s created,
like any
allocated
ereas if a
ven after
1cter, we
Information I
data field
eclare a
C Declaration
typdef struct node_tag
{
data <data_type>
link <pointer>
} riod.e;
Ex.:
typedef struct node_tag
andard
ement
{
int data ;
struct node_tag
link;
to the
eturns
} node;
ns the
Pg. 30
aDEngineers.c
Pg. 31
Mayuranand Classes
8~403/
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W),Mumbai 'SO:. jil3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vaihi, Navi Mumbai. if 6517 3281
B216/217 Vc
INSE
Assume
data
START
~~,
link
data
link
d:qta
link
data
link
11 ! I  [ Fj La
.+.
header
node
node
node
node
tail
Case 2
case 3
irit'data;
Case 1
(Start \
} node;
G
St
I* AI go to release a node *I
void freenode(node *p)
{
free(p);
}
TRAVERSE OPERATION
To traverse means to visit every node of a linked list once. While t raversing we
may do any operation on a node like printing data value of ea ch node or modifying
contents of node etc.
Case
GQ
Stc:
+ D
A gi\
Orig
Ex
Cor
6525 7069
3i.
6517 3281
Mayuranand Classes
8403/407, Konark Darshan, Above UTI8ank, Zaver Road, Mulund (W), Mumbai 80. V 3251 4726, 6525 7069
8216/217 Vardhman Chambers, Above UTI8ank; Nr 8abubhai Jagjeevandas,, Sector 17, Vashi, Navi Mumbai. V 6517 3281
+
ink
~tail
INSERT OPERATION
5!
~1
Start
2001+11112
100
200
300
400
in~erted
GDc::1o ~j12l3ool~~
.
Start
50
~ew
100
200
300
400
node
~1
Start
s ;2o9~!1sl4ooj~
100
200
300
400
rsing we
1odifying
~is ~ooj~~start
100
200
300
new node
DELETION OPERATION
...~.
.
GQ:>1s ~ooj~~~
Start
100
200
300
400
~:
~
Start
Pg. 32
:4oo~~~
js :3ooj11o
100
300
..
lNuLLJ
400
oDEngineers.col
Pg. 33
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai  80 ..if 3251 4726, 6525 7069
B216/2.17 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. V 6517 3281
B403
B216/217 \i
Some o
I*
A fur
Say star
(a)
B,
SEARCH OPERATION
I*
1st
2nc
void ~~arch(i'1t x)
' 'i!.
'
{
A
= start;
= NULL)
printf("Node is present\n");
else
(b)
printf("Node not found \n");
I*
int node_count()
{
node *tra;
int .cnt =
cp;
tra = start;
\. lOC
while(tra ! = NULL)
star
cnt++;
tra = tra > link;
void c
return cnt;
Note:
If start is declared as local to main function, then it must be initialised to NULL,
before linked listis created.
For every procedure, start should be passed as a reference parameter because
sometime start may be modified.
create.Jist( ) function now should be called as below :
create_list(&start);
II
reference parameter
Co
DEngineers.c
Comp
3, 6525 7069
~ai. ir 6517 3281
Mayuranand. Classes
B403/407, Konark Darshan, Above UTI Bank, laver Road, Mulund (W), Mumbai 80. e 3251 4726, 6525 7069
B216/217Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. it 6517 3281
Before combination :
~.Empty list
2nd
Before
Combining
list~~~
start:2
100
300
After Combination
1100
1~
/Is
start!
:2001
100
7 :3oo
200
14
:NULY
300
~tart2
(b)
Before combination :
First list
~Is
1ooj
startl
Second list
:2001
100
~is
400
start2
'17 :NUL~
110 : 3001
200
l sooj
~~2
300
:NULL'
400.
After combination :
startl
First list
+,
Second list
+
node.: *tra;
if(*startl
==
NULL)
*startl
to NULL,
= start2;
else
because
tra = *startl;
while(tra > link != NULL)
tra = tra > link;
tra > link = starti;
}
}
Pg. 34
Pg. 35
Mayuranand Classes
8403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. 9'3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, NrBabubhai Jagjeevandas, Sector 17, V~.~~~ N~vi Mumbai. if 6517 3281
840
8216/217
'top' co
Initially
1100rt 1+1
~+ljlolNuLy
"2~~
sta
~~~
Let us,
300
LINKE
type de
} nod1
void reverse_list( )
node:
!*fun
node * t1, *t2, *prev;
node
prev =NULL;
t1 = start; .
while (tL!~ NULL)
t2 = t1 > link;
/* fu
void
prev = t1;
t1 = t2;
}
start = prev;
}
I* A
1.
2.
{
int data;
struct node tag *link;
} node;
... As with the entries of contiguous stack (i.e. array stack), we shall push and pop
,nodes from one end of linked stack, called its top.
3.
LINKED STACK:
top pointer
NULL:
4.
sl.~11oo
.
: 91i'f'   .___
1_4__,1
100
200
300
first node
second node
third node
Mayuranand Classes
)525 7069
.a 6517 3281
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund {W), Mumbai 80. V 3251 4726,6525 7069
8,216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. il 6517 3281
{
int data;
struct node_tag *link;
} node;
I I Global deciaration
I* function to get a new node *I
node *top;
node *getnode( ) .
{
1.
NULL
top
~,.jNuLLl
sl
top
nd pop
.____2_oo___.L,
top
[N"uLLl
',
sj~....,._.... J100
....... ________
100 _
l1l
200
....
I NULLl sj
... __ 100
 
i 91
~
Pg. 36
aDEngineers.c
Pg. 37
M~yuranand
Classes
840~ f.407., Konark Oarshan, Above ufrBank, Z.aver Road, Mulund (W), Mumbai 80. ir 3251 4726, 6525 7069
B216/217'\tardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 11, Vashi, Navi Mumbai. V 6517 3281
B403 J
8216/217 v
void push(int x)
I* x 
*/
}
node *nptr;
nptr = getnode( ) ;
if(nptr = = NULL)
+ LINI
Linked 1
two poi1
of the q
else
{
.J1ptr > data = x;
Node st
typedef
top = nptr;
}
}
I*
.... ....
,,~
~~

NULL: 5
300

} node
...
As wit!
from 'r
... ......
100
top
~
200.
300
LINKE
1. pop a node

I 20~<1
100
top
200
f
'NULL:
91
deleted node
2. pop a node
,,
,, .......
,
....
... ...
[
...
~'~~
NULLl
,
100
sl
100 '
top
To en
'NULL:
71
front
deleted node
Sim~
3. pop a node
NULL
!NuLL:
top
I* de
I* AI
sl
deleted node
1. (
2.
node *t ; int x;
t = top;
if(top = = NULL)
printf("Stack is EMPTY \n .. );
else
x = t > data;
Compiled by Prof. Rajesh Bothra
Pg. 38
oDEngineers.col
Corr
Mayuranand Classes
i, 6525 7069
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. tr 32514726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. V 6517 3281
Linked queues are just as easy to handle as are linked stacks. We need only keep
two pointers, front and rear, that will point, respectively, the beginning and the end
. of the queue.
Node structure is as below :
typedef struct node_tag
{
int data;
LINKED QUEUE :
To create a
queue~
2.
NULL
NULL
front
rear
front
~ ~ .....,
. .
rear, ~
Pg. 38
Empty queue
Is
100
Pg.39
Mayuranand Classes
8403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. ti 3251 4726, .6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. il 6517 3281
3.
1. dele
front
100
front
200
200
rear
840
8216/217
rear
t'::J :I
4.
Insert'..third node
2. del
'
front
~.1_0_.;.'0__,t.,....j_
5 : 200
1~:~...
100
first node
___
fror
second node
re<
300
rear
void insert(int x)
3. de
fro1
re,
if(nptr = = NULL)
printf("Unable to insert non existent node \ n");
else
int d
I* node is .created *I
II Empty queue
I I first node
else
{
rear> link=, nptr;
rear = nptr;
}
}
}
rear
300
a linked queue
*1
[9
:NUll]
___/
r~
Q.
Ar
be
so
th
DEngineers.c
Co
Mayuranand Classes
8403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. ir_3251 4726, 6525 7069
8216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. ir 6517 3281
6, 6525 7069
bai. ir 6517 3281
1. delete a node
js
front
j1oo
7 : 300
deleted node
rear
300
200 _ _ _ _  / 300
~~
2. delete a node
front
deleted n : _ _ / 300
fe
rear
300
3. delete a node
front
NULL
9
rear
300
deleted
node
300
int del_node( )
{
int x;
node *nptr;
== nptr)
if(front ==
if( front
NULL)
nptr = front;
x = nptr > data;
Ans.: In singly linked list ( 1,way list), we used to traverse every time from
beginning until the desired node is found for carrying out operations, but this
solution is generally unsatisfactory. Running time of the program will depend on
thP IPnnth nf thP lic:t whirh
Pg. 40
m~v
hP nt titP lnnn
Pg.
41
Mayuranand Classes
8403 I 407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80 ... if 3251 4726, 6525 7069
.a216/217 Vardhman Chambers, Above UTIBahk, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. ir 6517 3281
B403
B216/217 \J
As node of singly linked list contains address of next node, it is not possible to
return back to previous adjacent node. The above problem can be solved by
keeping 'two links' in each node, .pointing in opposite directions. Hence, by
following the appropriate link, we can move either direction throug~ the linked list
with equal ease. We call such a list a Doubly Linked List.
void free
fn
}
TRA
void fwc
{
....~
*prev
(pointer /link field)
 To store address of
previous node
information field
{
Cdeclaration :
}
/* funct
int data;
struct node_tag
~prev,
void bk.
*next;
} node;
t
v
13oo ~:::::::'~~
200
first
To point first node
last
To point last node
+
Cimplementation :
INS
A giver
#include <stdio.h>
typedef struct node_tag
{
int data;
struct node_tag *prev, *next;
} node;
/*function getnode( ) * /
node *getnode( )
{
return (node*) malice (sizeof(node));
Case 1
Case 2
Case 3
I* function freenode( ) *I
Compile
Mayuranand Classes
1525 7069
ii' 6517 3281
8403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai. 80. V 3251 4726, 6525 7069
8216/217 Vardhnian Chambers, Above UTI Bank, Nr Baqubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. R 6517 3281
>ossible to
solved by
ience, by
linked list
free(p);
}
TRAVERSE OPERATIONS
void fwd_traverse( )
{
node *tra;
tra
= first;
while(tra ! = NULL)
{
= tra
> next;
}
/* function to traverse in backward direction
void bk_traverse( )
{
node *tra;
tra = last;
while(tra != NULL)
{
printf(" 0/od \n .. , tra >data);
tra = tra > prev;
}
ode
INSERT OPERATIONS
first
last
.\ .
Case 1 : New node is inserted as first node, then first will be modified.
Case 2 : Ifn.ew node is inserted as last node, then last will be m.odified.
Case 3 : New node may be inserted between two nodes.
               
Pg. 42
aDEngineers.c
Pg. 43
. Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai  80. R 32614726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi~~mbai. R 6517 3281
....
.,.,. .,.
:'I I
N
',,
...
.
3 1100
so
case 1 :
=3
'
'
~
,
so
,./
I5
100
200
300
last
first "'edified
Case 2: Say data value
Is
Case 2
=25
, ,.
!2oo
)
.
....300..,
,, ........
''
)
': '
100
200
300
', ...
........
400
new node1
first
I.5
...
4oo
,. /
. last modified
1200
Case~
= 18
~ 100 1151250
100
200
.,. ..,.
 .... . ..
t8 200118130~ .~
250 1_20_1...N )
300
new node
400
start
last
DELETE OPERATIONS
To delete
B403
B216/217 ~
c
+ c
A cir
havir
Wet
that
Case 1 : Node to be deleted may be first node, then start will be modified.
Case 2 : Node to be deleted may be last node, then last will be modified.
Case 3 : Node to be deleted may be neither first nor last node.
An existing linked list :
first
Downloaded tram
last
FaaDoDEngineers.col
Con
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. til 3251 4726,6525 7069
B216/217 Vardhman Chambers, Above. UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai..If 6517 3281
first
= 5 to
be deleted
find
last
modified
st
first
last
modified
. find
= 10 to be deleted
~).
deleted node
]
first
find
last
A circular linked list is a list in which the node at the tail of the list, instead of
having a NULL pointer, points back to the node at the head of the list.
We then need only one pointer tail to access both ends of the list, since we know
that tail > link pointer back to the head of the list.
)
Pg.44
tail
oDEngineers.col
p;4s
Mayurariand Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80 .. ii 3251 4726, 6525 7069
B216/217Vardhman Chambers, Above UTI Bank, Nr Babubhpi Jagjeevandas, Sector 17, Vashi, Navi Mumbai. V 6517 3281
B403/407
B216/217 Vardh
I* Algo tot
void
traver~
node
int data;
tra =
whilE
} node;
II Global variable
I* function getn9pe( ) *I
node *tail;
node *getnode( )
}
prin1
I* C  Implementation *I
void create_cll( )
{
node *nptr;
char ch;
printf("Want to create a list (Y/N) \n");
scanf( 110/oc", &ch);
while(ch === 'Y')
{
I I list is Empty
tail = getnode( );
printf("Enter data value \n 1' ) ;
scanf(" 0/od", tail > data);
tail > link = tail;
}
else
{
curr = getnode( .) ;
printf("Enter data value \n 11 ) ;
scanf(" 0,bd~',
}
}
I I end while
//end algo
Compiled t
Mayuranaa:d Classes
, 6525 7069
ai. V 6517 3281
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. tt 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, NaviMumbai. tt 6517 3281
node *tra;
tra = tail > link;
while(tra ! = tail)
{
printf{" 0/od\n", tra > data);
tra = tra  > link;
}
. :. s~
Pg. 46
Mayuranand Classes
8403/407, Konark Oarshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai  80. if 3251 4726, 6525 7069
8216/217 Vardhmart Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281
A node stand
DATA STRUCTURES
Consider Fig.
example, it i
root node (l,;
parent of M c
INT~ODUC"rJ;<>N
I I
.
n
_
::J
(2) Degree
It is an
inte~
defined as r
node A is4,
Degree of K
(3) Leaf
The nodes
1 Li(~~;a~:~as:!~~~t~re
B403/407, I<
B216/217VardhmE
leaf I terrT
queue)
~~L_L_]
L_D
200
300
100
(4) Degre4
Linear data
structure (Singly
linked List)
Degree of
of a given t
(5) Level
Level of a
then it has
Node K, J,
(6) .H eigh
Height o1
level in tht
(7} Subtr
Level
Subtree i
original tr.
Example
Level
Level
Level
Pg. 48
oDEngineers.co
Compiled
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. B 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. tr 6517 3281
6, 6525 7069
bai. tr 6517 3281
A node stands for the item of information and branches to other nodes.
Consider Fig. 1, having 21 nodes, each node is having same information and in this
example, it is having an alphabet as an information. Here, we say that node A is
root node (ultimate parent of all nodes) Node B, C ... are parent node. (Ex. C is
parent of M and D). Moreover, M and D (siblings) are children of C.
)N
linear data
leks, queues
l , these data
msional. In
i.n which one
TerminaiNodes:
The nodes with zero degree or nodes having no child. Nodes further are called
leaf I terminal node.
( 4) Degree of a Tree :
Degree of a tree is nothing but the maximum degree of a node in a tree. Degree
.of a given tre~ is 4.
to represent
tion within a
s well one, if
on, then we
scheme will
relationship
rmation in a
3ta structure
:>ns.
.. ;
of nodes in
e remaining
1 T1 is a tree.
Pg. 48
oDEngineers.com
49
Pg.
Mayuranand Classes
W 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector.17, Vashi, Navi Mumbai. W 6517 3281
B403/40i
B216/217 Vardr
Another k
Nodes to 0 1
8~403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80.
The most important tree structure is a Binary tree, which occurS, :quite often in
applications. In this type of tree, any node . will have atmost twb b@n~h~. That is
binary tree is cha_r:t;3cterized by the. fact that any node WTff"fl'avetdegree at most two.
In general tree (Fig;l), we neverbothered about the number of branches, however,
in binary tree, each node has maximum of two branches. Binary tree can be
represented as follows :
(9) A Col
Parent
Node
Leaf I
terminal
A complet
and everv
I
I
A Binary tree is an empty tree or it is finite set of nodes with root and two disjoints
trees called left subtree and right subtree.
Address field
(To store
addres$eS
of right child)
+rI
I
I
I
Definiti
It is also
Note: I
(11) St
Data/Information field
. A n"'ary
int data;
n child1
Strictly
leaf pat
Tree is
Binary 1
Tree if
Let us c
at least
longer t
node;
The fig1
,._ _
____ ! I. _ ..J
L .
"'   ~
""' . !   L
Compile
~  J... L . 
oDEngineers.CD
Mayuranand Classes
;, 6525 7069
18i.. 6517'3281
B403/407, Konark Darshqn, Above UTI Bank, Zaver Road, Mulund (W). Mumbai 80 .. V 3251 4726, 6525 7069
B216/217 Var~hman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. V 6517 3281
Jite often in
~he._?. That is
rt most two.
~s, however,
:ree. can be
~ight
Child
Node
No disjoints
A n"'ary Tree is called strictly nary Tree if every nonleaf node in a nary tree has
n children each. A strictly nary Tree of dep~ d, then can be de.f ined as a
Strictly nary Tree that has at least one root to lea.f path of length d, and no root to
leaf path in that tree is longer than d.
The figure below shows the 3 different strictly binary trees of depth 2.
~
Pg. SO
oDEngineers.co
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. 1ii 32514726,6525 7069
B216/217 Vardhman yhambers, Above UTI Bank, NrBabubhai Jagjeevandas, Sector 17, Vashi, Navi Mum,bai. .'if 6517 3281
B403/4(
8216/217 Varc
Function
A binary search tree is a binary tree which may be empty or should fulfill the
following criteria.
void init_tl
All thenodes lying .to the left of the root node must have data value (key value)
less than the data value (key value) of the root node.
All the nodes lying to the right of the root node must have data value (key
value) greater than or equal to the data value (key value) of the root node.
tptr
}
Function
node *get
{
ret1
}
Function
void freer
{
fre
}
Q. 2. Wr
Ans.: Fu
int searc
{
I*
nc
if
Search
i)
u) Tree Traversal
iii) Insertion
h~)
Creation
el
v}. Deletion
BinaryTreeADT
typedef struct node_tag
{
int data;
struct node_tag * left, * right;
}
node;
{
node* root;
tree;
}
Cc  
"'J
I
Com pi lee
Mayuranand Classes
7069
6517 3281
8403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. tJ 3251 4726, 6525 7069.
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector .17, Vashi, Navi Mumbai. 'R 65173281
{
'value)
1e (key
tptr
root .= NULL;
e.
Function to Create a Node
node *getnode()
{
free(p);
}
/* x
7
*I
node *find;
if (tptr
{
root = = NULL)
}
else
{
if (x = find
7
data)
return 1;
/*successful search/*
else
if (x < find
data)
}
Pg . 52
right;
/* end of while */
return <j>;
/* unsuccessful search,* /
}
/* end of function*/.
oDEngineers.co
~53
.,.,_
Mayurana,nd Classes
~03f"407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W}. Mumbai 80. if 32514726,6525 7069
B216/217 Yjirdhma~ Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas~ Sector 17, Vashi, Navi Mumbai. tl 6517 3281
B403/40"
B216/217 Vardt
Recursive Function :
Function f
void preorc
if (tr
if (find.== NULL)
return 0;
/*unsuccessful search */
else
find~
if (x ==
data)
return 1;
/*successful search */
}
}
else
if (x < find
data)
~
Function
left, x);
void postc
else
return search
(find~
right, x);
if (
{
/
. . ~TREE TRAVERSAL
"
}
}
Q.4.DE
Ans.:
L.
~hild (L)
Left,Child..{_l:)__
~rent Traversajs are VLR, VRL, LVR, LRV, RLV and 'RVL. But, as per the
convention, right node should not be visited before a left node, therefore, the valid
tree traversal are :
VLR
...
LVR
: s . .
{
if (tra ! = NULL)
{
inorder(tra
left);
inorder(tra
right);
/* go to left node
I* visit a node *I
I* go to right node */
Notet
node f
Step:
Step:
Step:
}.
Step
Step
Crr"W"t.r'\.il""""",... . . .
Tt.l
o. .~. o"'
D1L...
Com pi I
)25 7069
6517 3281
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. It 3251 4726, 6525 7069
8216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. tr 6517 3281
if (tra ! = NULL)
{
data);
*I
/* go to left node * l
/*visit a node
right);
}
}
Function for Postorder Tree Traversal :
postorder(tra
. postorder(tra
Inorder,
l* go to left node *I
left);
~right);
data);
}
je)
0.2
97<YOO
select left .
lild (L)
X=
find
s per the
= 0.4
. the valid
\
\
e
\
. New Node
Tree after Insertion
Note that, new node will always be inserted as leaf node on ly, so .to insert a new
node following steps are to be followed~
Pg. 54
Step 1
Step 2
Fill a nod by a data value and initialize left and right link by NULL.
Step 3
Step 4
Attach a node.
Steo 5
Finished.
oiEngineers.col.
Pg. 55
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulu~d (W), Mumbai 80. R 3251 4726, 6525 7069
B216/217 Vardhrhan Chambers, Above UTI Bank, Nr Babubhai Jagjeevatldas, Sector 17, Vashi, Navi Mumbai. if 6517 3281
void insert(tree
*~ptr,
B403/4(
B216/217 Varc
Q. ~Writ
int x)
Ans.: Alg
Step 1
. newnode = getnode()
Step 2
newnode
data = x;
newnode
left = newnode
right = NULL;
=newnode;
tptr ~ root
else
{
find = tptr
root;
follow = find;
if (x
<find~
data)
find = find
left;
find = find
right;
else
}
if (x < follow
data)
I*
I*
end of else
end of function
right= newnode;
Cases tc
*I
*I
1.
Er
2.
Lc
root
Ans.:
{
int x.;
char cb;
(Root as
leaf nod,
}
}
Compiled by Prof. Rajesh Bothra
..
Pa. 56
DEnginears.c m
Compilet
Mayuranand Classes
16525 7069
3i. tl 6517 3281
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. tl 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. B 6517 3281
Step 2
Replace a node by its right child (if exist) and reattach a left child
(if exist) at the leftmost node of the right subtree of the deleted node.
Node to be
deleted
Cases to be considered :
1.
Empty tree
2.
Leaf Node
root
~
root
root
A
== '
::
(Rootas a
leaf node)
, ; ,
node to be
deleted
(leaf node, left child of its parent) _ (leaf node, right child of its parent)
Pg. 56
DEngineers.c
Pg. 57
Mayuranand Classes
8403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80._if 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. ir 6517 3281
3.
Left Skewed
(~()de
void del_n
Root
Root
CJ
CB
B403/4{
B216/217 Varc
nod
if (t
else
{
I
I
I
I
I
/
~
(Root node
having left child
but no right child)
4.
Right Skewed
Root
GD
.
.
. . ,.'
.
(~ode
(Non~root,
right child
of its parent node)
Root
CID
GD
I
I
0
Root Node
5.
Root
Root
GD
Root node
(Nonroot, left
child of its parent)
(Nonroot, right
child of its parent)
Compile
Mayuranand Classes
6525 7069
i. w 6517 3281
8403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. tl 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281
It
== NULL)
if (tptr ~ root
{
/*tree exists
find = tptr
*I
~root;
data)
{
follow = find;
if (x < find
find
ght child
t node)
data)
= find
left;
else
. find = find _,_, right;
}
*I
== NULL)
if (find
== tptr ~
root)
==
root
=NULL;
==
NULL))
else
if (find ~ left = = NULL)
tptr
of its parent
root = find
right;
else
if (find
right = = NULL)
tptr ~ root
=find
left;
else
{
tp~r ~
left;
}
}
/*end if
*I
else
t, right
parent) _
/* nonroot to be deleted
Pg. 58
*I
left
= find)
oiEngineers.col
Pg. 59
Mayuranand Classes
8403 /407, Konark Oarshan, Above uTI Bank, Zaver Road, Mulund (W), Mumbai 80. if 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, ~r Babubhai Jagjeevandas, Sector 17, Vas.~i, Navi Mumbai. tl 6517 3281
follow
left = NULL;
B403/40
B216/217 Vard
Q. 8. Writ1
else
Ans.: Fun
follow
right = NULL;
void leafno
else
{
~
if (find
if
left = = NULL)
(follow~
stati
left== find)
~
follow
left = find
if (tr
~
right;
else
follow~
else
~
if (find
if
right ==NULL)
(follow~
left == find)
= find .~
follow
left
follow
right:
left;
else
= find
left;
Q. 9. Gi\1
INORDEF
else
Ans.:
hold = find
l>
right;
while (hold
left != NULL)
hold = hold
hold
left =
if (follow
left;
J>
find~
left;
l.eft = = find);
follow
left = find
right;
right;
else
follow~right
= find
Q. 10. Gi
freenode(find};
/*end else
}
I*
I*
IN
*I
p~
end det_node
Ans.:
*I
I nor
Pre<J
I*
*I
if (tra ! = NULL}
Delete'[
find its p
{
cnt++;
nodecount (tra
left);
}
}
Compiled
7069
3517 3281
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. ir 32514726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. tl 6517 3281
{
.static int cnt = <j>;
if (tra ! = NULL)
{
if ( (tra + left
== NULL)
== NULL)
cnt++;
leafnodecount (tra + left);
leafnodetount (tra + right);
}
}
PREORDER
: ABCDEFGH
DCABFEHG
Ans.:
?
Inorder
Preorder
G
1
Delete 'D' from PREORDER which is root node and then search 'D' in !NORDER and
find its position push right and then left range of array into stack.
Pg. 60
Mayuranand Classes
B403/407, Konark Oarshan, Above UTIBank, Zaver Road, Mulund (W), Mumbai  80...if 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTLBank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. it 6517 3281
B403/40.
B216/217 Vardt
Preorder
void preorc
{
nodE
int t
tra
whil
{
4
3
2
13
L D
S8
RD
s
Q. 11. Give the nonrecursive routines for inorder and preorder tree
traversal.
Ans.: Non Recursive Algorithm For Tree
Traversal~
Inorder Traversal
void inorder(tree *tptr)
{
}
!*
= 1;
int top
= tptr ~ root;
Q. 12. G
construe
Ans.:
inti;
node *cr
stack [++top] = tra;
tra = tra
nc
left;
ini
if
while (tra
~data);
right;
==
{
tra = stack [top];
printf (" 0/od \n", tra ~data);
tra = tra
right;
}
}
}
/*end of inorder*I
Compiled
Mayuranand Classes
25 7069
i' 6517 3281
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. ir 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. V 6517 3281
Preorder Traversal :
void preorder(tree *tptr)
{
node
~tra,
*s[ 10];
7
root;
7
data);
s[ ++top] = tra;
tra = tra
7
Ieft;
}
tra = s[top];
ter tree
tra = tra
7
right;
7
right;
}
}
}
/* end of preorder
*I
Q. 12. Given Preorder and lnorder traversal of the tree, write a routine to
construct a binary tree.
Ans.:
inti;
node *create(int I, int r)
{
node *nptr;
int pos;
if((l <= r) && (i <= n))
{
nptr = getnode();
nptr
7
data = pre[i];
*I
i++;
nptr
7
nptr
7
return n ptr;
}
else
{
return NULL;
}
/* end create *I
}
..
Pg. 62
'g. 63
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai  80. ir 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. fir 6517 3281
B403/4(
B216/217 Vard
In recursive algorithm, stack memory is consumed (utilized) for storing the address.
of the parent node. As we know that each nod~ of a tree is having 2 addresses field
to storing address of left and right subtree'. Therefore, for a tree., having 'n' nodes
will be having total (2 * n) address field.
So if we talk about utilized links so out of (2 * n) links, we utilized only (n1) finks
because address of root node is stored in a dedicated pointer (i.e. root points).
..
= (2 * n) (n ~1) = n + 1
Let's utilized these NULL links for storing address of successor qr predecessor
nodes. Normally, right NULL .link is used for storing address of successor node and
left NULL link is to be used for storing address of predecessor node,
To impler
logical fie
right prin
Right Tt
Node RE
Right most
NULL link
if
if
:. NULL links = 15
Given Bin~ry Tree
Left Th
NULL let
Node R
DEnginears.c m
Compiled
Mayuranand Classes
525 7069
a ss11 3281
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. ir 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. ir 6517 3281
,rovides a
a case of
whenever
ck to root
55) of the
e address
~sses
field
'n' nodes
n1) links
nts).
~decessor
node and
r node to
we don't
a pointer
To implement thread binary tree in 'C' under the dynamic implementation, an extra
logical field rtthread (right thread) is included within each node. whether or not its
right print is a thread.
Right Threaded Binary Tree :
Node Representation
Left link
Data field
if (rtthread
== <!>)
Right link
No right thread link
if(rtthead == 1)
Left Threaded Binary Tree : It can be defined similarly as one in which each
NULL left pointer is utilized to store address of its predecessor node.
Node Representation
Left thread
( ltth read) ..____
Right link
____......+_
___.__ _4'1
Data
Pg. 64
65
Mayuranand Classes
B403/407, KonarkDarshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai  80. if 32~1 .472&; 6525 7069
. :. B216/217 Vardhman Chambers, Above UTI Ban~. Nr Babubhai Jagjeevandas, Sector 17, Vashi, Ncivi Mumbai. W 6517 3281
link is utilized for storing address of predecessor and successor node respectively.
Note that, link of th~ leftmost node and right link of the right most node (BOTH
ARE NULL) should not be utilized for constructing threaded binary tree.
8403/40
8216/217 Vardl
To implem
and right c
can observ
T[O]'s chile
T( 1] 's chile
T[2]'s chile
For any r
Trees ;~?
T[2*1NDE~
We
canal~
inde~
If
If inde:
Importar
This sho'lll
from pare
APPLl
(1) Expre
(2) Game
+
Binary Tree
Linked Representation
EXPR
Often thE
same ty~
use a bir
characte1
A binary tree can be stored in an array in such a way that the parent child
relationship is maintained, what we will do is to store the tree in the array, level by
level, left to right as shown in the following figure. The number of nodes in the tree
is MAX (size of array). The first node, i.e. root node is stored in T(O) and the last
node in T[MAX 1].
[0]
30
[1]
20
[2]
40
[3]
10
[4]
25
[5]
35
[6]
50
[7]
[8]
15
[9]
22
Compilec
Mayuranand Classes
>525 7069
. ir 6517 3281
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. il 3251 4726, 6525 7069
B216/217Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. il6517 3281 .
right NULL
>ectively.
To implement algorithm to manipulate the tree, we must be able to find the left
and right child of the node in a Tree. Comparing a tree and array in the figure, we
can observe .the following facts :
ode (BOTH
For any node, T[Index], its left child is in T[2*INDEX+l] and right child is in
T[2*INDEX+2].
We can also observe from the figure that :
If
inde~
Important:
This shows that the array implementation of binary tree is linked in both directions
. from parent to child and from child to parent.
( 1) Expression Tree
(2) Game Tree
icit in data
:hild and a
Often the information stored in different nodes of a binary tree is not all of the
same type. For example, to represent a mathematical expression, we might like to
use a binary tree whose leaves contain values (operand) but nonleft nodes contain
character representing operators. Look at the following figure
3rent child
:y, level by
in the tree
1d the last
Pg. 66
oDEngineers.col
Pg. 67
Mayuranand Classes
8403/407, Konark Darshan, Above UTI Bank, 'laver Road, Mulund (W), Mumbai  80 .. B 3251.4726, 6525 7069
8216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. V 6517 3281
B403/ ~
B216/217 Va1
Q. 15.
float eval
Ans.: Cl
#include
INFIX
Expression
void mair
PREFIX
Expression
POSTFIX
Expression
char
float
PREFIX is also known as POLISH Notation and POSTFIX is known as reverse polish
notation.
Ex.
a+ b
get~
PREFIX Exp.
+ab
ans
POSTFIX Exp.
ab +
prin
In Prefix form each operator will appear before its operands whereas in Postfix
operator will appear after its operands.
. INFIX Exp :
a+b*cd/e
float eve:
{
More Examples :
1)
prin
INFIX Exp.
int
PREFIX Exp :
POSTFIX Exp :
a+ [*be]  d/e
a + (*be]  [Ide]
a + [be *]  d/e
a + [be *] [de/]
[ +a*bc]  [Ide]
[abc*+]
abc* +de/
+a* be
I de
floc
[de/]
chc
floc
for
Note that although the given INFIX expressions have parentheses, but in prefix or
postfix, there won't be parentheses.
2)
INFIX Exp :
a + b*c(cd/e+f*(g  h/i) + j) + k
+k
a + b *[cde/fghi/*+j+] + k
a + [bcde/fghi/*+j+*]+k
+ j) + k
POSTFIX Exp :
abcde/:fghi/* + j + *+k +
There are two phases irt complete evaluation of a mathematical expression.
(i) Given infix expression is converted in either prefix
}
rn"'nil"'rl
nv
Prnf
Q~;,.c:h Rnthr~
o,., t:.o
Compil
Mayuranand Classes
i25 7069
ir 6517 3281
which we
ns are not
;sions are
n.
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. it 3251 4726, 6525 7069
. B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi; Navi Mumbai. V 6517 3281
#include <stdio.h> .
float evaluate (char[ ] ) ;
/*function prototype*/
void main()
{
char p[20];
float ans;
:rse polish
}
float evaluate (char p[20l)
{
1 d/e
I [del]
[de/]
/*sis a stack*/
char x;
float r;
for ( i = 0; p [ i] ! = '\ 0'; i + + )
~/
{
X
: prefix or
= p(i];
/* x is an operator*/
opl = s[top ]; /* pop an element*/
op2
= s[top  ];
/* pop an element* I
switch (x)
{
case'+'
case''
case'*'
case'/'
s[ ++top] = r;
}
else
ersion)
/*x is an operand* I
V::; X
'<f>';
s[ ++;top]
= v;
}
Pg. 68
oDEngineers.co
Pg. 69
Mayuranand Classes
8403/407_, Konark Darshan, Above UTI Bank, ZaverRoad, Mulund (W), Mumbai 80. if 3251 4726, 6525 7069
B216/217 Vardhman. Chambers, Above UTI Bank,
Nr Babubhai Jagjeevandas,
Sector 17, Vashi, NaviMumbai. R 6517
3281
.
.
.
.
B403/ ~
B216/217 Va'
~ 
r = s[top];
for (i
return r;
/*end ofevaluate */
{
inorder (tra
~
left);
right);
}
}
I*
pr
{
if (tra != NULL)
pr
pr
printf.('' 0/oc",
tra + data);
pr
pr
} r
Q. 17.
and ir
void main()
Ans.:
#inclu
char p[20] x;
inti, top
#inclu
= 1;
#inciL
typed'
node *root;
node *stack[20];
/*stack of pointers * 1
Pg. 70
oDEngineers.co
Com pi
MayuranandClasses
525 7069
ir 6517 3281
.B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. it 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. ir 6517 3281
{
X=
p[i];
==
if (ch
INFIX or
'+' II ch
== '' II
ch
==
'*' II ch
== '/')
op 1
= stack[top];
= (node*)
newrec
data = x;
newrec
left
/*right operand*/
/*left operand*/
malloc(sizeof(node));
= OP2;
/*left operand*/
= newrec;
else
{
newrec
= (node*)
malloc(sizeof(node));
= NULL;
newrec
left
newrec
right
stack[ ++top]
= NULL;
= newrec;
*I
/*end of main*/
{
char data;
struC:t node:_tag *left, *right;
Pg. 70
oDEngineers.col
Pg.71
Mayuranand Classes
8403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. ir 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, NrBabubhai Jagjeevandas, Sector 17, Vastli, Navi Mumbai. ir 6517 3281
B403/
B216/217 Vc
} node;
node *getnode( c)
{
return (node *) malice (sizeof(node));
}
{
!:.
if(tra ! = NULL)
{
postorder (tra
left);
postorder (tra
right);
~data);
roc
l*c
pri
inc
if (tra ! = NULL)
pri
{
inorder (tra
I*
left);
~
pri
data);
po
right);
pr
I*
}
void main()
Q.18.
Ans.:
char p[20J, x;
# inciL
int
icp~
node *stack(2.Q];
S\
= p[i];
if(x ==
'+' II
x == ''
II
x == '*'
II
x == '/')
intis~
l*
right b'perand*/
newrec = getnode();
newrec
data = x;
newrec
left = op 1;
Dn
7?
Com pi
7069
6517 3281
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. tr 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. tr 6517 3281
newrec
right= op2;
else
{
newrec = getnode();
. newrec ~ data=x;
newrec
left = NULL;
newrec
right = NULL;
/*end of for
*I
root = stack[top] ;
/*call Inorder traversal*/
printf ("Infix Expression is \n");
inorder (root);
printf ("\n");
/* call Postorder traversal
"
*I
/*end of main
*I
switch (x)
{
case 'c'
return 4;
case'*'
case'/'
return 3;
case'+'
case''
return 2;
switch (x)
{
case'$'
case 'c'
return <j>;
return 1;
case'*'
Pg. 72
oDEngineers.co
Pg . 73
Mayuranand Classes .
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80.  ir a2514726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai' Jagjeevandas, Sector 17, Va$~i;. Nav~ Mumbai. tt 6517 3281
B403/
B216/217 V:
return 3;
case'/'
case'+'
case''
return 2;
}
void main()
{
char infix[20], p[20], stack[lS], x;
whi
gets (infix);
top++;
stack[top]
= 0;
for (i
= '$';
}
p[j
pri1
x = infix[i];
if(x
==
'+' II x
== '' II x ==
'*'
II
== '/')
{
while(isp(stack[top]) > = icp(x))
This is t
HET
The fu1
express
right SL
'oper' r
p[j] = stack[top];
top;
j++;
}
# inclw
top++;
# defin
stack[top] = x;
# defin
typede1
else
if (ch
== '(' )
{
top++;
stack[top] = x;
}
else
if (ch == ')' )
} node
while (stack[top] !
= '(' )
float 01
{
{
p[j] = stack[top];
top;
j++;
}
C"rn~il~ti "'"
DEngineers.c
Compile
Mayuranand .Classes
~5
7069 .
65173281
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. II 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr.Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. W 6517 3281
top;
}
else
{
p[j]=ch;
j++;
}
= stack
p[j]
[top];
j++;
top;
p[j] = '\0';
printf ("postfix expression is 0/os \n", p);
# define OPERAND 1
typedef struct node_Jag
{
int utype;
union
{
char chinfo;
float numinfo;
};
struct node_tag *left, *right;
} node;
float oper (char op, float opl, float op2)
I* opl
~operand
1, op2
~operand
*I
float ans;
switch (op)
{
Pg.74
75
Pg.
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai ~ 80. __if 3251 4726,6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. tr 6517 3281
B403
B216/217 I
case'+'
Q. 20.\
case''
Ans.: R
case'*' 
# includ
case'/'
# includ
# indue
return ;ans;
# indue
# incluc
# definE
float op
{
flo.
char sym;
if (tree
sw
utype = = OPERAND)
return
tree~
left);
right);
sym = tree
numinfo;
chinfo;
}
}
void su
RECURSION
int
fo
Stl
char first[2];
}
float e\
= prefix[O];
= '\0';
{
fie
= = '*'
II
cr
first[ OJ==)
if
substr{tl,O,strlen(tl) ,postfix);
}
OJ
postfix[O] = first[O];
Sl
postfix[l] = '\0';
v:
v:
re
}
Compile
Mayuranand Classes
5 7069 .
r 6517 3281
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. ir 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. ir 65173281
# include <ctypc.h>
# define MAX 50
float ans;
switch (op)
= vl
case'+'
ans
+ v2; break;
case''
case'*'
ans
= vl
* v2; break;
case'/'
ans ~ vl
I v2; break;
return ans;
}
void substr (char str[ ], int pos, int len, char strl[ ]);
n.
inti, j;
for ( i
= 0;
i < Ien ; i + + )
{
float vl,v2;
char op;
if (isdigit(prefix[O]))
~
v1 = prefix[O]  '0';
substr (prefix, 1, strlen(prefix)1, prefix};
return vl;
}
op = prefix[O];
substr[prefix, 1, strlen(prefix)1, prefix);.
v1 = eva I( prefix);
v2 = eval(prefix);
return (oper(op, v1, v2);
}
Pg. 76
77
Pg.

Mayuranand Classes
B403/407, Koliark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. tl32514726, 6525.7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas,. Sector 17, Vashi, Navi Mumbai. il 6517 3281
B403/
B216/217 Va
NQUEENS PROBLEM
1 to 2
inti;
2 to 3
for ( i = 1; i < = n; i + +)
{
if (place (k, i))
{
x[k] = i;
if(k==n)
3 to 1
{
for (j
= 1; j
< = n; j + +)
9
1 to 2
else
nqueen (k + 1, n);
} . I* end
}
I* end for *I
/* end nqueen *I
if
*I
+ TOWERS OF HANOI
Q. 22. Write a program to implement Towers of Hanoi problem.
Ans.: Let n : no. of disks.
x,
if (n > 1)
{
tower (x, z, y, n 1);
printf ("Disk moves from 0/od to 0/od \n", x, y);
n= 3
Pg. 78
Com pi
oDEngineers.col
Mayuranand Classes
;7069
6517 3281
B403/407, Konark Darshan, Above UTI Bank, laver Road, Mulund (W), Mumbai  80. V 3251 4726, 6525 7069
B216/217 Vardhman Chambers. Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vas~i, Navi Mumbai. tir 6517 3281
a~~__
1 to 2
___:__
__
1 to 3
1 to 2
2 to 3
y
X
e
3 to 1
~_...:....z__
3 to 2
X
T(l/2,3,3)
T( 1,3,2,2)
1 to 2
d
~l~
T(1,2,3,1)
A\
a
Pg. 78
T(2,3,1f1)
1 to 3
b
/2~3\
c
~1
T(3,1,2,1)
11\.
T(3,2,1,2)
3tol .
e
,A
3 to 2 . T(ll2,3,l)
DEnginears.c
79
mPg.
oDEngineers.co
.  ~
..
 
    ~7~;
'''
'/f,~l~''
WIII~~~;'Wimllml~i~AND
C: L A S S E S
MAYURANANDCLASSES
B403 I 407, Konark Darshan,
Above UTI Bank, Zaver Road,
Mulund (W), Mumbai 80.
C<?ntact Nos. : 3251 4726, 6525 7069
(MECHANICAL ENGINEERING)
Set 2(
ANALYSIS OF ALGORITHM
ALSD TEACHES
! CPI (Sem. I)
! CPII (Sem. II)
! DATA STRUCTURES (Sem III. : CMPN)
! NT (Sem. III)
Dadar + Andheri
+ Vashi + CBD
+ Mulund + Thane.
+ Panvel + Airoli
oDEngineers.co
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank~ laver Road, Mulund (W), Mumbai 80. if 3251 4726,6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Nav.i Mumbai. if 6517 3281
ANALYSIS OF ALGORITHM
DETAILED SYLLABUS
(1) Lists :
D Abstract Data Types
D Queues : ADT, Representation, Operations, Circular Queues, Examples,
Applications
0 Other Lists and their Implementations
l Preorder
Download~th;~ Fil~rilingineers.coiPg.
Mayuranand Classes
B403/407, Konark Darshan. Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. if 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281
B403/
B216/217 Va
(8) Algorithms :
(J Analysis of all the above Algorithms
0 ~reedy Method
0 Divide and Conquer Method
0 Dynamic Programming
0 Backtracking Method
0 Branch and Bound
0 0'1 Knapsack Problem, Travelling Salesperson Efficiency Considerations
0 NP Hard and NP Complete Problems
IJ NP Hard Problems
TERM WORK
Term work shall comprise of . at least 12 practical experiments and a class test
based on above syllabus.
Class assignments and laboratory experiments
15 marks
Class test
10 marks
Total
25 marks
Ch.
1.
2.
LIST OF ASSIGNMENTS
(1)
(2)
(3)
(4)
(5)
3.
4.
s.
6.
~
R
DEC 2003
18
52
20
16
28
24
170
MAY 2004
20
10
12
40
15
25
20
150
DEC 2004
20
25
16
19
20
15
40
160
MAY 2005
20
20
10
20
20
20
30
30
170
DEC 2005
20
20
30
30
20
20
140
MAY 2006
30
10
10
30
10
30
25
145
AVERAGE
MARKS
19
10
17
23
25
14
25
23
156
CH. 5.
CH. 7.
CH. 6.
CH. 8.
Sorting Searching Graph Algorithms TOTAL
Methods Methods
o~
::
Compiled
Mayuranand Classes
'26, 6525 7069
mbai.
6517 3281
84031407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. if 32514726, 6525 7069
. B216/217 Vardhman Chambers, Above UTIBank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281 .
(. ANALYSIS OF ALGORITHM )
:Jerations
INDEX
I a class test
. Ch .No.
Topic
Page No
~s
1.
Algorithm Analysis
18
2.
Sorting Methods
929
3.
Searching Methods
3034
4.
Graphs
3542
s.
Algorithms
6.
Sparse Matrix
52~
56 .
University Papers
57~
64
'ns.
ld Deletion of
CH. 8.
gotithm'$ TOTAL
24
170
20
150
40
160
30
170
140
2.S
145
23
156
Pn ;;
. 43 51
oDEngineers.CoiPg.
iii
B40~
B216/217 .
+ANA
Q. 1. '
'
Ans.: l
time a1
with ir
algoritt
(time,
to exec
Algorit
theory
algorit
insight
In the
asym1
length
Big 0
For in
logari1
Usual I
same
"reas<
multi~
Exact
they
of the
Exact
use a
much
progr
failur
Time
tom
boun
anal)
warr;
com~
cons
lOOC
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank; Zaver Road, Mulund {W), Mumbai 80. V 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. V 6517 3281
AOA
CHAPTER 1: ALGORITM ANALYSIS
ANALYSIS OF ALGORITHMS
OR
Big 0 notation, omega notation and theta notation are used to this end.
For instance, binary search is said to run an amount of steps proportional to a
logarithm, or in O(log(n)), colloquially "in logarithmic time".
Usually asymptotic estimates are used because different implementations of the
same algorithm may differ in efficiency. However the efficiencies of any two
"reasonable" implementations of a given algorithm are related by a constant
multiplicative factor called hidden constant.
Exact (not asymptotic) measures of efficiency can sometimes be computed but
they usually require certain assumptions concerning the particular implementation
of the algorithm, called model of computation.
Exact measures of efficiency are useful to the people who actually implement and
use algorithms, because they are more precise and thus enable them to know how
much time they can expect to spend in execution. To some people (e.g. game
programmers), a hidden constant can make all the difference between success and
failure.
Time efficiency estimates depend on what we define to be a step. For the analysis
to make sense, the time required to perform a step must be guaranteed to be
bounded above by a constant. One must be careful here; for instance, some
analyses count an addition of two numbers as a 'step. This assumption may not be
warranted in certain contexts. For example, if the numbers involved in a
computation may be arbitrarily large, addition no longer can be assumed to require
constant time (compare the time you need to add two 2digit integers and two
1000digit integers using a pen and paper).
Pg. 1
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. ir 3251 4726,6525 7069
ir 6517 3281
B~21G/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai.
the wor
... + N
No. of
steps
Worst Case
/ . Complexity

~
Average Case
Complexity
a
a
a
Note tl
becaus
Best Case
Complexity
+
0
The ar
Consider the following three algorithms for determining whether anyone in the
room has the same birthday as you.
Algorithm l : You say your birthday, and ask whether anyone in the room has the
same birthday. If anyone does have the same birthday, they answer yes.
Algorithm 2 : You tell the first person your birthday~ and ask if they have the
same birthday; if they say no, you tell the second person your birthday and ask
whether they have the same birthday; etc. for each person in the room.
Algorithm 3 : You only ask questions of person 1, who only asks questions of
person 2, who only asks questions of person 3, etc. You tell person l your birthday,
and ask if they have the same birthday; if they say no, you ask them to find out
about person 2. Person 1 asks person 2 .and tells you the answer. If it is no, you
ask person 1 to find out about person 3. Person 1 asks person 2 to find out about
person 3, etc.
Question l :What is the fclctor that can affect the number of questions asked (the
"problem size")?
Question 2 : In the worst case, how many questions will be asked for each of the
three algorithms?
Question 3 : For each algorithm, say whether it is constant, linear, or quadratic in
the prot?lem size in the worst case.
1.
2.
3.
4.
The tc
total t
If eac
each
follov,
ifthE
5.
6.
7.
9.
10.
Here.
Then
Solution:
Sequc
8.
H0 1
In gen
The best case complexity of the algorithm is the function defined by the
minimum number of st;eps taken on any instance of size n./
',r
ex~
For a p
_,..
,/
/
//
~_./ . .
Questi
constar
probler
We
/ ./ /
//
B40:
B216/217
Pq. 2
DEngineers.c
max(
Fore
the v
Comp
l525 7069
. 2 6517 3281
Mayuranand Classes
8403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. 2' 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. it 6517 3281
Question 3 : Given the number of questions you can see that algorithm 1 is
constant time, algorithm 2 is linear time, and algorithm 3 is quadratic time in the
problem size.
We express complexity using big0 notation.
For a problem of size.N :
Note that the big0 expressions do not have constants or loworder terms. This is
because, when N gets large enough, constants and loworder terms do not matter.
Sequence of
Statement~
1.
statement 1;
2.
statement 2;
3.
4.
yone in the
statement k;
The total time is found by adding the times for .all statements:
total time
s.
ey have the
jay and ask
= time(statement
If each statement is ,.simple .. (only involves basic operations) then the time for
each statement is constant and the total time is also constant: 0(1). In the
following examples, assume the statements are simple unless noted otherwise.
If (condition)
{
5.
sequence of statements 1
6.
7.
else
8.
9.
sequence of statements 2
10. }
Here, either sequence 1 will execute, or sequence 2 will execute.
Therefore, the worstcase time is the slowest of the two possibilities :
max(time(sequence 1), time(sequence 2)).
~you always
irthday. Here
algorithm 3,
Pg.
For example, if sequence 1 is O(N) and sequence 2 is 0(1) the worstcase time for
the whole ifthenelse statement would be O(N).
Downloaded from
faa oDEngineers.col
Pg. 3
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai ~ 80. V 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281
B4
B216/21
for Loops:
16. fo
17. {
12. {
18.
13.
19. }
sequence of statements
14. }
The loop executes N times, so the sequence of statements also executes N times.
Since we assume the statements are O(l), the total time for the for loop is N *
0(1), which is O(N) overall.
(C) A
d
20. fa
21. {
Nested Loops:
22.
23.
16. {
24.
for (j =
17.
o; j
< M; j + +)
25.
18.
26. }
sequence of statements
19.
Sol uti
1.
20. }
The outer loop executes N times. Every time the outer loop executes, the inner
loop executes M times. As a result, the statements in the inner loop execute a total
of N * M times. Thus, the complexity is O(N * M). In a common special case where
the stopping condition of the inner loop is j < N instead of j < M (i.e., the inner
loop also executes N times), the tota.l complexity for the two loops is O(N 2 ).
for (i = 0; i < N; i+ +)
2.
3.
sequence of statements
5.
for (j = 0; j < M; j + +)
6.
{
}
~hange
2.
Tl
0
3.
"'
e:
ir
e
On th
inconv
with a
so tim.
10. {
11.
for (j = 0; j < N ; j + +)
12.
13.
14.
w
w
In gen
metho
import
timec
pro bat
contra
compL
not rei
before
yl
Some
the pn
sequence of statements
9.
+BE~
4.
7.
8.
Tl
is
Note t
to con
distrib
sequence of statements
15. }
Compiled by Prof. Rajesh Bothra
on
aDEngineers.c
Compile
Mayuranand Classes
6, 6525 7069
:>ai. B 6517 3281
B403/407, Konark Darshan, Above UTI Bank, laver Road, Mulund (W), Mumbai 80. if 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. B 6517 3281
17. {
18.
sequence of statements
19. }
tes N times.
loop is N *
(C) A nested loop in which the number of times the inner loop executes
depends on the value of the outer loop index:
20. for (i = 0; i < N; i + +)
21. {
22.
for (j = i; j < N; j + +)
23.
24.
sequence of statements
25.
26. }
Solution:
1.
The first loop is O(N) and the second loop is O(M). Since you don'tknow which
is bigger, you say this is O(N+M). This can also be written as O(max(N,M)). In
the case where the second loop goes to N instead of M the complexity is O(N).
You can see this from either expression above. O(N+M) becomes 0(2N) and
when you drop the constant it is O(N). O(max(N,M)) becomes O(max(N,N))
which is O(N).
\J2).
2.
The first set of nested loops is O(N 2 ) and the second loop is O(N). This is
O(max(N 2,N)) which is O(N 2 ).
wing code
3.
When i is 0 the inner loop executes N times. When i is 1 the inner loop
executes N1 times. In the last iteration of the outer loop when i is N1 the
inner loop executes 1 time. The number of times the inner loop statements
execute is N + N1 + ... + 2 + 1. This sum is N(N+1)/2 and gives O(N 2 ).
s, the inner
~cute
a total
case where
., the inner
Pg.
Mayuranand Classes
B4(
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. ii 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281
B216/21~
e, o
+ GROWTH RATE
Many complexities occur frequently in computing, so it is worthwhile to become
familiar with them. Table 1 below lists some typical situations in which common
complexities occur. Table 2 lists these common complexities along with some
calculations illustrating their growth rates . Figure 1 presents the data of Table 2 in
a graphical form.
Complexity Example
Fetching the first element from a set of data .
0(1)
. O(lg n)
Splitting a set of data in half, then splitting the halves in half, etc.
O(n)
O(n lg n)
O(n 2 )
Traversing a set of data once for each member of another set of equal
size.
0(2")
O(n!)
no
f(n)
Graph it
in the r
(a)
Complexity
16
n = 256
n = 4k .
64k
to
in
n =1M
O{lg n)
O(n)
(b) 0 
w.
th
(c)
0{2)
O{n!)
l.OOOE+OO 2.092E+13



 


T(n)
O(n!) 0(2n) O(n 2 )
200 ..... ...................... T. .......................... .
ew
0{1)

n
w,
th
'
+ CLA
Becaus
rate of
terms t
with wt
algoritr
those t
and the
O(n lg n)
150 ............ ..
BIG 01
We
USE
least a~
threshc
You car
in this
g(x) e r
0
10
20
Becaus~
. 30
becausE
includin
Po. 6
DEngineers.c
Compiled
Mayuranand Classes
6, 6525 7069
bat. if 6517 3281
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. if 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr BabubhaiJagjeevandas, Sector 17, Vashi, Navi Mumbai. ii' 6517 3281
8, 0 And 0 Notations
e to become
1ich common
~ with some
of Table 2 in
Ctg(n)
n half, etc.
~~n
no
f(n)
each half.
=e
no
f(n) = O(g(n})
(g(n))
(a)
~~~n
no
f(n)
(b)
= n(g(n))
(c)
r set of equal
Graphic examples of the e, 0 and n notations. In .each part, the value of n0 shown
in the minimum possible value; any greater value would also work.
Occur
n =1M
0 l.OOOE+OO
1 2.000E+01
4 1.049E+06
5 2.097E+07
9 1.100E+ 12
We write f(n) = e (g(n)) if there exist positive constants no, c1 and c2 such that
to the right of no, the value of f(n) always lies between c1 g(n) and c2 g(n)
inclusive.
(b) 0notation gives an upper bound for a function to within a constant factor.
. We write f(n) ~ 0 (g(n)) if there are positive constants n0 and csuch that to
the right of n0 , the value of f{n) always lies on or below cg(nr
(c) nnotation gives a lower bound for a function to within a constant factor.
We write f(n) = .o (g(n)) if there are positive constants n 0 and c such that to
the right of no, the value of f (n) always lies on or above cg(n).

le 1
+ CLASSIFICATION OF GROWTH
Because the rate of growth of an algorithm is important, and we have seen that the
rate of growth is dominated by the largest term in an equation, we will discard the
terms that grow more slowly. When we strip all of these things away, we are left
with what we call the order of the functi.on or related algorithm. We can then group
algorithms together based on their order. We group them in three categories ~
those that grow at leastas fast as some function, those that grow at the same rate
and those that grow n9 faster.
BIG .OMEGA
We use n(f), called big omega, to represent the class of functions that grow at
least as fast as the function f. This means that for all values of n greater than some
threshold rio, all of the functions in n(f) have values that are atleast as large as f.
You can view n(f) as setting a lower bound on a function, because all the. functions
in this . class will grow as fast as f or even faster. Formally, this means that if
g(x) e n(f), g(n) ~ cf(n) for all n ~ n0 (where cis a positive constant).
Because we are interested in efficiency, n(f) will not be of much interest to us
because n
(n2 ),
Pg. 6
DEnginears.c m
Pg.
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. if 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. ir 6517 328.1
B403
B216/217 '
BIG OH
At the other end of the spectrum, we have O(f), called big oh, which represents
the class of functions that grow no faster than f. This means that for all values of n
greater than some threshold n 0 , all the function's in O(f) have values that are no
greater than f. The class O(f) has f as an upper bound, so none of the functions in
this class grow faster than f. Formally this means that if g(x) E O(f), g(n) ;5; cf(n) for
all n ~ n0 (where cis a positive constant)~
This is the class that will be of the greatest interest to us. Considering two
algorithms, will want to know if the function categorizing the behavior of the first is
in big oh of the second. If so, we know that the second algorithm does not better
than the first in solving the problem.
BIG THETA
We use e(f), called big theta, to represent the class of functions that grow at the
same rate as the function f. This meansthat for all values of n greater than some
threshold n 0 , all of the functions in e(f) have values that are about the same as f.
Formally, this class of function is defined as the place where big omega and big oh
overlap, so e(f) = n(f)n O(f).
When we consider algorithms, we will be interested in finding algorithms that might
do better than the one we are considering. So, finding one that is in big theta (in
other words, is of the same complexity) is not very interesting. We will not refer to
this class very often.
+TYPE
. Q. 1. 51
Ans.: I
of the c
so sma
techniq1
Extern;
Second;
enormo
done o
Needle~
for acce
+ DIFI
(1) CL.
Q.2. E
its per
Ans.:
interch
first pa
last pic
need r
need tc
Algori'
1)
2)
E~
RE
ur
or
3)
R(
Illustr
The ori
[
The so
[
The so
[
The so
[
. The so
[
Compiled by Prof. Rajesh Bothra
Pg. 8
oDEngineers.co
Compile
Mayuran~nd Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W). Mumbai 80. if 3251 4726, 6525 7069
B216/217 Vardhman Chambers. Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281
. 6525 7069
li. 2 6517 3281
AOA
represents
values of n
that are no
Functions in
)$cf(n) for
+ TYPES OF SORTING
Q.. 1. State the types of sorting methods.
Ans.: Internal Sorting : It is that sorting which takes place in the main memory
of the computer. It is important that in such sorting the size of the input should be
so small that entire input can be stored in the internal memory. All the sorting
techniques we will be studying ate internal sorting techniques.
dering two
= the first is
; not better
External Sorting : This type of sorting takes place in the secondary memory.
Sec::ondary memory can be in the form of disk or tapes. If the size of the input is so
enormous that it can not be stored in the main memory at a time, then the sorting is
done on such secondary memory devices, thereby resorting to external sorting.
Needless to say, external sorting is slower than internal sorting as the time required
for accessing internal memory is much less than that required for external memory.
~row
at the
than some
same as f.
and big oh
that might
g theta (in
1ot refer to
Q. 2. Explain classical bubble sort algorithm with example and also explain
its performance.
Ans.: This algorithm compares two consecutive elements and the elements are
interchanged immediately upon discovering that they are out of order. During the
first pass, when n  1 comparisons are made, the heaviest elements occupies the
last place in the array. When the process is repeated next time, this last element
need not be compared and therefore during second pass only n2 comparisons
need to be made. After n1 passes, the array gets sorted.
,n g is an
rnction g is
, when you
Algorithm:
1)
2)
Repeat the following (n  1) times for all adjacent pairs of elements in the
unsorted part of the array do if current adjacent pair is not nondescending
order, then exchange the element of the pair.
3)
Illustration :
The original array :
147
ls7 . ls;2
162
131
117
121
122
141
13iJ
117[21
122
141
137
162
122
141
137
ls7 162
141
137
ls2
ls7
162
I 37
147
I s2
ls7
!62
..
ls7
1""31
ls2
131
117
121
Pg. 8
131
117
121
122
l17
!21
I 22
!41
Pg.9
Mayuranand Classes
8403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. B 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. ir 6517 3281
3)
117 121 122 131 137 141 147 152 157 162
The sorted array after 6passes is :
liel 21 122 131 137 141 147 152 157 162
The sorted array after 7passes is :
117 121 122 131 137 141 147 152 ls7 162
B403 /'
B216/217 Va
Whil1
(a)
(b)
(b.1:
4)
RetL
Illustrat
117 121 122 131 137. 141 147 152 157 162
The origi1
117 121 122 131 137 141 147 ls2 ls7 16iJ
The sortE
The
sort~
The sort1
i=l
The sort1
The sort
The sort
Q. 3. Explain the modified bubble sort with example and explain its
performance.
Ans.: Classical bubble sort will take n  1 passes irrespective of whether the array
is already sorted or not. An improved bubble sort algorithm terminates the moment
he find out that the array is sorted and needs no "further passes.
Perforn
When this approach is used, maximum n  1 passes are required for sorting of the
qrray. During the first pass A[i] and A[2] are compared, [Note : Assuming A is the
given array] and if they are out of order then A[l] and A[2] will be interchanged,
this process will be repeat~d for A[2] and A[3] and A[ 4] a~d so on. After this first
pass, the largest element \.viii be placed in position. Ori each successive pass, the
elements with the next largest value will be placed in position n 1, n  2, .... , 2
respectively, thereby resulting in a sorted array.
ConseqL
After each pass tJ1rough the array, a check can be made to determine whether any
interchanges were made during that pass. If no interchange occurred, then the array
must be sorted and no further pass is required. The process terminates at such an
instance.
Best C;
The We
com pari:
Note:
The bub
a sma.ll
(3) SEL
Q. 4. E>
Ans.: 0
element
the arra
first eler
This is c:
Algorithm:
1)
2)
Pn 1 n
Compiled
Mayuranand Classes
5, 6525 7069
Jai.
6517 3281
8403/'407, Konark Oarshan, Above UTI Bank. laver Road, Mulund (W); Mumbai 80. if 3251 4726, 6525 7069
8216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. it 6517 3281
3)
(b)
for all adjacent pairs of elements in the unsorted part of the array do
Illustration :
ls7
ls2
162
131
117
121
122
141
137
121
122
141
137
162
122
141
137
ls7
162
41
137
57
162
137
147
js2
Js7
162
141
147
ls2
js7
162
141 . 147
ls2
ls7
162
ls2
ls7 . 131
117
1
1akes n  1
:md so on.
~. The total
147
ls2
131
117
121
131
117
121
122
52
~spective
of
:akes place,
e for every
the bubble
131
lt7
121
122
141
121
122
131
137
117
~r the array
he moment
121
122
131
137
rting of the
ing A is the
erchanged,
er this first
e pass, the
 2, ... , 1 2
The Worst Case : The worst case performance of the bubble sort is n(n  1)/2
comparisons and n(n1)/2 exchanges, i.e., O(n 2 ).
Note:
The bubble sort may be an acceptable method for sorting an array, which contains
a small number of elements, but it should not be used for larger files or arrays.
hether any
n the array
at such
an
Pg.
10
t .
Ans.: One of the easiest sorting methods is selection sort. Beginning with the first .
element in the given array, a search is performed to find the smallest element in
the arr.ay. When such an element is found, the same will be interchanged with the
1 .
oDEng1neers.co
Pg. 11
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, ZaverRoad, Mulund (W), Mumbai 80. ill 3251 4726,6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17; Vashi, Navi Mumbai. if 6517 3281
B403
B216/217 \
to nth element. The element with the second smallest value is interchanged with the
second element in the array. The process of searching for the next smallest
element in the array and placing it its proper position (within the desired ordering)
continues until all elements have been sorted in ascending order.
The arra
~
The sort
Algorithm:
1)
2)
. 3)
Perforr
In the 2
a pass.
places c
3.1
3.2
ch'ange pos to i
During
com par
The tot
4)
n1
5)
i = 1
L (ni
x[i + 1] to x[n1]
6)
Irrespe
same.:
numbe1
mechar
earlier
selectic
Illustration :
The original array :
147
ls7
ls2
162
131
117
121
122
141
137
(4} IN
ls7
ls2
Q. 5. E
162
131
147
121
122
141
Ans.:
array i:
137
vis~av
121
ls2
162
131
147
ls7
122
141
137
131
147
ls7
l. s2
141
137
such t
subsec
subar
121
122
162
Algori
121
122
131
162
147
ls7
ls2
141
137
1)
E~
2)
F1
2
122
131
137
147
ls7
ls2 141
162
121
122
131
3)
137
141, ls7
js2
147 Tss
I
Illust
121
122
131
137
141
147
ls2
ls7
162
137
141
147
ls2
!s7
162
The
01
121
122
131
The a,
Pn . 1?
Compil
Mayuranand Classes
'6525 7069
:~;.a 6517 3281
B403/407, Konark Oarshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. if 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281
117
121
122
131
137
141
147
js2
js7
r62
131
37
141
147 . ls2
ls7
162
117
\21
122
L (n  i) = 1 n ( n  1)
2
i= 1
Irrespective of the nature .of the data, the number of comparisons remains the
same. If the data is already sorted, then also it makes no difference to either the
number of comparisons or to the number of swapping. In seleCtion sort,
mechanism can not be devised by which the sorting process can be terminated
earlier as in bubble sorting . Since the number of comparisons is proportional to n2 ,
selection sort is O(n 2 ).
( 4) INSERTION SORT
Q. 5. Explain Insertion Sort.
Ans.: Another easy sorting method is insertion sort. First element in the given
array is sorted by itself. Second element is compared with first one and its position
visavis first element (before or after) is determined and is placed in that position
such that first two elements remain ~orted. The process is repeated for all
subsequent elements every time inserting the new element in the already sorted
subarray in such a way that the subarray remains sorted.
Algorithm:
1)
2)
3)
2.1
consider the size one less than the index of the element.
2.2
2.3
Illustration :
The original array :
1
47 . s7
1
s2
62
31
17
21 . 22
1
41
37
js7
Pg. 12
I
Downloaded from Faa
oDEngineers.col
Pg. 13
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. 'ir 3251 4726,6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi MumbaL if 6517 3281
147 152 157 162 131 111 121 122 141 137
The array after 3 iterations is :
31 147
i~
B4
B216/21
3)
4)
5)
6)
7)
Illust
22 141 137
The ur
117 .131 147 152 1s1 162 (21 122 141 137
The s<
41
62 141
37
The
S<
The
S<
47 152 157
37
l11 l21 122 l31 141 147 ls2 ls7 162 137 J
The~
111 121 122 131 137 141 147 1s2 157 162
Perfo
The a
the c1
insert
increr
eleme
insert
show~
(6) fJ
This case sorting will therefore have efficiency of O(n 2 ) . Therefore, worst case
running of insertion sort is a quadratic function of n, where n is the size of array.
Insertion sort is efficient if the array is almost sorted as minimum number of
comparisons will be require to sort it fully.
Q. 7.
Ans.:
with,
merge
till thE
'
Algo
1)
2)
3)
4)
Algorithm :
5)
1)
5)
2)
6)
.............Downloaded from
Po " 14
Com pi:
Faa oDEngineers.com
Mayuranand Classes
26, 6525 7069
1bai. ir 6517 3281
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. ir 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi MumbaL ir 6517 3281
3)
4)
5)
6)
7)
Divide the array into inc subarrays with inc as the increment size.
Sort these subarrays individually.
Reduce the inc to inc div 2.
Repeat steps
Illustration :
The unsorted array is :
147 ls7 ls2 162 131 140 121 ]22 141 137 118
The sorted array with increment 5 is :
118 121 122 141 131 140 157 152 162 137 147
The sorted array with increment 2is :
118 121 122 140 131 141 157 152 147 137 162
The sorted array with increment 1is :
118 121 122 131 137 140 141 147 152 ls7 162
The sorted array is :
118 121 122 131 137 140 141 147 js2 js7 162
Performance of the Algorithm
The analysis of Shell sort involves a lot of mathematical analysis. Eventhough at
the core of . shell sort, we have insertion sort, the analysis varies from that of
insertion sort. The efficiency of the sort depends on the values of diminishing
increments. They should be prime numbers so as to effect proper mixing of
elements. If that is achieved, for the last pass, which is like implementing classical
insertion sort, minimum numbers of shifting are required. Mathematical analysis
shows shell sort to be more efficient than classical insertion sort with O(nL 5 ).
, sorted, as
:; O(n). The
r, since the
worst case
:e of array.
number of
~nts'.
Shell
;orts these
1ent size is
t iteration,
I
Pg. 14
1)
2)
3)
4)
Merge these subarrays in pairs of two such that they remain sorted.
5)
5)
6)
DEnginears.c m
Pg.
15
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, laver Road, Mulund (W), Mumbai 80. if 3251 4726, 6525 7069
8216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas. Sector 17, Vashi, Navi Mumbai. if 6517 3281
B2161
iiiiiiiiiiiiiii
Clmplementation :
The~
Nonrecursive mergesort
void mergesort (int x[J, int n)
The~
The~
i1 = ~; k
The~
= 1;
12
= /1
rl
= /21;
Perf
+ size;
Assu
= (r1 + size
i = 11; j = 12;
r2
In r
<= n 1) ? r1 + size : n 1;
Duri1
max
sort
How
requ
= x[i++ ];
(7)
else
Q.S
temp[ ++k]
= x[j++ ];
Ans
step
with
sma
tech
can
plao
temp [ ++k]
11 = r2
= x[j++ ];
+ 1;
Algc
for (i =
~;
Ead
proc
algo
i < = r2; i+ +)
x[i] = temp[i];
size
1)
size;
2)
*I
I* end of merg~sort* I
}
=2 *
/*end of while
3)
Nor1
Illustration :
#dE
type
147
ls7
ls2
162
131
117
121
122
141
121
122
141
ls7
ls2
162
117
131
} st
Pa. 16
Com
Mayuranand Classes
1525 7069
if 6517 3281
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. til 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevaridas, Sector 17, Vashi, Navi Mumbai. it 6517 3281_
2is :
147 ls2 ls7 162 117 121 122 131 141
The sorted array with merge size 4is :
117 121 122 131 147 ls2 js7 162 141
ls1
162
2)
3)
Nonrecursive quicksort
# define size 10
{
int s[size];
int top;
} stack;
Pg.
16
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W); Mumbai 80. ir 3251 4726,6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. V 6517 3281
B4(
B216/21i
Illustr
The ori
sptr
~top
= 1;
lb
=0
{
if (sptr
~top
lb
=0
lb
=0
lb
=0
lb
=2
= p;
top];
lb =
{
stack s;
initialise (&s);
lb =!
lb
=I
lb =
pos = partitions (left, right);
push (&s, pos+l);
The :
}
}
}
P:e rf
/* end if*/
ASSL
/*end of quicksort
ASSL
midc
the
appr
com
files
subCompiled by Prof. Rajesh Bothra
Pg. 18
oDEngineers.col
COm(
6525 7069
i. ir 6517 3281
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. ir 3251 4726, 6525 7069
B~216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi; Navi Mumbai. V 6517 3281
Illustration :
145
1 53 ' 124
110
[14
112
134
145
js3
124
110
114
11?
134
110
1'14
112
140
153
156
145
110
114
134
140
js3
js6
145
124
114
134
140
js3
ls6
145
124
114
134
140' !s3
ls6
145
114
124
134
140
js3
[s6
145
= 0 ub = 8
140
lb
156
156
= 0 ub = 4
134
124
lb = 0 ub = 3
112
lb
= 0 ub = 0:
110
lb
124
112
= 2 ub = 3
!1o
112
lb = 2 ub = 2
lb
lb
!1o
112
= 4 ub =
110
112
114
124
134
140
ls3
ls6
145
112
114
124
134
140
153
156
145
114
124
134
140
153
156
145
114
124
134
140
145
ls3
js6
114
124
134
140
145
ls3
[56
124
134
140
145 . 153
156
= 5 ub 4
l1o
lb = 6 ub = 8
j1o
112
lb = 6 ub = 6
110
lb
1 12
= 8 ub = 8
110
112
l1o
112
114
Assume that the proper position for the pivot always turns out to be the exact
middle of the subarray. In that case, there will be approximately n comparisons on
the first pass, after which the file is split into two subfiles each of size n/2
approximately. For each of these two subfiles, there are approximateiy n/2
comparisons, and a total of four files each of size n/4 are formed. Each of these
files requires n/4 comparisons, yielding a total of n/8 subfiles. After halving the
subfiles m times. there are n files of size 1.
Pg. 18
l
Downloaded from Faa
oDEngineers.com
Pg. 19
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, laver Road, Mulund (W), Mumbai 80. V 3251 4726, 6525 7069
8216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas. Sector 17, Vashi, Navi Mumbai. if 6517 3281
Thus, the total number of comparisons for the entire sort is approximately,
n
8'
B216/2
void a
or
n + n + .... n (m terms) comparisons. There are m terms because the file is subdivided m times. Thus, the total number
of comparisons is O(mn) or O(n log n). Thus, if there properties describe the file,
the quicksort is 0( n log n).
Suppose that these conditions do no hold and that the original array is sorted (or
almost so"rted).
For e.g., X[/b] is in its correct positions; the original file will be split into two
subfiles of size 0 and n1. If this process continues, a total of n1, the third of size
n  2, and so on. Assuming k comparisons of a file of size k the total. number of
. comparisons to sort the entire file is
Ans~:
The drawbacks of the binary tree sort are remedied by the heap sort,
an inplace sort that requires only 0 (n log n) operations regardless of the order of
the input.
void
{
Heap (or descending heap or a max heap) of size n can be defined as an almost
complete binary tree of n nodes such that the content of each node is less than or .
equal to the content of its father. It is cl_e ar from this definition of a descending
heap that the root of the tree (or th~ first element of the array) contains the lar.gest
elemen_t in the heap.
We now formulate an algorithm, which will have as input an unsorted array and
produce as output a heap.
Algorithm:
1)
2)
3)
Swap the first element with the last element of the array.
4)
Without considering the last element, adjust the elements of the array so as to
5)
6)
Illu
The
C  Implementation :
Ma:
void heapify (int a[], int n) /* forming max_heap to sort array in ascending order*/
Adj
the
{
inti;
for (i = n/2; i >=
~;
Mil
i )
Adj
the
Pg. 20
Cor
Mayuranand Classes
525 7069
if 6517 3281
B403/407; Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. if. 3251 4726,65257069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281_
int j, x;
:al number
Je the file,
j=2*i;
x=a[i];
while (j <=n)
sorted (or
it into two
hird of size
number of
+ 1;
a [j/ 2] = a [j] ;
is already
= 2 * j;
a[j/2]
= x;
. heap sort,
he order of
inti, temp;
an almost
than or
descending
the largest
~ss
for (i = 1; i < = n  1 ; i + + )
{
. temp= a[l];
array and
= temp;
}
Illustration :
ay so as to
24
10
14
15
34
30
10
ng order*/
Pg.
20
oDEngineers.co
Pg, 21
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W}, Mumbai 80. 'a 3251 4726, 6525 7069
8216/217 Vardhman Chambers, Above UTI Bank, Nr Bab.ubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281
Heapify' process
B216/~
After
In general
~
0 .b
Left Child
 Location
Right Child
2*i+l
1.
1.
X=
55, i
=4
45
'
3'\
3~
@@
@@
6
3.
Afte
10
*parent is at proper place,
no adjustment is required.
10
X= 45, i = 3
4.
X=
50, i
1.
. a.
J.l
@
9
5.
X=
40, i = 1
Aft
45
3~
@
6
8.
7
10
Compiled by Prof. Rajesh Bothra
Pg. 22
Con
Mayuranand Classes
7069
6517 3281
B403/407, KonarkDarshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. tl 3251 4726,6525 7o69
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, NaviMumbai. V 6517 3281.
55
50
45
40
30
10
14
15
34
24
10
) Right Child
+1
Pass No.1
45
3'\
@@
6
10
ace,
50
40
45
34
30
10
14
15
24
55 )
10
red.
Pass No.2
2. Adjust parent i
= 1, n = 8; x = 24
45
40
24
34
30
10
14
15
50
55
10
Pg. 23
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. if 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. ir 6517 3281
.B403
B216/217 I
Pass No.3
1.
2. Adjust parent i = 1, n = 7; x = 15
1. Swc
24
3~
@
6
........ 4
@
8
After~
10
Ppss No.4
1.
1. Sw
2. Adjust parent i
= 1, n = 6; x = 14
After
After pass No.4:
34
30
24
15
14
10
40
45
.50
55
10
1. S\
Pass No.5
1.
2. Adjust parenti
= 10
After
15
4
= 1, n = 5;
10
30
15
24
10
14
34
40
45
50
55
10
Pg. 24
DEngineers.c
Compi l
6, 6525 7069
bai.
6517 3281
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. if 3251 4726, 6525 7069
8216/217 Vardhman Chambers, Above UTI Bank,. Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. ir 6517 3281
Pass No.6
X=
15
2. Adjust parent i
= 1, n = 4;
= i4
3~
24
15
14
10
30
34
40
45
50
55
10
Pass No.7
2. Adjust parent i = 1, n = 3; x = 10
14
......... 2
(24::}
r~ai
.......
.......
15
10
14
24
30
34
40
45
so
55
10
Pass No.8
2. Adjust parent i = 1, n = 2; x = 14
15
2
Pg.
24
14
10
15
24
30
34
40
45
5o 1 55
9
10
Pg. 25
Mayuranand Classes
8403/407, Konark Oarshan, Above UTI Bank, Zaver Road, Mulund {W), Mumbai 80. if 3251 4726, 6525 7069
8,216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Nav(Mumbai. V 6517 3281
Illustrc
Pass No.9
1.
. B40:
B216/217
2.
= 1, n = 1; x =10
Adjust parent i
The
ori~
.@
...... . 1
(~~:~:;
After pass No. 9 :
10
14
15
24
30
34
40
45
so
I ss]
10
The arr.
A heap can as well be considered as a priority queue. One may recollect the
definition .of a priority queue. The maintenance of queue is secondary but at the
point of deletion the priority queue should delete the highest (or the smallest)
element in the present queue for a descending (or ascending) priority queue.
A max heap behaves like a descending priority queue wherein the root of the heap
is always the maximum element in the heap.
Consider the time complexity of the heap sort. Since we are using a complete
binary tree, the worst case analysis is easier than the ave.rage case. Note the depth
of a complete binary tree of n nodes is log 2 n. Recall that to sort a given array we
must first create a heap and then sort that heap. The worst case at each step
involves performing number of comparisons, which is given by the depth of the
tree. This observation implies that the number of comparisons is 0 (n log 2 n).
Average case behavior is also 0 (n log 2 n). Also no extra working storage area,
except for one element position, is required. That is why it is known as an inplace
sort technique.
Perfor
(9) RADIX SORT :
Q. 10.
Expl~in
Radix Sort.
The al9
There c
Ans.: Radix sort is based on positional value of the actual digit of the numbers
being sorted.
So the
In this method, the nUmbers are sorted as per the least significant digit first so that
when all the numbers are sorted on a more significant digit, numbers having same
digit at that position but distinct digits at a lesssignificant position are already
sorted on a less significant position.
(10) B
First
Algorithm:
Secane
a sorte
Q. 11.
Ans.: l
p~
1)
2)
Call bucket sort repeatedly on least to most significant digit of each element as
the key.
Algori1
2)
3)
1)
3)
4)
Compile<
Mayuranand Classe s
525 7069
6517 3281
B403/407, Konark Darshan, Above UTI Bank, laver Road, Mulund (W), Mumbai 80. ir 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, NrBabubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. W 6517 3281
= io
370
392
423
554
927
L__j L_j
. 0
(__J
:ollect the
but at the
smallest)
ty queue.
f the heap
L..J
(__J
1423 1 927
0
complete
the depth
1 array we
each step
pth of the
:n logz n).
:age area,
l inplace
l___j (__J
357
927
294
t423t L....J l___j 1554 1 L_j 13701 l___j t392t
6
8
2
7
9
3
4
5
1
554
2
357
370
4
392
5
294
392
370
357
294
423 . 554
(._J L_j (__J (__J (__J L_j L_j 19271
First phase is creating a binary search tree using the given array elements.
Second phase is traverse the created binary search tree inorder, thus resulting in
a sorted array.
dement as
Pn ?t;
Algorithm:
1)
2)
3)
Traverse the tree inorder and store the elements back in the array.
4)
oiEngineers.col
Pg. 27
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. 2 3251 4726, 6525 7069
8~216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi. Navi Mumbai. ir 6517 3281
B~
B216/2'
C  implementation :
While
the ef
decidE
prefer
other
select
int data;
node * left, *right;
} node;
SE
It is d
meth'
the t
distrit
static int T = O;
Selecj
For a
increc
if( root)
{
If the
adopt
to 0( 1
If the
heap
whicr
avoid
}
void bin.;...tree_sort(int x[], int n)
{
inti;
node * root = NULL;
for ( i
= 0;
i < n; i + +)
Illustration :
The original X array :
I 40
56
4si 53
24
10
14
12
34
34
40
45
53
56
10
12
14
24
+n
= n(n
+ 1) I
= O(n 2)
Pg. 28
oDEngineers.co
Com~
Mayuranand Classes
6525 7069
li. ir 6517 3281
B403/407, Konark Darshan, AboveUTI Bank, Zaver Road, Mulund {W), Mumbai 80. if 3251 4726,6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, NrBabubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281
If the size n is large and key size is small, then the method of radix sort can be
adopted. The key size is an important criterion as radix sort has time proportional
to O(m + n), where m is the key size.
If the size n is large and key size is also not small, then the method of quick sort or
heap sort can be adopted. Since in the worst case also they have O(n log 2 n) time,
which is much better than any other sorting algorithm. Quick sort should be
avoided if the input is more or less sorted.
the worst
~n the sort
:! insertion
ns, and so
Pg. 28 .
Mayuranand Classes
B403/407, Konark Oarshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. V 3251 4726,6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. ir 6517 3281
B403/
B216/217 Va
AOA
However,
of the ori,
However,
the senti
linked li~
contain in
linked lis
SEQUENTIAL
SEARCHING (LINEAR. SEARCH)
.
2)
Set i
3)
Es
2)
SE
3)
SE
4)
5)
if
+ 1;
if ( i < = n  1) then
Perforr
return i;
It is ob
linearly
instead
sentine
more e
1)
= <1>;
i = i
4)
Algoritl'l
+ "IN[
Q.3.E
Pg. 30
Ans.: it invol
inCIex
a"side i
lllinde~
elemer
key. I1
rep res
The al
Algor
1)
2)
E
2
3)
4)
5)
6)
Effici
(The r
Ean . t
searc
Comp
525 7069
a 6517 3281
May~ranand Classes
B403 I 407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. if 3251 4726,6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, NrBabubhai Jagjeevandas, Sector 17, Vashi; Navi Mumbai. if 6517 3281
However, it may be noted that at least one vacant space must be there at the end
of the original array to accommodate the sentinel value.
However, if the list is represented by a linked list, then addition
the sentinel value requires some pointer adjustments. It 'also
linked list. Under such circumstances, after carrying out the
containing the sentinel value is required to be deleted from the
linked li~t needs to be restored to its original form.
present in
>n of no in
of node containing
alters the original
search, the node
linked list and the
Algorithm:
1)
2)
Set a[n] to x.
3)
set ito 0.
4)
while (x ! = a[i])
i++;
5)
It is obvious that the algorithm is still O(n) as increasing the size of data would
linearly increase the time requirement of the sort. However, it may be noted that
instead of two comparisons required by the classical . sequential search, such
sentinel search needs only one comparison for every iteration of the loop, making it
more efficient.
(~
C :r,
...,
~
1.
: .
,. f.i
/\
:)
Ans.: There is anothertec:hniqlj~ to improve se9rch efficiency f()r e3 sorted ~le1 byt
it involves an increa.s.e
th~ a n,ount'o('spac'e ceq'u ired: ' !~is m'ethod iscarfe"d the
indexed sequentlai' 'see~rcli"' 'method:""A'r1" 'auxii(a'ry""table', cat'led an index, ~is sef'
aside in addition to the sorted file itself. Each element in the index consists of a key
aindex and a pointer to the record in the file that corresponds ~o kindex. The
elements In the index, as well as the elements in the file must be sorted on the
key. If the index is one tenth the size of the. file, every tenth record of the file Is
represented in the index . This is illustrated by .thefigure on the next page.
Jri'
Algorithm:
1)
2)
3)
4)
4th
5)
Search sequential the array a for the number x in the indexed segment of a.
array or a
in array
1S.
6)
Return.
II list at the
Efficiency of Algorithm :
riginal data
1tinel value
( The real advanta9e ()f the indexed s~quential mE:thodJs)that the items in the table
~h~ ;;~;mln~;i' ~P~IIPnfi;iilv ' i(ail the
in thefi'fe must be accessed, yetfth~
records
DIEngineers.col'ar:. ~:
\
/
fi{
Mayuranand Classes
8403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. 2 3251 4726, 6525 7069
8216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. B 6517 3281
performed on the smaller index rather than on the larger table. Once the correct
index position has been found, a second sequential is performed on a small portion
of the record table itself.
The use of an index is applicable to a sorted table stored as a linked list, as well as
to one stored as an array. Use of a linked list implies a larger space overhead for
pointers, although insertionsand deletions can be performed much more readily.
If the table is no large even the use of an index does not achieved sufficient
efficiency (either because the index is large. in order to reduce sequential searching
in the table, or because the index is small so that adjacent keys in the index are far
,from each other in the table), a secondary index can be used. The secondary index
acts as an index to the primary index, which points to entries in the sequential table.
Deletions from an indexed sequential table can be :nade most easily by flagging
deleted entries. In sequential searching through the table, deleted entries are
ignored. Note that if an element is deleted, even if the key is in the index, nothing
need be done to the index; only the original table entry is flagged.
8403
B216/217 \J
BIN)
Q.4.
Ans.: C:
numeric
techniqL
Algoritl
1)
Estc:
2)
Estc
3) Set
(a)
(b)
Insertion into an indexed sequential table is more difficult, since there may not be
room between two already existing table entries, thus necessitating a shift in a
large number of table elements. However, if a nearby item has been flagged as
deleted in the table, only a few items need to be shifted and the deleted item can
be overwritten. This may in turn require alternation of the index if an item pointed
to by an index element is shifted. An alternative method is to keep an overflow
area at some other location and link together any inserted records.
k
(key)
0
1
2
3
/~
65
186
319
12
451
16
613
20
kindex[]
pindex[]
r. .
(
'
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
r
(record)
Note:
Binary
10
25
39
47
65
97
123
175
186
213
275
296
319
373
384
413
451
512
539
564
613
639
674
695
713
EfficiE
Assurr
In bin;
each 1
and if
carriec
is 21o~
+IN
Q.
s.
Ans.:
searc
may
Initial
the a
On tl
value
If ke
Repe
of ra1
AI go
1)
2)
Pg. 32
Comp
Mayuranand Classes
6525 7069
La 6517 3281
8403/407, Konark Darshan, Above UTi Bank, Zaver Road, Mulund (W), Mumbai 80. it 32514726,6525 7069
8216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. it 6517 3281
the correct
nail portion
+ BINARY SEARCH
, as well as
terhead for
readily.
d sufficient
d searching
dex are far
1dary index
ntial table.
'JY flagging
~ntries are
~x, nothing
t"
2)
3) Set upper and lower limits (i.e., initially left = 0 and right = n  1);
 (a)
(b)
nay not be
' shift in a
flagged as
d item can
:m pointed
n overflow
then
b.l) adjust lower limit accordingly (i.e. left = mid+ 1)
else
b.l) adjust upper limit accordingly (i.e. right =
mid~1)
Note:
Binary Search algorithm is 0 (log2n)
INTERPOLATION SEARCH
= left + (x 
a[left]*(right left)
1 (a[right]
a[left])
If key is lower than k(mid), reset right to mid1; if higher, reset left to mid + 1.
Repeat the process until the keys has been found or left > ri_g ht or the key goes out
of range, i.e., key < k(left) or key > k(right).
Algorithm:
Pg. 32
1)
2)
oOEngineers.co
Pg. 33
Mayuranand Classes
B403/407, Konark Oarshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. 2 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281
3)
= 0 and
right
=n 
a)
b)
841
. B216/21 .
1).
+IN'
then
b.l) adjust lower limit accordingly (i.e. , left= pos+l)
b.l) aojust upper limit accordingly (i.e ., right = pos1)
A gra1=
a set
rep res
rep res
edge i
In a di
.tail ar
two di
However, if the keys are not uniformly distributed, interpolation search can have
very poor average behavior. In the worst case, the value of rnid can consistently
equal low + 1 or high!, in which case interpolation search degenerates into
sequential search. By contrast, binary search's comparisons are never greater than
approximately /og 2 n. In practical situations, keys often tend to cluster around
certain values and are not uniformly distributed.
HASHING
The g
If (V:
adjac
Hash search is of 0(1) if there are no collisions. But in practice it will be very
difficult to avoid collision. Still we can consider that hashing is faster than other two
searching techniques.
V(Gl)
V(G2 )
G(G3:
The n
Ann
comp
of din
A sut
graph
A pa
Hashing Technique :
Hashing is a searching technique in that the address or index of the element to be
searched is obtained by computing some arithmetic function. A function that
transforms an element into an array index Is called a hash function. If h is the
hash function and key is the element, then h(key) is called the hash of key and is .
the index at which the element should be placed.
a pat
A sin
distin
and J
secor
A eye
is a c
In an
there
if for
in G.
Pn_ 14
DEngineers.c
Com pi
Mayuranand Classes
525 7069
il 6517 3281
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. if 3251 4726, 6525 7069
 B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281
AOA
CHAPTER 4 : GRAPHS
:ion search
uch more,
3risons for
can have
)nsistently
rates into
eater than
:er around
Gl
od we are
aaaressto
ieacraress
key~is' "n ot
the table.
searching
using the
II be very
other two
G2
G3
E(G1)= {(1,2)r(1,3),(1,4),(2,3),(2,4),(3,4)}
G(G3) = (1,2,3}
E(G3)= {<1,2>,<2,1>,<2,3>}
Vp,Vr~V5 ,Vt .... Vq such that (vp,vr),(vr,V5 ) .... (vt,vq) are edges in E(G). The length of
1ent to be
ction that
[f h is the
cey and is
A cycle is a simple path in which the first and last vertices are the same. l, 2, 3, 1
is a cycle in Gl. 1, 2, 1 is a cycle in G3.
Pg. 34
oDEngineers.col
Pg. 35
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. if 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281
B4l
8216/21"
GRAPH REPRESENTATION
[~ ~ ~ ~
Note:
1 1 0 1
1 1 1 1
1.
F~
2.
Ft
The adjacency matrix is also known as bit matrix. In the adjacency matrix 1 can be
considered as true and 0 can be considered as false. So this matrix can be
considered as a Boolean matrix.
3.
4.
If Adj [i][j] = true or 1, then we can say that there exists a path from i to j of
length 1.
AD
1)
Find out Adj2 by multiplying adj with Adj (use Boolean matrix multipliaion
rules)
= true
Similarly, if Adh [i] [j] = true or 1 then there exist a path from i to j of length
3 with Adj 3 is product of Adj 2 and Adj.
In general if Adjn [i] [j] = true or 1 then there exists a path from i to j of length
n, where Adjn is the product Adjn l and Adj.
throu~
graph
repre
ln thi~
lists.
the VE
Each
acces:
L] [ ],
entrie~
the n u
in the
the n
Each
Using
The d
int, int);
#defil
void main()
typed
} nex
nextn
}
void creategraph (int g[ ][ ], int v, int e)
{
int i, j, a, b;
Compiled by Prof. Rajesh Bothra
Pg. 36
Com pi
DEnginears.c m
Mayuranand Classes
525 7069
ss17 32a1
B403 I 407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. if 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank. Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. 2 6517 3281
= 1; j < = v;
g[i][j] =
j + +)
~;
{
printf ("enter the vertices connecting the edges\n");
scanf (" 0/od 0/od", &a, &b);
G is is two
only if the
g[a](b] = g[b][a] = 1;
}
}
Note:
1 can be
ix can be
I(
n i to j of
lultipliaion
from i to j
i of length
j of length
= g[b][a] = 1
1.
For undirected
g[a][b]
2.
For directed
g[a][b] = 1
For weighted
dir~cted
g[a][b] = g[b][a]
g[a][b] = w
Using adjacency matrices all algorithms will require at least O(n 2 ) time as n 2  n
entries of the matrix (diagonal entries are zero) have to be examined where n is
the number of nodes of the graph. When graphs are sparse, i.e., most of the terms
in the adjacency matrix are zero, the time can be reduced to O(e+n) where e is .
the number of edges in the graph. Such a speed up can be made possible
through the use of linked lists in which only the edges that are present in the
graph are represented. This type of representation is known as adjacency list
representation.
In this representation n rows of the adjacency matrix are represented as n linked
lists. There is one list for each vertex in the graph. The nodes in a list i represent
the vertices that are adjacent from vertex i.
Each node has at least two fields : vertex and link.
Each list has a headnode. The headnodes are sequential providing easy random
access to the adjacency list for any particular vertex.
The declarations is Pascal for the adjacency list representation is given below :
#define MAX 10
typedef struct node
{
int vertex;
struct node *link;
} nextnode;
nextnode head node [MAX];
Pg. 36
oDEngi eers.co1
Pg. 37
Mayuranand Classes
8403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. if 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281
edge t
criteric
minim1
Li2IJ1
Vl
Uill1
Uill1
Uill1
V2
V3
V4
V3
N3
V2
V2
I H
I H
[ H
I H
B4!
B216/21 ~
~:~y~t
V4
1.
Tl
SE
V4
V4
a
tr
rT
V3
2.
:1
Ir
a
b
WEIGHTED GRAPHS
Q. 2.
~xplain
tl
weighted graph.
Con sic
Ans.:
+PI
Cons ider the above graph. A number is associated with ~9S.~~!:f.b. or ~Q.9 .~ . . s~LJ,h~
~ra~b.. Such a l!@Qb_. in which.,A_nU_[l~~T. __!_S?._QfJ.9J~d__ with ~9S.h ~,r.~bis ..C.911~Q  ~
weighted _grapt1 or a network: These weights can be cost of construction, the
Tength '~offfie link e'tc.  . .  ....~~ , _
SPANNING TREE
llrsr. search.....,s
resulting''lrom'
knowr:,./as
a breadth
:'...
;f
t/
Sta
...
.
'
Stc
A greedy method to obtain a minimum costspanning tree would build this tree
rni'Y'\nilorl h\1
Prnf
Q~iPc:h Rnthrr~
Pg. 38
oDEngi eers.co1
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, laver Road, Mulund (W), Mumbai 80. if 3251 4726,6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. tr 6517 3281
525 7069
a 6517 3281
edge by edge. The next edge to inClude is chosen according to some optimization
criterion. f rhe simple~t suchc:~iterion wquld be to choo~ean E7c:l9e ~hat results il"' _a
 ~i.r!!rrtum \. (6cr~~se i6_1:b.~ ~~m _9.f th~~ofedges)so far  included: Jheseareh~~o
ways to interpret this criterion.
    
. ,~;;~ :
1.
...:: 
...................
,. ..,
costs
'
. ...
, .... :: ""
 ~
The set of edges so far selected form a tree. Thus, if A is the set of edges
selected so far, then A forms a tree. The next edge (u, v) to be included in A is
a minimum cost edge not in A with the property the A U {(u, v)} is also a
tree. This selection criterion will result in a minimum cost spanning tree. This
method is known as .Prim~s Algorithm .
. 2. ( In,__the second iDt~rpr:et(3tion the edges of th~ . gra.ph (lre considerecj in non
far
is
~Q9.~ ....9.f.Jh.~
I'RIM'S ALGORITHM
h;is called a
ruction, the
Stage 1
imum cost.
Stage 2
2 v~rtic.es
of
_a ~~.P~h
anning . tr~~
om
nnlng 'tree.
rees.
;~
, \\ '\
G)
Stage 3
Stage 4
mning tree T
,is smallas
presents the
. Ji\d this tree
Pg. 38
DEngineers.c
Pg. 39
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W). Mumbai 80. V 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281
.'
r :,_
KRUSKAL'S ALGORITHM
Stage 1
Stage
G)
G)
G)
Algori
2 0
2
4
B4
B216/21
0
0
Given
initial!'
visited
visited
for ea1
In ca~
adjacE
dfs w<
list nc
adjacE
Since
G)l=2
A dep
is unt
alreac
de per
numb
1
Stage 3
BF
Starti
unvisi
are vi
Stage 4
Algor
A bre
vertic
are gl
Initia !
queue
initial
visite
addqt
GRAPH TRAVERSAL
while
Q.
4~
DEPTHFIRSTSEARCH
Pg. 40
oDEngi eers.co1
Each
most
each
Com pi
25 7069
il6517 3281
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund {W), Mumbai 80. if 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 328.1
Algorithm:
Given an undirected graph G = (V, E) with n vertices and an array visited [n]
initially set to false, this algorithm, dfs(v) visits all vertices reachable from v.
visited is a global array.
visited [v] : = true;
for each vertex w adjacent to v
if not visited [w]
then dfs(w)
In case the graph G is represented by its adjacency list, then the vertices w
adjacent to v can be determined by following a chain of links. Since the algorithm
dfs would examine each node in the adjacency lists at most once and there are e
list nodes, the time to complete the search is 0( e). If G is represented by its
adjacency matrix, then the time to determine all vertices adjacent to v .is O(n).
Since at most n vertices are visited, the total time is O(n 2 ).
A depth first traversal traverses a single path of the graph as far as it can go (that
is until it visits a node with no successors or a node all of whose successors have
already been visited). There may be several depth first traversals. The traversal
depends very much on how the graph is represented and how the nodes are
numbered.
Starting at vertex v and marking it as visited, breadth first search visits next all
unvisited vertices adjacent to v . Then unvisited vertices adjacent to three vertices
Algorithm:
A breadth first search of G is carried out beginning at vertex v (i.e., bfs(v)). All
vertices visited are marked as visited [i] : = true. The graph G and array visited
are global and visited is initialized to false.
Initializequeue, addqueue, emptyqeue and deletequeue are functions to handle
queue operations on q.
~
shortest
oms tot
) we are
I vertices
arch and
:selected
h that all
:ed which
from w.
1y of the
Pg. 40
deletequeue
(q,\~);
Each vertex visited get into the queue exactly once, the while loop is iterated at
most n times. If an adjacency matrix is used, when the loop takes O(n) time' for
each vertex visited. The total time is thereforP Ofn 2 ) _
DEnginears.c m
Pn 41
Mayuranand Classes
B403/407, Koriark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. 2 3251 4726, 6525 7069
B216/217Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. 2 6517 3281
.B216.
r:_.,
+
Q. 1
Ans.
SUQ
in for
[I~Y
they
can
( Gr~e
inclu
( f!n_gl
If we are initiating a depth first search starting at the node 1, then the vertices of
the graph may be visited in the order 1, 2, 3, 8, 7, ~' 6, 4. It may be noted that
this need not be the only order with depth first search. If a breadth first search is
initiated from vertex 1, then the vertices of the graph may be visited in the order 1,
2, 5, 3, 4, 6, 7, 8. It may be noted that this need not be the only order with
breadth first search.
gree
at a
later
boo~
Corr
by n
};>
The
we
cane
we1
Comoiled bv Prof. Raiesh Bothra
"
Pa. 42
oDEngineers.co
Com
Mayuranand Classes
; 7069
~ 6517 3281
B~03 1407, Konark Darshan, Above UTI Bank, laver Road, Mulund (W), Mumbai 80.
AOA
CHAPTER 5 : ALGORITHMS
.~;_ .
~\
''
GREEDY METHOD
.I
:~
Ans.: T~e . greedy algprithnis . are usually .most strell9.h tforward. As the name
suggests, fu~i a re sho.r1sT9h.te_~, i!1_therr approach.' ta~lng. ~edslo~~ on the basis o~
informati()n imme'dfately at hand without worrying about the effect these decisions .
m~~y haY."e in future: rhus~ th.ey are easy to inye'nt,"'ea'sy to "rmple'ifient, andwhen"
they workefficient. However, since the world is rarely that simple, many problems
c_an not b~..s.olved correctly ~y s.uch ~ _cr~dE! appr()a<:h.
....  '

ertices of
oted that
search is
~order 1,
rder .with
Commonly, greedy algorithms and the problems they can solve are characterized
by most or all of the following features :
>
We have some problem to solve in _an optimal way. To construct the solution
of our problem, we have a set , (or list) of candidates : the coins that are
available, the edges of a graph that may be used to build a path;. the set of
jobs to be schedules, or whether.
)o>
)o>
)o>
)o>
Yet another function, the selection function, indicates at any time which of the
rem~ining candidates, that have neither been chosen nor rejected, is the most
promising.
Finally an objective function gives the value of a solution we have found. The
number of coins we used to make change, the length of the path we
constructed, the time needed to process all the jobs in the schedule, or
whatever other value we are trying to optimize. Unlike the three functions
mentioned previously, the objective function does not appear explicitly in the
greedy algorithm.
The selection function is usually related to the objective function. For example, if
we are trying to maximize our profit, we likely to choose whichever remaining
candidate has the hiqhest individual value. If we are tryin.g to minimize cost, then
Pn . 4?
oDEngineers.com' shal:gs::
..
Mayuranand Classes
B403/jf.' Konark Oarshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai  80. W 3251 4726, 6525 7069
8 216121
~~rdhman Cham~rs. Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. W 6517 3281
B4
B216/21
Consid
KNAPSACK PROBLEM
Final
subject to '
L wixi s M
ii::l
and 0 s X1 s 1, 1 s I s n
. The profits and weights are positive numbers.
A feasible solution (or filling) is any set (x1, ..... , xn) satisfYing (2) and (3) above.
An optimal solution is feasible solution for which (1) ,is maximum.
Example:
Q. 3.
n = 7, M = 15,
Ans.:
de con
the ~
subin ~
sol uti ~
Solution:
Two
Dl
this?'
divide
Item No.
Profit
Weight
Profit/Weight
Rank
1.
10
2.
3.
5
15
1.66
Consi
the p
perfot
4.
The g
s.
FunC'
6.
7.
18
4.5
Tt
3 .
5
Compil
cr~~
. . "' n"'
n~"'
n.."'
oownloaded from
FaaDoDEngineers.col'
.:
;::~
'
'
Mayuranand .Classes
7069
)517 3281
B403/407, Konark Darshan, Above UTI Bank, laver Road, Mulund (W), Mumbai 80. if 3251 4726, 6525 7069
.
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. ir 6517 3281
1apsack
..
napsack
napsack
napsack
1.
= 14
2.
= 12
3.
4.
s.
6.
=2
Final Configuration :
)Ve.
Profit
Profit
Weight
1.
10
2 .
. 2.
3.33
3.
15
15
4.
5.
6.
18
18
7.
15
55.33
Total
Weight
Item No.
10
Two questions that naturally spring to mind are "Why would anyone want to do
this?' and "How should we solve the subinstances?" The ~fficiency of the
divideandconquer technique lies in the answe'r.to this latter question".
Consider an arbitrary problem, and let adhoc be a simple algorithm capable solving
the problem. We ask of adhoc that it be efficient on small instances, but its
performance on large instances is of no concern. We call it the basic subalgorithm.
The general template for divide~ndconquer algorithms is as follows .
Function DC(x)
if x is sufficiently small or simple then return adhoc (x)
decompose x into smaller instances x1 , x2 , ...... , x1
oDEngineers.col
Pg. 45
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. if 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281
fori~
1 to I to I do Yi
DC(xi)
DYN
Q.4.W
return y
Ans.: R
type of
may chi
B403
B216/217'
Many useful algorithms typically follow divide and conquer approach. Two most
popular algorithms namely recursive quicksort and recursive mergesort use _
this approach. Both the methods divide larger arrays to smaller arrays and keep on dividing them till the size of the array is one . Advantage is taken of the fact that an
element by itself is always sorted.
In general, divide and conquer algorithm for sorting can be outlined as,
function sort(list)
Previou:
to solve
the soiL
happen
the pro
of thesE
pay no
algoritr
to solvE
efficien
quite si
kndwn
Dividedividedivide i
progra1
the sm
we obt
the sol
+BAt
Q. s.
probiE
Ans.:
patten
partiCL
compL
enCOUI
}
Specifically, in mergesort algorithm, any given list is simply divided into two almost
equal sublist and the process is repeated till the list size is one. Care is taken
during merging to merge the lists such that the merged list remains sorted. _
Therefore, the method is called mergesort.
In quicksort, care is taken while dividing the given list in two subparts. The list is
divided by partitioning the list with respect to the pivot element. The pivot element
partitions the array in such a way that all the elements less than the pivot element
forms a sublist, all the elements greater than the pivot element forms another
sublist and pivot element occupies its final position in the list. The process of
partitioning continues till the sublists contain only one element. By this time all the
elements are in their final positions, thereby sorting the array.
In sue
avail a I
built a
searcr
storag
searcr
the gr
at all.
seard
In its
The g1
.struct
to sor
such 1
Gener
to the
add in~
possit
way,
stop
altern
unsuc
comp
oDEngi
eerSa.ComCompil
Mayuranand Classes
169
i17 3281
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80 . .if 3251 4726, 6525 706~
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi MumbaL B 6517 3281
DYNAMIC PROGRAMMING
y; for
;econd
ticular
JOSe X
1nique
n of a
rme of
'ble to
loop.
1e that
faster
Jn the
:; way;
; often
most
rt use
~ep on
hat an
1
Ans.: Richard Bellman first used the term Dynamic Programming to describe a
type of problem in which the most efficient soluti~m depended on the choices that
may change with time instead of being predetermined.
BACKTRACKING
almost
taken
;orted.
~ list is
iement
!ement
nother
:ess or
all the
In such a situation, we use an implicit graph. This is one for which we have
available a description of its nodes and edges, so relevant parts of the graph can be
built as the search progresses. In this way computing time is saved whenever the
search succeeds before the entire graph has been constructed ~ The economy in
storage space can also be dramatic, especially when nodes that have already been
searched can be discarded, making room for subsequent nodes to be explored, If
the graph involved in infinite, such a technique offers our only hope of exploring it
at all. This section and ,the ones that follow detail some standard ways of organizing
searches in an implicit graph.
In jts basic for, backtracking resembles a depthfirst search in a direCted graph.
The graph concerned is usually a tree, or at!east it contains no cycles. Whatever its
structure, the graph exist only implicitly. The aim of the search is to find solutions
to some problem. We do this by building partial solutions as the search proceeds;
such partial solutions limit the region in which a complete solution may be found.
Generally speaking, when the search begins, nothing is known about the solutions
to the problem. Each move along an edge of the implicit graph corresponds to
adding a new element to a partial solution that is, to narrowing down the remaining
possibilities for a complete solution. The search is successful if, proceeding in this
way, a solution can be compl~tely defined. In this case, the algorithm may either
stop (if only one solution to the problem is needed), or continue looking for
alternative solutions (if we want to look them all) . On the other hand, the search is
; ......... ,,,.,..,.,.. .. ;, d iF ~t C'I"\!'Yla ct~no tho n~rti~l c::nl11tinn rnnc::tn1rt'Prl c::n f::tr r::~nnot be
. Mayuranand Classes
8403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund CN), Mumbai 80. V 32514726,6525 7069
8216/217 Yardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Yashi, Navi Mumbai. if 6517 3281
B403/
B216/217 V.
removing as it goes the elements that were added at each stage. When it gets back
to a node with erie or more unexplored neighbours, the search for a solution
resumes.
N QUEEN PROBLEM
void ma
. For solving this problem, we are using a design strategy known as backtracking.
Let us consider the problem for n = 8.
ir
{
p
s
r
}
void nq
Then try to find the place of 2nd queen. Since 1st queen is already placed in 1st
column, the second queen cannot be placed in 1st or 2nd columns. Since if we are
placing 2nd queen in 1st column, then  1st queen and 2nd queen will be the same
column. That is not allowed. Similarly, if we are placing queens in 2nd column then
1st queen and 2nd queen will be in a diagonal.
That is also not allowed. So we can place 2nd queen in 3rd column. So X[2] = 3. This
process continues for all the queens. If we are not able to find a proper location for
a queen then we will backtrack and dry to adjust the position of the previous
queen. If it is also not possible, we will be backtrack once again.
Algorithm:
int place(int k, int x[ ] )
{
int i, flag;
i = 1; flag = 1;
while ((i <= k1) && (flag)
{
if( (x[i]
== x[k]
! ! (abs(ik)
==
flag=$;
else
i++;
}
return flag;
Note:
1.
The above function place will return true if it can find out a proper place for kth
queen in the kth row of the 8 x 8 chess board. Otherwise, it will return false.
2.
In tbe above function place, the expression abs(x[i]  x[k]) = abs(ik) is used
to check whether the queen k is coming in diagonal with any of the queens
from 1st to (k 1)th queen.
Mayuranand Classes
7069
6517 3281
B403/407, Konark Darshan, Above UTI Bank, laver Road, Mulund (W), Mumbai 80. if 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 11, Vashi, Navi Mumbai. 2 6517 3281
~ts
back
solution
1oard so
! on the
x[i]
x[k]
void main()
{
racking.
int n;
printf ("how many queens\n");
~, .... x8)'
~en
and
we are
2nd row
:; in the
nqueen(n);
}
void nqueen(int n)
it be 1.
{
int x[ 10], k
d in
1st
we are
e same
nn then
= 1;
x[k] =
while (k >
q,;
q,)
x[k]
3. This
1tion for
1revious
= x[k]+1;
= x[k]
+ 1;
if (x[k] < = n)
{
if(k
==
n)
{
for (i = 1; i <= n; i++)
printf (" 0/o3d"; x[i]);
printf("\n");
}
else
{
k = k + 1;
x[k]
= <P;
}
}
else
k; /*backtracking*/
}
! .for
kth
lise.
is used
queens
Pg. 48
Pg. 49
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. if 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281
Prob
Giver
what
retur
An e
weig
repre
find c
It ca
chan1
. General description :
The general idea may be described in terms of finding the minimal value of a
function f(x) over a set of admissible values of the argument x called feasible
region. Both f and x may be of arbitrary nature. A t:Jranchandbound proc:edure
~~9U..ir.e~ ~wotogl~. .
 
... ... The
B216/
~rst
A rei
TSP)
the lc
lThe
trans
manL
In ro
holes
then
A!J.Q.t.ll.~r
tool is; bollnding, which is a fast way of finding upper and lower bounds
for the optfmal soh.Jtion within a feasible subregion.
. ., .
. .
Algol
The core of the approach is a simple observation that (for a minimization task) if
the lower bound for a subregion A from the search tree is greater than the upper
bound for any other (previously examined) subregion B~ then A may be safely
discarded from ' the search . This step is called pruning. It is usually implemented
by maintaining a global variable m that records the minimum upper bound seen
among all subregions examined so far; any node whose lower bound is greater
than m can be discarded.

The t
It may happen that the upper bound for a node matches its lower bound; that
value is then the minimum of the function within the corresponding subregion.
Sometimes there is a direct way of finding such a minimum. In both these cases it
is said that the node is solved. Note that this node may still be pruned as the
algorithm progresses.
c
0
c
e
b
e
F
tt
rv
Pg. 50
CompilE
DEnginears.c m
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. if 3251 4726, 6525 7069
B216/217Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281
7069
6517 3281
Problem statement :
Given a number of cities and the costs of travelling from any city to any other city,
what is the cheapest roundtrip route that visits each city exactly once and then
returns to the starting city ?
optimal
and
eration
in 1960
:.~
Je of a
easible
)Cedure
smaller
ldili'lg,
and all
tree or
;tructed
bounds
Algorithms:
task) if
The traditional lines of attack for the NPhard problems are the following:
e upper
~
safely
men ted
1d seen
greater
1d; that
)region.
cases it
as the
);;>
Devising algorithms for finding exact solutions (they will work reasonably fast
only for relatively small problem sizes).
Finqing special cases for the problem ("subproblems") for which either better or
exact heuristics are possible.
For benchmarking of TSP algorithms, TSPLIB a library of sample instances of
the TSP and related problems is maintained, see the TSPLIB external reference.
Many of them are lists of actual cities and layouts of actual printed circuits.
of the
~pea ted
In that
jomain,
1m that
found;
)r each
esigned
stances
is the
~ which
~
') is a
1atori~l
m of a
plex.!!y__
Pg. 50
DEnginears.c m
Pg.
51
Mayurariand Classes
B403/407, Konark Darshan, Above UTI Bank, laver Road, Mulund (W), Mumbai 80. V 3251 4726,6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281
(2) M
AOA
The a
instea
there
8L
B216/2'
void r
MATRIX OPERATIONS
Matrix operations are very useful and common in many areas of engineering and
sciences and are computationally expensive, and therefore, they are of interest to
computer science.
. The first few . sections of this chapter define what a matrix is (at least in the
context of 5Q) and some of the basic matrix operations and their properties. Even
if you are already familiar with matrices, you might find it useful to skim these
sections in order to familiarize yourself with the notation.
Note:
The subscripts or indices of the elements of the matrix range from (0,0) (at the
upper left corner of the array) to (n1, n1) (at the lower right corner). This is
somewhat different than you might see in mathematical texts, where the subscripts
start and 1 and end at n; I have made this change in order to make it easier to
understand matrices in the context of C's zerobased arrays, but you should be
aware that my notation is different than what you might see elsewhere.
The
squc
mult
the
algo
som
For example, the C array written int A[2][2] would be written as matrix.
The matrix element denoted as corresponds to the C array element A[i] [j].
(1) Addition :
Ho~
intri
alga
i~
the matrix
t"fo\Ai
sma
the
rese
prm
algc
disc
{
inti, j;
for (i
= 0;
i < N; i++)
{
for (j
= 0;
j < N; j + +)
+t
{
C [ i ][j]
=A
[ i ][j]
As
B [ i] [j] ;
mul
One
As
the
nee
thaj
Pg. 52
oDEngineers.col
Corr
Mayuranand Classes
}
7 3281
8403 I 407, Konark Darshan,Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. ir 3251 4726, 6525 7069 .
8216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector.17, Vashi, Navi Mumbai. ir 6517 3281
iiiiiiiiiiiiiii
(2) Multiplication :
The algorithm for multiplication is quite a bit different than might be expected instead of simply multiplying the elements together, each element of the product is
the result of several operations, as described in algorithm
void mm_mul (int A[N][N], int B[N][N], int C[N][N])
and
~st to
J
{
inti, j, k;
int sum;
the
Even
these
1
for ( i = 0; i < N; i + +)
{
for (j
= 0;
j < N; j + +)
{
sum= 0;
. such
for ( k = 0; k < N; k + +)
{
.byn
19 the
sum += A[i][k]
* B[k][j];
}
C[i][j]
= sum;
}
at the
his is
;cripts
;ier to
Jld be
The above algorithm , which defines the operation of matrix multiplication for
square matrices, is clear. Since there are many algorithms that use matrix
multiplication, often on relatively large matrices, this can have a serious effect on
the speed of the programs that use these algorithms. For this reason, many
algorithms that use matrix multiplication use various tricks which take advantage of
some particular attribute of the specific matrices used by that algorithm.
matrix
However, for many years it was assumed that general matrix multiplication was an
intrinsically operation, so despite the benefits that a faster ge11eral multiplication
algorithm would have, there was not a lot of research dedicated to finding one.
However, in 1969 Strassen discovered an algorithm
This may seem like a
small improvement (and in fact, it does not really translate into real savings unless
the matrices are large), but it was an astonishing result that spurred a great deal of
research in this area. To the best of my knowledge, however, nobody has yet
proven what the big0 of the fastest possible general matrix multiplication
algorithm is * ***. Perhaps there are some useful and theoretically important
discoveries still to be made .
****.
Pq. 52
oDEngi eers.com
Pg.
53
Mayuranand Classes
8403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai  80. if 3251 4726, 6525 7069
8216/217 Vardhman Champers, Above UTI Bank, NrBabubhai Jagjeevandas, Sector 17, Vashi, Navi. Mumbai. if 6517 3281
BB216/2
principles for handling these matrices can also be used to speed up operations on
other kinds of sparse matrices.
int i, j, k;
int sum;
for (i = 0; i < A> num_rows; i++)
{
for (j' = 0; j < B > num_cols; j++)
{
sum= 0;
for (k = 0; k <A> num_cols ; k++)
{
sum += saGet (A,i,k)
* saGet (B,k,j);
}
This is a step in the wrong direction, however : since saGet and saSet are generally
O(n) operations themselves, the resulting algorithm is in the worst case.
However, there is a way to speed this up considerably by changing the inner loop
(in this code, the k loop) to take advantage of two key facts :
~
The product of any number and zero is zero. Therefore, if we know that either
A[i][k] or B[k][j] is zero, we can skip the multiplication and addition.
~ The loop strides through the actual (nonzero) elements in the array in the
same order that they appear . in the linked lists that are used to represent the
array. Therefore, instead of starting at the base of each list (as saGet and saSet
must do), we can keep track of where we are in each list, so that we can find
the next element very quickly.
The
both
have
orde
itera
the
elerr
Asp
spar
the 1
Let
spar
com
This algorithm is identical to algorithm , except for the inner block, which is
changed as follows:
A ca
and
We'l
***:
This
int i, j, sum;
This
an e
= 0;
Ho\t\
c ! 1 
...J
l.i..
iS VE
"'L
The1
At t
nov..
F"\'..":.L
n&..1..  
Q,..
I:A
oDEngineers.co
Com
Mayuranand Classes
J69
517 3281
B403/407, Konark Oarshan, Above UTI Bank, laver Road, Mulund (W), Mumbai 80. if 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank; Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281.
ons on
orithm
matrix
{
if (row_p > index = = col_p > index)
{
sum += row_p > value* coLp >value;
row_p = row_p > next;
col __ p = col_p  > next;
}
else if (row_p > index < col_p > index)
row_p = row_p > next;
else
col_p = col_p > next;
}
saSet (C, i, j, sum);
.
nerally
The inner loop of above algorithm avoids trying each possible k by moving down
both the row and column lists in tandem, searching for elements in the row list that
have the same index as elements in the column list. Since the lists are kept in
order by index, we know that we can do this in on'e scan through the lists. Each
iteration through the loop moves forward at least one position in one of the lists, so
the loop terminates after at most R + C iterations (where R is the number of
elements in the row fist and C the number of elements in the column list).
=r loop
either
in the
mt the
I saSet
:m find
1ich is
As promised, we will now extend the techniques we have developed for multiplying
sparse matrices where the common value is zero to handle sparse matrices where
the common value is some other number.
Let A be a sparse matrix where most of the elements have value , and B be a
sparse matrix where most of the elements have a value of zero. Our goal is
compute AB efficiently.
A can be written as the sum of two matrices : one where all of the elements are
and the other the difference between this matrix and A.
**,
of A as
We'll denote the matrix that results from subtracting from every element
****, and the matrix that consists entirely of s as ***.
This is useful, because matrix multiplication is distributive.
This property follows from the definition of matrix multiplication; the proof is left as
an exercise.
However, matrix multiplication iS not commutative, in general ***. Therefore, it
is very important to. get the order right when we do multiplication !
Therefore,****
At this ooint. it seems like we're makina more work for
Pg. 54
we are
>gether.
otJrc::PivPc:. hPri=IIIC:P
Pg. 55
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road; Mulund (W), Mumbai 80. if' 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, SeCtor 17, Vashi, Navi Mumbai. it 6517 3281
BB216/2
However, with a little more work we can simplify this calculation enormously.
Since and B are both sparse matrices with a common value of zero, the product can
be computed efficiently using the algorithm described in the previous section.
Since every row in is identical, every row in the product of must also be identical as
well. In fact, each element in the result is multiplied by the sum of the elements in
the corresponding column of B. Therefore, the product is ****.
The sum for computing each value of the first row takes O(n), but once the first
row is finished, each other row is just a copy of the first. Therefore, . this
2
.multiplication is O(n ).
Computing the order of the entire calculation depends upon the "sparseness" of A
and B. If they are very sparse, and the sparse array multiplication algorithm from
the previous section is modified to take full advantage of this (see the exercises for
2
more information), then the multiplication of can be done faster than O(n ), so that
2
the O(n ) addition at the end of the calculation dominates the order of calculation.
If A and B are not so sparse, then this multiplication can be ****.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
_cor
oDEngineers.com____
Con
Mayuranand Classes
9
7 3281
8403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. ir 3251 4726,6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector17, Vashi, Navi Mumbai. if 6517 3281
ANALYSIS OF ALGORITHMS
PAPER SETS
:t can
SEM V (M_ECH)
:alas
1ts in
DECEMBER
!
first
thfs
'of A
from
~s for
) that
3tion.
1.
2.
3.
200~
(a)
(b)
(c)
computer
(a)
(b)
10
(a)
various
data
structures
for
(b) Implement heap sort, keeping data in singly (doubly linked list.
4.
5.
6.
7.
8.
9.
16
(a)
(b)
(c)
(d)
(a)
(b)
Develop program for binary search tree detection with the help of a
subprogram for binary search tree search.
10
(a)
(b)
12
(a)
(b)
(c)
(a)
(b)
12
(a)
(b)
10
18
10.
Pg. 56
14
(a)
(b)
NP hard problems
Pg. 57
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80.
3251 4726; 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai.
6517 3281
(c)
NP complete problems
(d)
Dynamic programming
(e)
B216/;
1.
MAY 2004
Consider the following set of numbers to be stored :
1.
100, 25, 88, 13, 76, 31, 45, 68, 94, .53
.Show a stepbystep (or after each pass) picture of this array as it
gets sorted using each of the following sorting methods :
2.
3.
(a)
Bubble sort.
(b)
(c)
(d)
(e)
10
(b)
I display
10
(a)
I display
(b)
4.
5.
2.
(i)
Inorder traversal
(ii)
Preorder traversal
(iii)
Postorder traversal .
(iv)
3.
10
(b)
10
(a)
10
(b)
10
6.
4.
5.
Explain the following terms for graphs with any suitable examples :
(a)
(b)
(c)
(d)
(e)
(f)
Cr""" ......
n&
n~h c  .. h~.., .
Pn
t;A
6.
Con
oDEngi eers.co1
~t~;~;~::}.
: ..
.' .
~
Mayuranand Classes
69
17 3281
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. ir 3251 4726, 6525 7069
8216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281
DECEMBER 2004
1.
Suppose that each of the four edges of a thin .square metal plate is
maintained at a constant temperature, and we wish to determine
the temperature at each interior point of the plate. To model the
plate, we can use a twodimensional array, with each array element
representing the temperature at a point on the plate. Write a
program that first reads the four constant temperatures (p_
ossibly
different} along the edges of the plate, uses these values, to
initialize the . outer rows and columns of the array, and initializes.
The other elements of the array, which represent interior points to
zero. Then determine the equilibrium temperature at each interior
point by repeatedly averaging the temperature at each of its four
"neighbours" that it, replacing each array element by the average
of the elements immediately to the left, right, above and below it.
Repeat this procedure, displaying the array at each stage,
terminat ing when the new temperature at each interior point differs
from the old temperature by no more than some specified small
amounts.
20
2.
20
4
4
4
4
4
10
10
3
3
3
3.
(a)
Implement the algorithm for Hash search and discuss the algorithm
complexity.
10
{b)
10
(a)
. 10
10
10
10
.4.
5.
(a)
10
(b)
Write notes on :
10
(i)
6.
(a)
Sparse matrix
(i)
(ii)
Evaluati~m
(b)
of postfix expression.

Downloaded from
10
FaaDoDEngineers.col_
:  .   ._1...&...J
!.
Mayuranand Classes
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai ~ 80. if 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6"517 3281
821 1
iiiiiiiiiiiiii
7.
20
(b)
NP Complete problems.
(c)
(d)
Backtracking algorithm.
6.
MAY 2005
.1.
(a)
10
7.
(b)
10
2.
1.
(a)
10
(b)
10
(i)
(ii)
Delete a node based on the data value stored in the nodes of the
DLL.
(iii) Display all the nodes from head to tail of the DLL.
3.
(a)
10
Write a program in 'C' using pointer representation for a BSTBir:'ary Search Tree to perform the following operations :
(i)
2.
4.
5.
Co
(b)
10
(a)
10
(b)
10
(a)
10
(b)
10
.. . . . 
,   ,  ._ ... 
LL  
Pn
hn
Cc
Mayuranand Classes
' 3281
8403/407, Konark Darshan, Above UTI Bank. Zaver Road, Mulund (W), Mumbai 80. ~ 3251 4726, 6525 7069
8216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. 'if 6517 3281
iiiiiiiiiiiiii
Also explain the fact that in some cases a secondary index can
. improve the performance of this search technique.
20
6.
10
(i)
10
(ii)
10
(iii)
10
7.
10
10
(ii)
10
(iii)
10
(iv)
10
DECEMEBER 2005
1.
(a)
Peter, the postman, became bored one night and to break the
monotony of the night shift, he carried out the following experiment
with a row of mailboxes in the post office. These mail boxes were
numbered .1 through 150, and beginning with mailbox 2, he opened
the doors of all the even numbered mail boxes. Next, beginning with
mailbox 3, he went to every third mailbox, opening its door if it was
closed. Closing if .it was open, then he repeated this procedure with
every fourth mailbox, then every fifth mailbox and so on. When he
finished he was surprised at the distribution of open mailboxes. Select
suitable data structure and develop a program in C I C++ to
determine which mailboxes these were.
(b)
10
10
10
10
2.
10
10
20
Magic square
10
10
10
10
. 60
17
24
15
23
14
16
13
20
22
10
12
19
21
11
18
25
aDEngineers.c
Pg. 61
Mayuranand Classes
B403/407, Konark Darshan. Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. 2 32514726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, NaviMumbai. 2 6517 3281
(a)
If a move takes you above the top row in the Jth column, move to
the bottom of the Jth column and place the integer there.
(b)
If a move takes you outside to the right of the square in the Ith
row, place the integer in the Ith row at the left .side.
(c)
B4(
B216/21'
1.
(c:
(a)
(b)
10
10
(i)
(I
Creation
2.
4.
(i)
20
Creation
(ii) Traversals
6.
7.
Write a program for implementing Heap sort, Merge sort and Quick
sort and discuss its . algorithm complexity in terms of Big 0
notations.
20
(a)
10
(b)
10
(a)
10
(i)
3.
4.
10
5.
Pg. 62
oDEngineers.com
Comp
Mayuranand Classes
69
17 3281
B403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. ir 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281 .
MAY 2006
1.
(a)
10
(b)
10
10
{
10
if ( i > j)
printf ("HELLO \n");
else
break;
}
2.
(a)
20
20
10
3.
10
10
10
(b)
10
4.
10
5.
'g. 62
(a)
Explain the following terms for graphs with any suitable example :
(a)
(b)
(c)
(d)
(e)
(a)
DEngineers.c
Pg. 63
Mayuranand Classes
B403 I 407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. if 3251 4726, 6525 7069
B216/217 Vardhman Chambers, Above UTI Bank. Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281
6.
(b)
(a)
(b)
7.
(i)
(ii)
lQ
Backtracking algorithms
(b)
(c)
N P hard problems
(d)
N P complete problems
(e)
! ! !
rnmniiPrl hv Prnf
R;:~ipc::h Rnthr;:~
:.
...
Pn ,:;,4
Bien plus que des documents.
Découvrez tout ce que Scribd a à offrir, dont les livres et les livres audio des principaux éditeurs.
Annulez à tout moment.