Vous êtes sur la page 1sur 156

95

. Downloaded from Faa

oDEngineers.co

Mayuranand Classes
8403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. tl 3251 4726, 6525 7069
B-216/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

Static and Dynamic Structures


Unions
0 Strings
0 Files
0 Macros

(2) Lists:

Abstract Data Types


stacks

! 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

Recursive Definition and Processes


Recursion in C
Writing Recursive Programs
Efficiency .ir;1 Recursion

(5) Binary Tree :


0
0

Binary Tree Operations and Applications


Binary Tree Representations
. ! Node Representations
! Array Representations
! Binary Tree Traversal
! Threaded Binary Tree
! The Huffman Algorithm
0 Representations Lists as Binary Trees
! Finding an Deleting Elements
! Tree-Representations Lists
0 Applications of Trees
! Expression Trees
! Game Tress

oDEngineers.colpg.j

Downloaded from Faa

Mayuranand Classes
B-403/407, Konark Darshan, Above UTI Bani<, Zaver Road, Mulund (W), Mumbai- 80. if 3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, ~ctor 17, Vashi, Navi Mumbai. ir 6517 3281

8-4
B-216/21

LIST OF EXPERIMENTS
(1)
(2)

Strings and files in 'C.'


Implementation of Stack and its operation

(3)

Implementation of Queue and its operation

(4)

Implementation of Circular Queue and its operation

(5)

Array and Dynamic implementation of Linked List and its operation

(6)

Binary Tree implementation, creation of binary tree, insertion and


deletion of nodes in an existing tree

YEARWISE 8r. TOPICWISE MARKS DISTRIBUTION

. 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.)

Downloaded from FaaDoDEngineers.col

Com

Mayuranand Classes

6525 7069
li. lr 6517 3281

B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai, 80. V 3251 4726, 6525 7069
B-216/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

30-47

140

4.

Binary Tree and Recursion

48-79

164

140

148

144
150

I
t

I
r
1:

Pg. ii

Downloaded from Faa oDEngineers.colpg-m

,f

B-41
B-216/21"

STI

Q.l.,
Ans.:
In ne

togetr
becau
For )c
at lee:
en cap
unit, <

by YOI
So, n
togett
built-i

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

Downloaded from Faa

To;
key'
stru
Com1

Mayuranand Classes
B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. if 3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281

DATA STRUCTURES
CHAPTER 1 : INTRODUCTION TO 'C'

STRUCTURES AND UNIQNS .

Q. 1. Write detailed notes on Structures and Unions.


Ans.: Structures:

In nearly every . programming language, it becomes necessary to group data


together to form larger constructs. We do this for many reasons, but mainly
because it's easier for us to think of a group of information as part of a larger item.
For example, when you think of someone's date of birth, you are really thinking of
at least 3 numbers, the day of the month, the month, and the year. But
encapsulating all this data into a single place, we can start thinking of it as a single
unit, and that's very advantageous over keeping track of variables that are related
by yourself.

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
built-in 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;
};

struct dob birthday;


birthday.month = 6;
birthday .day = 2;
birthday. year = 1973;
Now, let's take a look at our various parts. All structures have 2 parts, the
definition and the declaration. Once they are defined and declared, we can use
them. We'll stqrt with the definition, since we must first define a structure before
we can declare it or use it.
Structures are defined using the struct keyword. That keyword is followed by the
name of the structure. The name of a structure is just like a variable type name,
like int or char, so it must be unique. The name of the structure we defined is
called 'dob', short for -date of birth. Once we have the name of the structure, we
need to open a brace {to enclose the members of the structure. This is where we
put all the variables we will have as members o f the structure. We use the same
procedure for declaring variables inside a structure as we do for declaring variables
in a function, except we don't initialize any of the values. This is because these
variables do not actually exist yet, because we haven't created any structures yet,
we're only telling the compiler how to create a structure so that when we tell it to
build one, it will know how. Finally, when we are finished declaring the members of
the structure, we close the brace } and signify the end with a semi-colon,

To actually declare a structure, like we declare a variable, we use the struct


keyword again with the name of the structure (so the compiler knows which
structure to create). and then aivP it r~ vr~ri~hiP nAmP C::n \A/o
"'ob to
IIC".OI"'

.......... ,.. ...

oDEngineers.colpg:!

Downloaded from Faa

Mayuranand Classes
B-403/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

8-4
B-216/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
built-in 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,

Modify the struct.c source file so that it looks like this :

Q. 2.

II C Source File

Ans.:

#include <stdio.h>

Point'

mem

struct dob

So, v
know

Point

int month, day, year;

allow

};

chan

struct Pers{)n

A po

point
char name[20];

Decl;

int height;

int

struct dob birthday;

void

:.~

};

cha1

void printPerson(struct Person person)

Basi
nam

are
int,

I I clear the screen

wan

clrscr( ) ;

II

print the structure information

printf ("Name : 0/os\n", person.name);


printf C'Height : 0/od inches\n", person.height);
printf ("Birthday : 0/od- 0/od- 0/od \n", person.birthday.month,
person.birthday.day, person.birthday. year);

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

B-403/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.

DYNAMIC MEMORY AND POINTERS IN 'C'

Q. 2. Write detailed notes on Dynamic Memory and pointers in 'C'.


Ans.: Pointers:
Pointer-s are core to the 'C' programming language. They allow us to access
memory directly, which lets us to write very efficient and thus very fast programs.
So, what is a pointer ? Basically, it is an address in memory somewhere. We don't
know where, and we don't need to know where. That's why we have the pointer.
Pointers are one of the most useful concepts in 'C'. The reason is that pointers
allow us to keep a single copy of a variable (i.e . the memory we are using) and
change that memory from anywhere in the program.
A pointer, in general, is a number representing a memory address. We call it a
pointer because it is pointing to a place in memory we want to manipulate.
Declaration of pointers can be done as below :
int * :ptr;

I I declares an integer pointer

void *ptr;

II

char *ptr;

I I character poit:1ter, often used for string literals

declares a pointer of unknown type (useful, but easy to misuse)

Basically, a pointer is declared by putting an asterisk * in front of the variable


name. In addition to regular variable types, you can also have void pointers, which
are just pointers of which the type is unknown. The other kinds of pointers (char,
int, float, double etc.) are just the memory addresses of variables. Now, you may
want to know, why would we need to know the memory address of a variable ?
Well, what if we want to change the value of a variable without copying the
variable, and without assigning it the return value of a function. Simple, if we
supply t~e address of the variable, we can change it from any place in our
program. This makes our programs very efficient.

/~!:!.~!11!~ ~.C!m~JI.II.()_c:atio_n..

=..

Up until this time, we have used what is referred to as static memory. Static

memory means we reserve a certain amount of memory by default inside our


program to use for variables and such. While there is nothing wrong with this, it
means that once we reserve this memory, no other program can use it, even if we
are not using it at the time.
How could we possibly remedy this situation ?
nbers
;ewe
Jt we
them
they

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

oown100ded tram Faa oDEngineers.c

m~

Mayuranand Classes
8-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. ir 3251 47.~6i. 6525 7069
8-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector17, Vashi, Navi Munibai. V 6517 3281

B-211

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<

char *str = (char*) malloc(40);

A fL

II allocate memory for a 40 character string

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

Some more functions :

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.

free() returns no value.


realloc() returns a pointer to the newly allocated memory, which is suitably
aligned for any kind of variable arid may be different from ptr, or NULL if the
request fails or if size was equal to 0. If realloc() fails, the original block is left
untouched - it is not freed or moved.

If,
int

+ FUNCTIONS AND MACROS IN 'C'


Q. 3. Write notes on Functions and Macros in 'C'.

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 high-end stereo systems. These stereo systems
do not come in an all-in-one package, but rather come in separate components :
pre-amplifier, 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 top-down programming, because we- first
analyze what needs .to be broken down into components. Functions allow us to
create top-down 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

int add_two_ints (int x, int y)


void useless (void)

sa 1
us

oDEngineers.col

'Downloaded from Faa

Co

Mayuranand Classes
6525 7069
Ji.
6517 3281

8-403/407, Konark Darshan, Above UTI Bank, laver 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. 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

The second header takes in two integers and returns an int.


The last header doesn't return anything nor take in parameters .
A function can return a single value to its caller in a statement using the keyword
return. The return value must be the same type as the return type specified in the
function's interface.

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.

Parameter passing in function :

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().

In 'C', all parameters are passed by value.


In simplistic terms, functions in 'C' create copies of the passed in variables.
These variables remain on the stack for the lifetime of the function and then
are discarded, so they do not affect the inputs ! This is important. Note it again.
Passed in arguments will remain unchanged.
let's use this swapping function as an example : .
void swap (int x, int y)

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 (Macros) :

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

All preprocessor lines begin with #. The unconditional directives are :

~.

Pg.4

#include

Inserts a particular header from another file

#define

Defines a preprocessor macro

#undef

Undefines

a preprocessor macro

Downloaded from Faa

DEngineers.c

Pg. 5

. Mayuranand Classes

B-403 I 407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. ir 3251 4726, 6525 7069
8-216/217 Vardhman Chambers, Ab()ve UTI Bank, Nr Babubhai Jagjeevandas,Sector 17, Vashi, Navi Mumbai. if 6517 3281

The conditional directives are :


#ifdef

If this macro is defined

. ~ifndef

If this macro is not defined

#if

Test if a compile time condition is true

#else

The alternative for #if

#elif

#else an #if in one statement

#endif

End preprocessor conditional

, ,.~

Some examples of the above :


#define MAX_ARRAY_LENGTH 20

B-403
B-216/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)

Tells the CPP to undefine MEANING_OF_LIFE and define it for 42.

Ans.:

#ifndef IROCK

(1) n

(2) fr1

(6)

f\1

f~

n
T

#define !ROCK "You wish!"


#end if
Tells the CPP to define IROCK only if IROCK isn't defined already.

(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-

oownloaded from Faa oDEngineers.com

Comp

Mayuranand Classes
;, 6525 7069
lai. a 6517 3281

8-403/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 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 pre-compilation
directives. It is just a text substitution tool before the actual compilation begins .

.+

SOME LIBRARY FUNCTIONS

Q. 4. Explain the following library functions with example :


~define for

(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, ..... );

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. fprintf() returns
the number of characters written if successful or a negative number on faHure.

cuddle"
!re the

(5) fscanf() :

tave to
)S.

prototyp(3 :

1at you

int fscanf(FILE *stream, const char* format, ... ~);

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
B-403/407, Konark Darshan, Above UTI Bank,.Zaver Road, Mulund (W), Mumbai- 80. tl 3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, NrBabubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281

. ,~ j

J!

l]

B-21E

+
(6) fwrite{) :

,jj

Q.

Prototype:

out

size_t fwrite{const void *ptr, size_t size, size_t nitems, FILE*stream);

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 file-position indicator for the stream (if defined) is advanced by the
number of bytes successfully written. If an error occurs, the resulting value of
the file-position indicator for the stream is indeterminate.

;~

li

The fwrite() function returns the number of members successfully written,


which may be less than nitems if a write error is encountered.
{7) fread{) :
Prototype:

size_t fread(void *ptr, size_t size, size_t nitems, FILE *stream);


The fread() function reads, into the array pointed to by ptr, up to nitems
members whose size is specified by size in bytes, from the stream pointed to
by stream. The file position indicator for the stream (if defined) is advanced by
the number of bytes successfully read. If an error occurs, the resulting value
of the file position indicator for the stream is indeterminate. If a partial
member is read, its value is indeterminate.
Upon successful completion, fread() returns the number of members
successfully read which is less than nitems only if a read error or end-of-file is
encountered. If size or nitems is 0, fread{) returns 0 and the contents of the
array and the state of the stream remain unchanged . Otherwise, if a read
error occurs, the error indicator for the stream is set and errno is set to
indicate the error.

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:

int fseek( FILE *stream, long offset, int whence);


The fseek function sets the file position indicator for the stream pointed to by
stream. The new position, measured in bytes, is obtained by adding offset
bytes to the position specified by whence. If whence is set to SEEK_SET,
SEEK_CUR, or SEEK_END, the offset is relative to the start of the file, the
current position indicator, . or end-of-file, respectively. A successful call to the
. fseek function clears the end-of-file indicator for the stream.

STATIC AND DYANAMIC STRUCTURES IN 'C'

Q. 5. Explain the difference between static and dynamic structure in 'C'.


Ans.: Static vs. Dynamic Data Structures :
Static data structures such as arrays allow :
- fast access to elements
- expensive to insert/remove elements
- have fixed, maximum size
Dynamic data structures such as linked lists allow :
- fast insertion

I deletion of element

- but slower access to elements


- have flexible size

Downloaded from Faa

aDEngineers.c

Lil
Li~

to
(1

Mayuranand Classes
6525 7069

B-403/407, Konark Oarshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. ir 3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr BabubhaLJagjeevandas, Sector 17, Vashi, Navi Mumbai. V 6517 3281

:i. ir 6517 3281

FILE HANDLING IN 'C'

Q. 6. What is the primary advantage of using files for inputting and


outputting?
stream);
' to nitems
by stream.
ed by the
19 value of
ly written,

>;
to nitems
>ointed to
'anced by
ing value
a partial
members
-of-file 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 real-life 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.

Q. 7. Give complete classification of different 'File I/O' methods supported


by 'C' language.
Ans.: An important part of any program is the ability to communicate with the
world external to it. Reading input from files and writing results to files are simple,
but' effective ways to achieve that. When accessing files through 'C', the first

necessity is to have a way to access the files.


For 'C' file I/0, you need to use a FILE pointer, which will let the program keep
track of the file being accessed. (You can think of it as the memory address of the
file or the location of the file .)
For example :
FILE *fp;
Library Functions for File I/0 :

=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'.

fopen() returns a file .Pointer on success or NULL on failure.


The file pointer is. used to identify the stream and is passed as an argument to the
routines that read, write or manipulate the file. The filename and mode arguments
are standard null-terminated strings. The valid modes are shown below.
' Mode

Pg . 8

Use

Open for reading.

Open. or create for writing. Truncate (discard) any previous contents.

Open or create for writing. Append (write after) any previous contents.

r+

Open file for update (reading and writing).

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.

oowrlloaded tram Faa ,oOEngineers.c I

Pg. 9

Mayuranand Classes
B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. if' 3251 4726, 6525 7069
B-216/217Vardhman Chambers, AboveUTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. tif 6517 3281

{2) fclose() :

Files are closed with the function fclose(). Its prototype is :

int fclose(FILE *stream);


fclose() returns zero on success and EOF on failure.

(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 :

B-403
B-216/217 \

The out1
scanf()
output ~
the inpL
conside1
stdin is
and std
Thus,

tr

inti;
scanf ("

int fprintf(FILE *stream, const char* format, .... };

fprintf (

fprintf() returns the number of characters written if successful or a negative


number on failure.

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:

int fscanf(FILE *stream, const char* format, .... );

(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

int fputc(int c, FILE *stream);

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

int *fgets(char *s, int n, FILE *stream);

(2)

It returns a pointer to the character string if successful, or NULL if end offile


is reached or if an error has occurred. The string is also read into the character
array specified as an argument. The character string will be terminated be a
"\0", which is standard for 'C'. At the most, n-1 characters will be read. This
allows for storage of the string terminator, "\0''.
(8) fputs() :

01
The fo
'C' pro

#inclu
#inclu

int fputs(const chars*, FILE *stream);

#inclu

This function writes a string to the stream. It returns EOF on failure.

void n
{

Q. 8. What do you understand by standard files and predefined streams?

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

standard input device (opened for input)

if

stdout

standard output device (opened foroutput)

stderr

standard error output device (opened for output)

stdaux

standard auxiliary device (opened for both input and output)

stdprn

standard printer (opened for output)

Downloaded from Faa

aDEngineers.c

Compil

Mayuranand .C lasses
B-403 I 407, Konark Darsllan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. il 3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if -6517 3281

26, 6525 7069


nbai. ir 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 :

Thus, the statements,


inti;
scanf (" 0/od", &i);
fprintf (stdprn, " 0/od \n", i);

r a negative

f similar to

3nf has one


'er that the
()is:

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.

COMMAND LINE ARGUMENTS

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 MS-DOS 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.

The following program does a low level copy of any file.

'C' program :
#include <stdio.h>
#include <stdlib.h>
#include <process. h >
void main(int argc, char *argv[ ])

!ams?

s to FILE
)les).

FILE *fs, *ft;

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

Downloaded from Faa

Mayuranand Classes
8403/407, Konark Oarshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai -80. V 32514726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. it 6517 3281

8-4
8-216/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

while ((ch = fgetc(fs)) != EOF)

a ope

fputc(ch,ft);
fclose(fs);

Note
enclo

fclose(ft);

Wher

Wher
note

Save the above file as say filecopy.c.


Compile it and build it. Make an executable file.
Now go to 'FILE' option and select 'DOS SHELL' and type the command on the
following prompt as :

C:\tc\bin>filecopy source.txt target.txt


Please make sure that source.txt is present in a current directory; After the
execution of the above command the contents of source.txt will be copied to
target.txt.
argv

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,

(2) Data structure


(3) Purpose
Filename is a string of characters that make up a valid filename for the operating
system. It may contain two parts, a primary name and an optional period with the
extension. Examples :
PROG.C

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, we must specify what we want to do with the file. For


When we open
example, we may write data to t~e file or read the already existing data.
Following is the general format for declaring and opening a file :

FILE *fp;
fp

= fopen

("filename", "mode");

Co

!6, 6525 7069


1bai.

V 9517 3281

Mayuranand Classes
B-403/407, Konark Oarshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. V 3251 4726, 6525 7069
B-216/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.

w open the file for writing only.

a open the file for appending (or adding) data to it.


Note that both the filename and mode are specified as strings. They should be_
enclosed in double quotation marks.
When trying to open a file, one of the following things may happen :
When the mode is 'writing', a file With the specified name is created if the file does
not exist. The contents are deleted, if the file already exists.
~nd

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

Consider .the following statements :

. File *pl, *p2;

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.

a number o.f files

at a time. This number. however depends

perating
with the

function
hey are

He. For

Pg. 12

oDEngineers.col

Downloaded from Faa

13
Pg.

y,:

Mayuranand Classes
B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. if 3251 4726, 6525 7069,
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas,Sector 17, Vashi, Navi Mumbai. if 6517 3281

I:
.

~-

i
!
!

8
B-216/:
.

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

+ ABSTRACT DATA TYPES (ADTS)


Q. 1. What is an Abstract Data Type (ADT) ?
Ans.: A useful tool for specifying the logical properties of a data type is the
Abstract Data Type or ADT.
Fundamentally, a data type is a collection of values and set of operations on those
values. That collection and those operations form a mathematical construct that
may be implemented using a particular hardware or software data structure. The
term "Abstract Data type" refers to the basic mathematical conceptthat defines the
data type.
Let us now formally define an ADT. An abstract data type is a data declaration
packaged together with the operations that are meaningful on the data type. In
other words, we encapsulate the data and the operations on data and we hide them
from the user.

To tt

is a
(top
Inse
stac

ImJ
#de
int

I* c
voic

+ LIST

Q. 2. What are lists ? Explain briefly a stack and a queue list.


Ans.: Lists are sequences of elements. There are two special lists : stacks, where
elements are inserted and deleted at one end only and queues, where elements
are inserted at one and deleted at other.
Lists are particularly flexible structure because they can grow and shrink on
demand and elements can be accessed, inserted or deleted atany position within a
list. Lists have several applications such as information retrieval, programming
language translation and simulation etc.
Mathematically, a list is a sequence of zero or more elements of a given type. We
often represent such a list by a comma-separated sequence of elements

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

B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. S 3251 4726, 6525 7069
B-216/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/

(i) MAKENULL(S) : Make stack S be an empty stack.


(ii) TOP(S) : Return the elements at the top of stack S.

(iii) POP(S) : Delete the top element of the stack.


(iv) PUSH{X, S) : Insert the element X at the top of stack S.
of the data
)recess the

(v) EMPTY{S) : Return true it stack S is empty; return false otherwise.

ARRAY IMPLEMENTATION OF STACK

The simplest way to represent a stack is by using one-dimensional array, say


stack[MAXSIZE] where MAXSIZE is the maximum number of allowable entries or
SIZE of stack. The first element is stored at stack[O], the second at stack[!] and ith
at stack [i -1], 'top' is a variable which points to the top element in the stack.
ype is the
s on those
;truct that
cture. The
1efines the

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*

algorithm to push an element into

~oid

I*
a stack *I

global declaration

*I

push(int x)

I I check for FULL stack

cs, where

if (top > = MAXSIZE - 1)

elements

printf ("Stack overflow");


hrink on
' within .a
ramming

else
stack[+ +top] = x;
}

:ype. We

I* Algorithm to pop element from a stack *I


int pop( )
id to be
1d an is

int t =

<)>;

if(top <= -1)


printf ("Stack is empty");
else
rations

1s take
1

return stack[top--];
}

list or

Pg. 14

Downloaded tram Faa ,oDEngineers.c 1

Pg. 15

May~ranand Classes
B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. W 3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. tr 6517 3281

B
B-216/~

/* Algorithm to print a stack * /

+PI

void print_stack( )

C-1

void
inti;

for (i =top; i >=0; i--)


printf (" 0/od \n", stack[il);

/* Algorithm to return the stack top *I


. int stacktop( )
{
return stack[ top];

}
int

STACK BY USING STRUCTURE :

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 :

I I sl is a variable of type stack .

stack s1;

0 1 2
members l

voi

99

'-11111-----11

r..

L............... -~ . I~----.

top

1100~--~..

voi

1000 sl
(say address)

Let p is a pointer of type stack i.e.


stack *p;

Now assign address of sl to p, i.e.,


p = &sl;

Now to access members of sl by pointer p,

Q.

P -> a[ ]

AI
(tl

p ->top

FI
Cnrnnil.o,.. h,, o.-"f'

o~alf""h

c,....,~""'

........

~.

Downloaded from Faa

DEngineers.c

Cc

Mayuranand Classes

;525 7069
ff 6517 3281

B-403 I 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. if 6517 3281

PUSH AND POP OPERATIONS :

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 -> a[s ->top];

s -> top--;
return

x;

}
}

void create_stack( stack *s)

{
s ->top= -1;
}

void print_stack(stack *s)

{
i_nt i; . .
for (i = s ->top; i >= 0; i-.:.)
printf (" 0/od \n", s -> a[i]);

QUEUES

Q. 4. Explain the Data structure - Queue.


Ans.: A queue is another special kind of list, where items are inserted at one end
(the rear) and deleted at the other end (the front). Another name for a queue is
J=TI::n nr 'firct- in firct nrot lie+ Th,.... ,...'"',....,-,.+-;,...,....,.. ~ ........ ..., ,.,~,....,,,.... --- ...., __ ,,.... __ .. _ ..__ .1..L:>Se fOr
1

Downloaded from Faa

DEngiDIIfS.C

Pg.

17

Mayuranand Classes
8-403/407, Konark Oarshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai - 80. ir 3251 4726, 6525 7069
8-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vaslii, Navi Mumbai..ir 6517 3281

B-403
8-216/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

MAKENULL{Q} : Makes queue Q an Empty list.

1.

Empty'
Scenar

2.. FRONT(Q) : Returns the first element in a queue Q


3.

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:

5. EMPTY{R) : Return true iff queue Q is an Empty list.

CIRCULAR QUEUES

Q. 5. Discuss Circular Queues.


Ans.: In concept, we can overcome the inefficient use of space simply by thinking
of the array as a circle rather than straight line. In this way, as entries are added
and removed from the queue, the head (front) will continually chase the tail (rear)
around the array, so that the snake .can keep crawling indefinitely but stay in a
confined circuit. At different times, the queue will occupy different parts of the
array but we never need worry about running out of space unless the array is fully
occupied in which case we truly have overflow.

Status
Condn

Seen a
(a)

max-1 max-2

2
In

thi~

Statu

Cond

Circular queue

Seen

to=~:Qax-1
r
l .
.

Occupied

front

(a)

max-2

rear

Unwinding

(b)

In C, we can increase an index i by 1 in a circular queue (array) by writing


if(i >=max -1)
i = <j>;
else

i= i

(c)

+ 1;

or by modulo division operator ( 0/o), we may write it as


i = (i +1) 0/o max
where max is size of circular array.

Cor-=- .........

I"\--~

r"\-.!--L

.... _L_L __ _

Downloaded from Faa

DEngineers.c

Com

Mayuranand Classes

5525 7069
. ir 6517 3281

8-403 I 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. 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

Status : Empty Queue


Condition : if (rear = = front - 1)
error ("Queue is Empty \n"); .

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.

Status : Full Queue


Condition: if (front==~) && (rear==. QSIZE- 1)
error ("Queue is Full \n");

~cenario

(a)

{III} :

~~~
0

front=

(b)

(i)

add 10

(ii)

add 20

r.

(iii)

add 30

rear=

(iv)

add 40

Operations .:

~
2

(i) delete (Q) ... 10 is rem.

(ii) delete (Q) ... 20 is rem.

r 1

front =
(c)

rear = 3

~~
l l
0

Operations :

Operations :
(i)

add 50

(ii) add 60
(iii) add 70

rear= front =

>g. 18

Downloaded from Faa aDEngineers.c

IP9.19

Mayuranand Classes
B-403/407, Konark Darshan, Above UTI Bank, laver 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. ft 6517 3281

8-4C
. B-216/21i

Status : Full Queue

OPI

. Q~ 6. E

Condition: if (rear== front- 1)

Ans.:

error("Queue is Full \n");

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

(ii) delete (Q), 20 is removed

I*

Als

void ir
{

rear = 2

Status : Contains only 1 element


Condition: if (front

==

rear) then

Queue contains single element.

Conditions in I and III scenarios are same but decisions are exactly opposite.

Scenarios 2 and 3 are same i.e. status is same (Queue full).

Now if we look properly, both the scenarios are same i.e. front is followed by
rear.

Following expression is valid in both situations.

1*

The expression is

int de

(rear+ 1) 0/o QSIZE == front

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:

if(((rear + 1) 0/o QSIZE

==

front) && (rear> -l))

error("Queue overflow \n");


EMPTY QUEUE:

if(rear <= -1)


error(" Queue Underflow \n");

CcDownloaded from Faa

DEngineers.c

Com~

Mayuranand Classes
,6525 7069
ai. ir 6517 3281

B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. tr 3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. tif 6517 3281

OPERATIONS ON A CIRCULAR QUEUE

Q. 6. Explain various operations performed on a circular queues.


Ans.: (i) Using Special Indices (Front and rear) :
C- Code:

#define QSIZE 3
int q[QSIZE], front, rear;

I*

Algorithm to create a circular queue

*I

void create_queue( )

{
int front = Q>;
int rear= -1;
}

I* Also to insert element into a circular queue *I


void insert(int x)

I* x to be inserted in a circular queue *I


if (((re,~r + 1) 0/o QSIZE =

= front) & & (rear>

-1))

printf("Queue overflow \n");


else
{

I* Queue i.s not .full *I


osite.

rear= (rear+ 1) 0/o QSIZE;


q[rear] = x;

owed by

}
} .

I* Algo to delete element from a circular queue*/


int del-element( )
{

int x;

>case.

if(rear <= -1)


printf("Queue is Empty \n");
else
{ .

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

Downloaded from Faa

aDEngineers.c

Pg. 21

Mayuranand Classes
B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai - 80. if 3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. V 6517 3281

B
B-216/~

C-I

QUEUE BY USING STRUCTURE

Func

Q. 7. Write a program to create Queue ADT using array implementation.


Queue ADT should support the following operations :

!* Cr

(i)

void<

create queue

(ii) insert into a queue

(iii) delete from a queue

(iv) destroy a queue


Ans.: For circular array based implementation of queue, we define the abstract
data type queue as below :
#define QSIZE 3

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

Members of structures now can be accessed by pointer as below.

qptr -> a[i];


qptr -> front;
qptr -> front;

(Downloaded from FaaDoDEngineers.col

Com

Mayuranand Classes
6525 7069
li.. 6517 3281

B-40~ /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. ir 6517 3281

C - Implementation :
nentation.

Functions:

I* Create the queue *I


void create_que(queue *q)

{
q -> front =

~;

q -> rear= -1;


1e abstract

I* Function to add (insert) element in a queue*/


void insert( queue *q, int x)

I* x

-> element tobe inserted

*I

if(((q -> rear+ 1) /o QSIZE == q -> front) && ( q -> rear> -1))
0

printf("Queue is FULL \n");


else

q -> rear= (q -> rear+ 1) 0/o QSIZE;


q -> a[q -> rear] = x;

}
}

I* Function to delete element from a queue *I


int del_ele(queue *q)

{
int x;
if(q ->rear<= -1)
printf("Queue is Empty \n");
else

x = q -> a[q -> front];


if(q ->front!= q ->rear)
q -> front = (q -> front+ 1) 0/o QSIZE;
else

I*
I*

Queue is now Empty*/


Call create_que( )

q -> front

*I

= <1>;

q ->rear= -1;

}
return x;

//end

else

}
22
Pg.

Downloaded tram Faa

oDEngineers.c IP9.23

Mayuranand Classes
B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80; W 3251 4726, 6525 7069
B-216/217 Varqhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. ir 6517 3281

8B-216/2

iiiiiiiiiiiiiii

I* Algorithm to print a queue *I

Q. 9.

void print_que(queue *q)

Ans.:

else

The
perfo1
one's
may I
a tim,
multi I
must

Many

inti;
if(q -> rear<= -1)
printf("Queue is Empty \n");

for (i = q -> front; i != q -> rear;)


{

printf(" 0/od \n", q -> a(i]);


i = (i

+ 1) 0 /o QSIZE;

}
printf(" 0/od \n", q -> a[i]);

I* end of else *I

Requ
than

pr

nE

se
'The

PI

Now, write a main program.

PRIORITY QUEUE

Q~

8. Explain priority queue.

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

Ordinarily, extracting the minimum element of a priority queue represented by a


binary search tree involves travelring down. the left side of the tree from the root.
This is first step of the ir:torder traversal process.
However, since no new elements are inserted into the tree once the tree is
constructed and the minimum element does not actually have to be deleted, the
. inorder traversal efficiently implement the successive selection process.
Post

Downloaded tram FaaDoDEngineers.co

..---

Com~

Mayuranand Classes
8-403/407, Konark Darshan, Above UTI Bank, laver Road, Mulund (W), Mumbai 80. tr 32514726,6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. 6517 3281

6525 7069
ai. a ss17 3281
I

Q. 9. Give some applications of queue.


Ans.: Applications of queues :
The applications are more common .than are applications of stack, since in
performing tasks by computer, as in all parts of life, it is so often necessary to wait
one's turn before having access to something. Within a computer system, there
may be queues of tasks waiting for the printer, for access t.o disk storage or even in
a time-sharing system, for use of the CPU. Within a single program, there may be
multiple requests to be kept in a queue, or one task may create other tasks, which
must be done in turn by keeping them in a queue.
Many examples in a computer's operating system
Requests for services come in unpredictable order and timing, sometimes faster
than they can be serviced (like at a bank window, cafeteria, etc.)

print a file

need a file from the disk system

send an email

"The print file is in the queue". Your outbox is a queue.

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

io. Give some applications of stacks.

( 1) Expression evaluation

(2) Backtracking (game playing, finding paths, exhaustive searching)


ease or
! clearly

(3)

lements

(1) Expression evaluation :

Memory management, run-time environment for nested language features.

Infix, Prefix and Postfix Notation :


and a

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)

*+ab-ed

ab+cd-*

b*b-4*a*c
40- 3 * 5 + 1
Postfix expressions are easily evaluated with the aid of a stack.

Pg.

24

Downloaded tram Faa ,oDEngineers.c

IP9.2s

Mayuranand Classes

8-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. ir 3251 4726, 65257089
B-216/217 Vardhman Chambers, Above UTf Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai.
6517 328'1

8-40:
B-216/217

Postfix Evaluation Algorithm :

Each pr
contain

Assume we have a string of operands and operators :


(l) Scan the expression left to right

(2) Skip values or variables (operands)


(3) When an operator is found, apply the operation to the preceding two operands

(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 remains--the 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);
}

else if (token instance of operator)


{
Op2 =pop();

opl =pop();

lose'

result = calc(token, opl, op2);

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 gam-e 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

We need some way to remember these decision points in case we want

come back and try the alternative.

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 dead-end. 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.

(3) Memory Management :


Any modern computer environment uses a stack as the primary memory
management model for a running program. Whether it's native code or others, a
stack is at the center of the run-time environment for Java, C++, Ada, FORTRAN etc.

aasl
posi
vaiL
WOL

obtc

For
fin a
the1
The

ma'
,....---~--'

L ..

"'--1!

n_.:. __ ._ n.-.&..l---

n-

-"\C

oDEngineers.col

Downloaded from Faa .

ColT

525 7069
it 6517"3281

Mayuranand Classes
8-403/407, Konark Darshan, Above UT18ank, Zaver Road, Mulund (W), Mumbai- 80. R '3251 4726, 6525 7069
8-216/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

Josephus Flavius Problem :


Josephus Flavius was a famous Jewish historian of the first century at the time of
the Second Tempte destruction. During the Jewish-Roman war he got trapped in a
cave with a group of 40 soldiers surrounded by Romans. The legend has it that
preferring suicide to capture, the Jews decided to form a .circle and, proceeding
around it, to kill every third remaining person until no one was left. Josephus, not
keen to die, quickly found the safe spot in the circle and thus. stayed alive.

(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,

.Downloaded tram Faa

aDEngineers.c

9 27
'

Mayuranand Classes
B-403/407, Konark Oarshan; Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. 3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. il 6517 3281

B-4C
B-216/21i

meh,

wl

which makes y = 2. Hence, had there been 47


the man last chosen would
have originally occupied the second place. Similarly had there been 47+x men, the
man would have occupied originally the yth place, where, subject to the same
conditions as before, we have y=(2+3x)-(47+x)=2x-45 . If x = 23, y = L Hence,
with 70 men the man last chosen would have occupied originally the first place.

I* This program used a circular queue *I


#include <stdio.h>
#define MAX 50

I* Implementation of circular queue *I


int queue[MAX], e, f, r;

I* _f is front; . .:..r is rear & _e is element number *I


I* A general insert algorithm act over queue *I
void insert(int i)
{
r++;
e++;
if(r >=MAX)

r = 1;

!** e

queue[r]

main I

= i; .

I* A general delete algorithm act over queue *I


int remove( )

{
inti;

e--;
i

= queue[ f);

f++;
if (f >=MAX)

f = 1;
. return i; .
}

I** End of circular queue **I


I* A general Josephus function *1
I* This function starts removing element from first element and returns survivor *I
intjosephus(int n, int v)

{
register inti;
e = n;
for (i

= 1; i <= n;

i++)

queue[i] = i;

= 1;

r, = n;

II
II

0 for surviving first element.


n+ 1 for surviving first element.

i = 1;

Ccoownloaded from Faa oDEngineers.com

Com

.
;525 7069
6517 3281

Mayuranand ,Classes

8-403 I 407, Konark Darshan, Above UTIBank,Zaver Road, Mulun_


d (W), Mumbai- 80. ir 3251 4726, 6525 7069
8-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. 6517 3281

while ( e ! = 1)

sen would
the
the same
L Hence,

~men,

if(i != v)

place.

i++;

insert( remove());

}
else
{

remove();
i = 1;
}
}

I I end of while loop


return queue[f];
}

I**

end of Josephus function

**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

Downloaded from Faa .

Pg. 29

Mayuranand Classes
B-403 i 407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80 ..if 32514726, 6525 7069
8-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, NaviMumbai. ir 6517 3281

DATA STRUCTURES
CHAPTER 3 : LINKED LIST

BB-216/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

Q. 1. Explai11 stati.c and dynamic variables.


Ans.: Variables that can be used during execution of a C program_:CC)me in two
forms.
Static varia~les are those that are declared and named, .as usual, while writing
the program -space for them exist as long as the programs . in which they are
declared ere running. There is a storage class for variables in 'C' called static; the
variables are known only in the function where they are declared anq_ their' space
exists for the duration of main program.

Dynamic variables are created (and perhaps destroyed) during program


. execution. Since dynamic variables do not exist while the program is compiled, but
only when it is run, they cannot be assigned names while it is being writt~fl.
The only way tO access dynamic variables is by using pointers once. It is created,
trc~wever a dynamic variables does contain data. and must have a type like any
other variable.

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

us~s an asterisk (*) to denote a pointer, If p is a pointer to character, we


declare it by :

'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-

typedef struct node_tag

ty~

} node;
node *q;
}

CREATING. & DESTROy'l:NG DYNAMIC VARIABLE

Q. 2. Explain malloc(} and free() functions.

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.

oovmloaded tram Faa

DEngineers.c

-c

Mayuranand Classes
6, 6525 7069
)8i. 2 6517 3281

B-403 I 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. 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 one-way 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

NODE STRUCTURE AND DECLARATION

allocated
ereas if a
ven after

1cter, we

Information I
data field

Link I pointer field


(To store address of the next node)

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

Such a structure is called self-referential structure .

Pg. 30

Downloaded from Faa

aDEngineers.c

Pg. 31

Mayuranand Classes
8~403/

B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W),Mumbai -'SO:. jil3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vaihi, Navi Mumbai. if 6517 3281

B-216/217 Vc

LINKED LIST REPRESENTATION

INSE

Assume
data

START

~~,

link

data

link

d:qta

link

data

link

1-1 ! I - [ -Fj La

.--+--.

header

node

node

node

node

tail

(Contains adds of first of first node of a linked list)


Case 1
typedef struct node_tag

Case 2

case 3
irit'data;

. ' ... struct node_tag *link;

Case 1

(Start \

} node;

I* Algo to create a node dynamically*/


node *getnode( )

G
St

return (node*) malloc (sizeof(node));


}
Case:;;

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.

Traversing through a list

Case

GQ
Stc:

+ D
A gi\

Orig

tra ... local pointer

CrD~~Ioadoo tram Faa oDEngineers.com

Ex

Cor

6525 7069
3i.
6517 3281

Mayuranand Classes
8-403/407, Konark Darshan, Above UTI8ank, Zaver Road, Mulund (W), Mumbai- 80. V 3251 4726, 6525 7069
8-216/217 Vardhman Chambers, Above UTI8ank; Nr 8abubhai Jagjeevandas,, Sector 17, Vashi, Navi Mumbai. V 6517 3281

+
ink

~tail

INSERT OPERATION

Assume the given list is an ordered list and is given below :

5!

~-----1
Start

2001---+11112

100

!300,___.,,15! 400~ I 20 !NULLI

200

300

400

Case 1 : Node may be inserted before a first node.


Case 2 : Node may be inserted after a last node
Case 3 : Node may be inserted between two nodes

Case 1 : New node to be

in~erted

having data value say 3.

(Start will be modified)

GD----c::1o ~j12l3ool~~
.

Start

50
~ew

100

200

300

400

node

Case 2 : New node to be inserted having data value say 25.

~---1
Start

s ;2o9~!1sl4ooj~
100

200

300

400

Case 3 : New node to be inserted having data value 18

rsing we
1odifying

~---is ~ooj~~start

100

200

300
new node

DELETION OPERATION

A given list is as shown below :


Original list

..---.-~--.
.

GQ:>----1s ~ooj~~~
Start

100

200

300

400

~:

Ex: Say a node (Data_value = 15) to be deleted

~
Start
Pg. 32

:4oo~--~--~

js :3ooj------11o
100

300

..

lNuLLJ
400

oDEngineers.col

Downloaded from Faa .

Pg. 33

Mayuranand Classes
B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai - 80 ..if 3251 4726, 6525 7069
B-216/2.17 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. V 6517 3281

B-403
B-216/217 \i

Step 1 : Search a node to be deleted.

Some o

Step 2 : Ifpresent, delete a node.

I*

A fur

Case l : A node may be a first node.

Say star

Case 2 : A node may not be a first node.

(a)

B,

Step 3: Return address of a deleted node.

SEARCH OPERATION

I*

Algo to search for the data item in a list */

1st

2nc

void ~~arch(i'1t x)
' 'i!.

'

{
A

I* x- data item to be researched *I


node *find;
find

= start;

while((x != find -> data) && (find ! = NULL))


find = find-> link;
if( find !

= NULL)

printf("Node is present\n");
else

(b)
printf("Node not found \n");

I*

A function .to count no of nodes in a given linked list*/

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

Prototype of create_list( ) function is as below :


void create_list(node **s);

Co

Downloaded from Faa

DEngineers.c

Comp

3, 6525 7069
~ai. ir 6517 3281

Mayuranand. Classes
B-403/407, Konark Darshan, Above UTI Bank, laver Road, Mulund (W), Mumbai- 80. e 3251 4726, 6525 7069
B-216/217Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. it 6517 3281

Some other operations on linked list:

I* A function to combine two linked lists *I


Say startl and start2 are header pointers for 2 linked lists and lists are created.
(a)

Before combination :

~------.Empty list

1st list j NULL


startl

2nd

Before
Combining

list~~-~
start:2

100

7l 300 l~l4l NULLI


200

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

--+

void combine_list(node **startl, node *start2)


{

node.: *tra;
if(*startl

==

NULL)

*startl
to NULL,

I* i.e. if first list is empty *I

= start2;

else

because

tra = *startl;
while(tra -> link != NULL)
tra = tra -> link;
tra -> link = starti;

}
}
Pg. 34

Downloaded tram FaaDoDEngineers.co

Pg. 35

Mayuranand Classes
8403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80-. 9'3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, NrBabubhai Jagjeevandas, Sector 17, V~.~~~ N~vi Mumbai. if 6517 3281

8-40
8-216/217

/* A C-function to reverse a given singly linked list */

'top' co

Existing linked list

Initially

1100rt 1----+1

~-----+ljlolNuLy

"--2-~~

sta

~~~

Let us,

300

LINKE

type de

!NULL: 911-,-----1~ii]i'f-'---tl200: 101i'1-'-----t._3_0_0__,


100
200
300
Start

} nod1

void reverse_list( )

node:

!*fun
node * t1, *t2, *prev;

node

prev =NULL;

t1 = start; .
while (tL!~ NULL)

t2 = t1 -> link;

/* fu

t1 -> link = prev;

void

prev = t1;

t1 = t2;
}

start = prev;
}

I* A

LINKED LINK IMPLEMENTATION OF STACK ADT

It is easy to implement stack as linked structure in dynamtc memory. To do so, we


first need declaration of structure of a node

1.

typedef struct node_tag

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

Downloaded tram FaaDoDEngineers.co

Mayuranand Classes
)525 7069
.a 6517 3281

B-403/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

'top' contains the address of the last node.


Initially top = NULL implies stack is EMPTY.
Let us define all possible operations on stack.
LINKED STACK - ADT :

typedef struct node_tag

{
int data;
struct node_tag *link;
} node;

I I Global deciaration
I* function to get a new node *I
node *top;

node *getnode( ) .
{

return (node *) malloc (sizeof(node));


}

I* function to destroy a node *I


void freenode(node *p)
{
free(p);
}

/* AI go to push a node into a stack* I


) so, we

1.

NULL

~------~ E~pty ~tack

top

2. Push first node


100

~------,.jNuLLl

sl

top
nd pop

3. Push second node

.____2_oo___.L,
top

[N"uLLl

',

sj~....,._.... J100

....... ________
100 _

l1l
200

....

4. Push third node


300
top

I NULLl sj
... __ 100

j1oo 7 lot-I--,~. . ~I 200


200 ___ ,,..
300

--- ------------

i 91

--~

Address field contains address of previous node.

Pg. 36

Downloaded from Faa

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
B-216/217'\tardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 11, Vashi, Navi Mumbai. V 6517 3281

B-403 J
8-216/217 v

void push(int x)

I* x --

Data value for a node to be pu_shed

*/
}

node *nptr;

nptr = getnode( ) ;
if(nptr = = NULL)

+ LINI

printf("Unable to push non-:-existent node");

Linked 1
two poi1
of the q

else

{
.J1ptr -> data = x;

Node st

nptr -> link = top;

typedef

top = nptr;

}
}

I*

Algo to pop a node from a stack * 1

.... ....

,,~

~-~

--------------------

NULL: 5

300

--

} node
...

As wit!
from 'r

... ......

1'---1100; 7 ~~_ _ ,r-.. 2""Z"'Oo-.T-:9__,,


1

100

top

--~

200.

300

LINKE

1. pop a node

----------------

INULLl si--T 10o : 71

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. (

Now stack is EMPTY


int pop( )

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

Downloaded from Faa .

Corr

Mayuranand Classes
i, 6525 7069

ai. ff 6517 3281

B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. tr 32514726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. V 6517 3281

top = t -> link;


freenode(t);
return x;
}
}

LINKED LIST IMPLEMENTATION OF QUEUE - ADT :

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;

struct node_tag *link;


} node;
As with the entries of contiguous queue (i.e. array queue), we shall insert node
from 'rear' end and delete node from front node.

LINKED QUEUE :

To create a

queue~

set front and rear to NULL

front = rear = NULL;

Simple implementation of insert and delete operation :

I* declare front and rear as global pointers~ I


I* Algo to insert node into a linked queue ~*I
1.

2.

NULL

NULL

front

rear

Insert first node

front

~ ~ ..---..----.,

. .

rear, ~
Pg. 38

Empty queue

Is

100

Downloaded from FaaDoDEngineers.col

Pg.39

Mayuranand Classes
8-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. ti 3251 4726, .6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. il 6517 3281

3.

1. dele

Insert second node

1oo .....j ____...I s : 2oo I....----~~~.....___N,__.~

front

100

front

200

200

rear

8-40
8-216/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

I* x- - data va:lue of new node *I


node *nptr;
nptr = getnode( );

re,

if(nptr = = NULL)
printf("Unable to insert non existent node \ n");
else
int d

I* node is .created *I

nptr -> data = x;


nptr -> link = NULL;
if(front == NULL)
front.= rear = nptr;

II Empty queue
I I first node

else

{
rear-> link=, nptr;
rear = nptr;

}
}
}

/* Algo to delete a node from


front ( 100

rear

300

a linked queue

*1

1----1111 5 : 200 j~-----~[71300]

[9

:NUll]

___/
r-------------~--------------

Q.

Ar
be
so
th

Downloaded from Faa

DEngineers.c

Co

Mayuranand Classes
8-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. ir_3251 4726, 6525 7069
8-216/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

Queue is Empty now

int del_node( )
{
int x;
node *nptr;

== nptr)
if(front ==

if( front

NULL)

printf( .. Queue is Empty \n .. );


else
{

nptr = front;
x = nptr -> data;

front = .riptr -> link;


free(nptr);
return x;
}
}
}

DOUBLY LINKED LIST (2-WAY LIST)

Q. 3. Explain doubly linked list and operations.

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

Downloaded tram FaaDoDEngineers.com

Pg.

41

Mayuranand Classes
8-403 I 407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80 ... if 3251 4726, 6525 7069
.a-216/217 Vardhman Chambers, Above UTIBahk, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. ir 6517 3281

B-403
B-216/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

NODE STRU-CTURE AND DECLARATION :

fn
}

TRA

void fwc

{
....~

*next (pointer I link field) -


- To store address of next node

*prev
(pointer /link field)
- To store address of
previous node

information field
{

C-declaration :
}

typedef struct node_tag


}

/* funct

int data;
struct node_tag

~prev,

void bk.

*next;

} node;

t
v

DOUBLY LINKED LIST :

......__~'-------1 ::::::~ 1001

13oo ~:::::::'---~----~

200

first
To point first node

last
To point last node

+
C-implementation :

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

Downloaded tram FaaDoDEngineers.co

Compile

Mayuranand Classes
1525 7069
ii' 6517 3281

8-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai. 80. V 3251 4726, 6525 7069
8-216/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

void freenode(node *p)


{

free(p);
}

TRAVERSE OPERATIONS

void fwd_traverse( )

{
node *tra;

tra

= first;

while(tra ! = NULL)
{

printf(" 0/od \n", tra -> data);


tra

= 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

A given list is as below :

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

Downloaded from Faa

aDEngineers.c

Pg. 43

. Mayuranand Classes
B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai - 80. R 32614726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi~~mbai. R 6517 3281

Case 1 : Say data value

-----....

.,.,. .,.

:'I I
N

',,

...
.

3 1100

so

case 1 :

=3

'

'

~
,

so

,./

I5

1200 ~ 100 115 1300 ~ 200 120


.

100

..... _~---new node

200

300

last

first "'edified
Case 2: Say data value

Is

Case 2

=25
, ,.

!2oo

)
.

....---30-0---..,

,,-------- ........

~ too Its 13oo ~ 200 I 20 14oo ~ 3oo I 2s I N

''
)
': '

100

200

300

', ...

........

400

new node--1

first

I.5

...--

4oo

,. /

. last modified

Case 3: Say data value

1200

Case~

= 18

~ 100 1151250

100

200

.,. ..,.

----- .... . ..

t8 200118130~ .~

250 1_20_1-...N )

' ....... ______


' 250 ... - ~

300

new node

400
start

last

DELETE OPERATIONS

To delete

B-403
B-216/217 ~

c
+ c

a node from a DLL, following steps are to be followed :

A cir
havir

Step 1 : Search a node to be deleted.


Step 2 : If present then delete a node and return its address.

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

Mayuranand Cl-a sses


6525 7069
li. it 6517 32&1

B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. til 3251 4726,6525 7069
B-216/217 Vardhman Chambers, Above. UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai..If 6517 3281

<;ase l : If node whose value

first

= 5 to

be deleted

find

last

modified

st

Case2 : If node whose value =7 to be deleted


deleted
node

first

Case 3 : If node whose value

last
modified

. find

= 10 to be deleted

~).

deleted node

]
first

find

last

CIRCULAR LINKED LIST

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

Downloaded from Faa

p;4s

Mayurariand Classes
B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80 .. ii 3251 4726, 6525 7069
B-216/217Vardhman Chambers, Above UTI Bank, Nr Babubhpi Jagjeevandas, Sector 17, Vashi, Navi Mumbai. V 6517 3281

B-403/407
B-216/217 Vardh

l* Algo to create a circular linked list *I

I* Algo tot

typedef struct node_tag

void

traver~

node

int data;

tra =

struct node_tag *link;

whilE

} node;

II Global variable
I* function getn9pe( ) *I
node *tail;

node *getnode( )
}

prin1

return (node*) malloc (sizeof(node));


}

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')
{

if( tail = = NULL)

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~',

&curr -> data);

curr.-> link= tail -> link;


tan -> link = curr;
tail = curr;
}

printf("Want to continue (YIN) \n'');


fflush(stdin);
scanf(" 0/oc", &ch);

}
}

I I end while

//end algo

Downloaded from FaaDoDEngineers.co

Compiled t

Mayuranaa:d Classes
, 6525 7069
ai. V 6517 3281

B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. tt 3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, NaviMumbai. tt 6517 3281

I* Algo to traverse through a circular linked list *I


void traverse( )
{

node *tra;
tra = tail -> link;
while(tra ! = tail)

{
printf{" 0/od\n", tra -> data);
tra = tra - > link;
}

printf(" 0/od\n", tra -> data);

I I to print tail node

. :. s-~

Pg. 46

Downloaded tram FaaDoDEngineers.comPQ.47

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

Ct:JAPTER 4 : Bl;NARY TREES AND RECURSION


-: BJNARY TREES

INT~ODUC"rJ;-<>N

Q. 1. State th~ advantage of non-linear data structures over linear data


structure.
Ans.: So far we. have seen the linear data structures like arrays, stacks; queues
and linked list. One of the important aspects that we can seen . in , these data
structure is, the relationship among the data elements is one dimensionaL In
simple words, we can define linear data structure is the data structure in which one
memory locationis followed exactly by one location only.

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

B-403/407, I<
B-216/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

But, such representations are insufficient or difficult; when we have to represent


one to many relationships. For example, we want to store the information within a
computer system having root directory, subdirectory and all related files well one, if
at all things of representing this information using linear representation, then we
may have to spend much of time,. space and won't know whether the scheme will
function. The best way out of it is to use Non-Linear Representation.
These non-linear structures are capable of expressing more complex relationship
than that of physical adjacency. In short, if one wants to store an information in a
hierarchical form then non-linear "data object" is tree. Tree is useful data structure
fro representing the relationship among data element in many applications.

(5) Level

Level of a
then it has
Node K, J,

(6) .H eigh

Height o1
level in tht

The tree can be shown as below :

(7} Subtr
Level

Subtree i
original tr.
Example

Level

Level

Level

Fig. 1. General Tree


Definition :
(1} Trees:
. We formally define a tree as a non-linear data structure, with finite set of nodes in
which there is one specially designated node called Root node and the remaining
nodes are partitioned into disjoint sets T1 , T2 , .... , Tn, n >= 0, where each Ti is a tree.
Compiled by Prof. Rajesh 'Bothra

Downloaded from Faa

Pg. 48

oDEngineers.co

Compiled

Mayuranand Classes
B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. B 3251 4726, 6525 7069
B-216/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

(2) Degree of Nodes :

It is an integer value and can be defined as number of subtrees of a node or can be


defined as number of child nodes which immediately follow a node. The degree of
node A is 4, Cis 2, B is 1.
Degree of K, J, I, E ... is zero.
(3) Leaf

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.

(5) Level of a Node :


Level of a no~e is defined by letting the root at level 1. If a node is at level k,
then it has its children at level k + 1. Node is at level 1, node B, C ... at level 2.
Node K, J, I, .... are at level 4.

(6) Height I Depth of a Tree :


Height of a tree is the maximum level of any node in the tree. The maximum
level in the example (,Fig.l) is 4, thus height I depth of the tree is 4.
(7) Subtree :
Subtree is defined as a tree with same nodes and edges (branches) that belong to
original tree.
Example:

.. ;

of nodes in
e remaining
1 T1 is a tree.
Pg. 48

Downloaded from Faa

oDEngineers.com

49
Pg.

Mayuranand Classes
W 3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector.17, Vashi, Navi Mumbai. W 6517 3281

B-403/40i
B-216/217 Vardr

(8) Binary Tree :

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'av-et-degree 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

1.- Left sub- -~+ Riqht sub -1


Fig.2 Binary Tree

Left Child Right Child


Node
Node

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.

Memory Representation of Node of Binary Tree :


(10) Fu
Address field
(To store
addresses
of left child)

Address field
(To store
addres$eS
of right child)

+-r-I

I
I
I

Definiti
It is also
Note: I
(11) St

Data/Information field

Structure Declaration of Node :


typedef struct node_tag

. A n"'ary

int data;

n child1
Strictly
leaf pat

struct node_tag *left, *right;

Tree is
Binary 1
Tree if
Let us c
at least
longer t

node;

The fig1

,._ _

____ ! I. _ ..J

L .

"' - - -~

""'- . ! - - L

Compile

~ - J... L .- -

Downloaded from Faa

oDEngineers.CD

Mayuranand Classes
;, 6525 7069
18i.. 6517'3281

B-403/407, Konark Darshqn, Above UTI Bank, Zaver Road, Mulund (W). Mumbai 80 .. V 3251 4726, 6525 7069
B-216/217 Var~hman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. V 6517 3281

Jite often in

Another kind .. of Binary-tree :


Nodes to one of the sides (skewed trees)

~he._?. That is

rt most two.
~s, however,
:ree. can be

(Tree having nodes to


left only -left skewed
tree)

(Tree having nodes to


right only - right skewed
tree

(9l A Complete Binary Tree


A complete binary tree is defined as a binary tree where all of its leaves on level n
and every parent node has two child node (Fig. 3).

~ight

Child
Node

No disjoints

Fig. 3 : Complete Binary Tree


(10) Full Tree with reference to Binary Tree :
Definition: A binary tree in which each node has exactly zero or two children.
It is also known as proper binary tree.
Note : In other words, every node is either a leaf or has two children.
)
(11) Strictly Binary Tree :
Tree is an imp9rtant data structure in Computer science. Of all trees we work with,
Binary Tree is probably the most popular one. A Binary Tree is called Strictly Binary
Tree if _every non-leaf node in a binary tree has nonempty left and right subtrees.
Let us define a strictly Binary Tree of depth d, as a Strictly Binary Tree that has
at least one root to leaf path of length d, and no root to le_af path in that tree is
longer than d. So let us use a similar reasoning to define a generalized structure.

A n"'ary Tree is called strictly n-ary Tree if every non-leaf node in a n-ary tree has
n children each. A strictly n-ary 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

Downloaded tram Faa

oDEngineers.co

Mayuranand Classes
B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. 1ii 32514726,6525 7069
B-216/217 Vardhman yhambers, Above UTI Bank, NrBabubhai Jagjeevandas, Sector 17, Vashi, Navi Mum,bai. .'if 6517 3281

B-403/4(
8-216/217 Varc

{12). Binary Search Tree :

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.

All subtrees must be binary search trees.


Binary Search tree can be shown as below :
~ (.

tptr
}
Function
node *get
{

ret1
}

Function
void freer
{

fre
}

Q. 2. Wr
Ans.: Fu
int searc
{

I*
nc

LIST OF OPERATORS ON BINARY SEARCH TREE

if

Search

i)

u) Tree Traversal
iii) Insertion

h~)

Creation

el

v}. Deletion

Binary-Tree-ADT
typedef struct node_tag

{
int data;
struct node_tag * left, * right;
}

node;

Declaration of tree pointer (header pointer)


typedef struct root_tag

{
node* root;

tree;

}
Cc - -

Downloaded from FaaDoDEngineers.col


J

"'J
I

Com pi lee

Mayuranand Classes
7069
6517 3281

8-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. tJ 3251 4726, 6525 7069.
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector .17, Vashi, Navi Mumbai. 'R 65173281

Function to Initialize root pointer :


:Ifill the

void init_tree(tree * tptr)

{
'value)

1e (key

tptr

root .= NULL;

e.
Function to Create a Node
node *getnode()
{

return (node*) malloc(sizeof (node));

Function to Destroy a Node


void free node (node *p)
{

free(p);
}

Q. 2. Write a routine to searcti a node from a given binary tree.


Ans.: Function to Search for a Node (Iterative Function) :
int search (tree *tptr, int x)
{

/* x

A data value of a node to be searched

--7

*I

node *find;
if (tptr
{

root = = NULL)

printf ("Error ! tree is empty\n")


return <j>;

}
else
{

find = tptr --+ root;


while (find ! = NULL)
{

if (x = find

--7

data)

return 1;

/*successful search/*

else
if (x < find

data)

find = find ~ left;


else
find == find
}

}
Pg . 52

right;

/* end of while */

return <j>;
/* unsuccessful search,* /
}
/* end of function*/.

Downloaded from Faa

oDEngineers.co

-~53

.,.,_

Mayurana,nd Classes

~03f"407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W}. Mumbai- 80. if 32514726,6525 7069
B-216/217 Yjirdhma~ Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas~ Sector 17, Vashi, Navi Mumbai. tl 6517 3281

B-403/40"
B-216/217 Vardt

Recursive Functio-n :

Function f

int search (node *find, int x)

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)

return search (find

-~

Function

left, x);

void postc

else
return search

(find~

right, x);

if (

{
/

. . ~TREE TRAVERSAL

"

Q. 3. Write a routine to traverse a non-empty binary tree in (i) Inorder,


(ii) Preorder and (iii) Postorder.
Ans.: As we know that traversing means
visiting each node .of a ~trg ._.Qnc~: The
Rurpose o~ v1sitinf may be anything like to
print the ata va ue of a node or to count
number of. noaes etc. TraverSlng to1Je
carried out when we have to certain
operation on each node. Traversing can
carried to different ways. Following is the
minimal structure of a binary tree.

}
}

Q.4.DE
Ans.:
L.

~hild (L)

Left,Ch-ild..{_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

...

Preorder (vertex is at the beginning)/

LVR

Inorder (vertex is in between)


Postorder (vertex is at the end)

: s . .

Function for Inorder Traversal of a Binary Tree :


void inorder (node *tra)

{
if (tra ! = NULL)
{

inorder(tra

left);

printf (" /od \n.", tra ~ data);


0

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---"'

D-1-L...--

Downloaded tram FaaDoDEngineers.co

Com pi I

)25 7069
6517 3281

Mayuranand Classes
B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. It 3251 4726, 6525 7069
8-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. tr 6517 3281

Function for Preorder Traversa I :

void preorder( node *tra)


{

if (tra ! = NULL)
{

printf (" 0/od \n", tra

data);

*I

/* go to left node * l

preorder(tra --+ left);


preorder(tra

/*visit a node

/*go to right node * l

right);

}
}
Function for Postorder Tree Traversal :

void postorder(node *tra)


{
if (tra ! = NULL)
{

postorder(tra
. postorder(tra
Inorder,

l* go to left node *I

left);

~right);

printf (" 0/od \n", tra

data);

/* goto right. node *l


/* visit a node */

}
je)

Q. 4. Design an algorithm to insert a Node into a given Binary Tree.


Ans.: .
find= 0.1

0.2

97<YOO
select left .

lild (L)

X=

find

s per the

= 0.4

. the valid

\
\

e
\

. New Node
Tree after Insertion

Existing Binary Tree

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

reate a new node.

Step 2

Fill a nod by a data value and initialize left and right link by NULL.

Step 3

Search address of a parent node to which new node to be attached.

Step 4

Attach a node.

Steo 5

Finished.

oiEngineers.col.

Downloaded from Faa

Pg. 55

Mayuranand Classes
B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulu~d (W), Mumbai- 80. R 3251 4726, 6525 7069
B-216/217 Vardhrhan Chambers, Above UTI Bank, Nr Babubhai Jagjeevatldas, Sector 17, Vashi, Navi Mumbai. if 6517 3281

void insert(tree

*~ptr,

B-403/4(
B-216/217 Varc

Q. ~Writ

int x)

Ans.: Alg

node *newnode, *find, *follow;

Step 1

. newnode = getnode()

Step 2

newnode

data = x;

newnode

left = newnode

right = NULL;

if (tptr ~ root == NULL)

=newnode;

tptr ~ root
else
{

find = tptr

root;

while (find ! = NULL)


{

follow = find;
if (x

<find~

data)

find = find

left;

find = find

right;

else
}
if (x < follow

data)

follow ~ left = newnode;


else
follow~

I*

I*

end of else

end of function

right= newnode;
Cases tc

*I

*I

Q. 5. Write a function to ,create a binary search tree.

1.

Er

2.

Lc

root

Ans.:

void create_tree (tree *tptr)

{
int x.;
char cb;

(Root as
leaf nod,

printf ("what to build a tree (yin) \n");


scanf {" 0/oc", &ch);
while ( ch = = 'y')
{
printf ("enter data value \n");
scanf ('' 0/od", &x);
insert(tptr, x);
printf ("want to continue (yin) \n");
fflush (stdin);
scanf (" 0/oc", &ch);

}
}
Compiled by Prof. Rajesh Bothra

..

Downloaded from Faa,,

Pa. 56

DEnginears.c m

Compilet

Mayuranand Classes
16525 7069
3i. tl 6517 3281

B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. tl 3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. B 6517 3281

Q. 6. Write a function to del_ete a node from a Binary Tree.


Ans.: Algorithm :
Step 1

Search for a node to be deleted.

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

Downloaded from Faa

DEngineers.c

Pg. 57

Mayuranand Classes
8403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80._if 3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. ir 6517 3281

3.

Left Skewed

(~()de

void del_n

having left child but no right child)


Root

Root

Root

CJ

CB

B-403/4{
B-216/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

.
.

. . ,.'
.

(Non-root node, left child


of its parent)

(~ode

(Non~root,

right child
of its parent node)

having right child. but no left child)


Root

Root

CID

GD
I
I

0
Root Node

Non-root, right child


of its oa rent
Non-root, left child of its parent

5.

Normal Tree (Node having left and right child)


Root

Root

Root

GD

Root node

(Non-root, left
child of its parent)

(Non-root, right
child of its parent)

Downloaded tram FaaDoDEngineers.col

Compile

Mayuranand Classes
6525 7069
i. w 6517 3281

8-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. tl 3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281

void del_node(tree *tptr, int x)

It

node *find, *follow;

== NULL)

if (tptr ~ root

printf ("tree is empty \n");


else

{
/*tree exists
find = tptr

*I

~root;

while (find ! = . NULL) && (x ! = find

data)

{
follow = find;
if (x < find
find
ght child
t node)

data)

= find

left;

else
. find = find _,_, right;
}

/* end of whi.le (search loop)

*I

== NULL)

if (find

printf ("node not found \n");


else
if (find
{

== tptr ~

root)

/*Root node to be deleted */


if ((find __,left
tptr

==

root

NULL) && (find__, right

=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 ~

root = find __, right;

hold = find __, root;


while (hold __, left ! = NULL)
hold = hold __, left;
hold __, left = find

left;

}
}

/*end if

*I

else

t, right
parent) _

/* non-root to be deleted

if(( find ~. left = = NULL) && (find ~ right = = NULL))


if (follow

Pg. 58

*I

left

= find)

oiEngineers.col

Downloaded from Faa

Pg. 59

Mayuranand Classes
8403 /407, Konark Oarshan, Above uTI Bank, Zaver Road, Mulund (W), Mumbai 80. if 3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, ~r Babubhai Jagjeevandas, Sector 17, Vas.~i, Navi Mumbai. tl 6517 3281

follow

left = NULL;

B-403/40
B-216/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~

right = find ~ right;

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~

~nd else .*I

end det_node

Ans.:

*I

Q. 7. Write a program to count number of nodes in a binary tree.

I nor

Ans.: Function to count number of nodes :


void nodecount (node *tra)

Pre<J

I*

static int cnt;

set to zero automatically

*I

if (tra ! = NULL}

Delete'[
find its p

{
cnt++;
nodecount (tra

left);

nodecount (tra ~ right);

}
}

D~ioaded tram FaaDoDEngineers.co

Compiled

7069

3517 3281

Mayuranand Classes
B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. ir 32514726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. tl 6517 3281

Q. 8. Write a program to count number of leaf nodes in a binary tree.


Ans.: Function to count number of Leaf nodes :
void.leafnodecount (node *tra)

{
.static int cnt = <j>;
if (tra ! = NULL)

{
if ( (tra -+ left

== NULL)

&& (tra -+ right

== NULL)

cnt++;
leafnodecount (tra -+ left);
leafnodetount (tra -+ right);

}
}

Q. 9. Given !NORDER of certain binary tree, construct all possible trees.


!NORDER : ABC
Ans.:

Q. 10. Given !NORDER and PREORDER of certain tree, construct a tree .:


!NORDER

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

Downloaded from Faa ,oOEngineers.co

Mayuranand Classes
B-403/407, Konark Oarshan, Above UTI-Bank, Zaver Road, Mulund (W), Mumbai - 80...if 3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTLBank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. it 6517 3281

B-403/40.
B-216/217 Vardt

Preorder

void preorc
{

nodE

int t

tra

whil
{

4
3
2

1-3

L- D

S-8

R-D

s
Q. 11. Give the non-recursive routines for inorder and preorder tree
traversal.
Ans.: Non Recursive Algorithm For Tree

Traversal~

Inorder Traversal
void inorder(tree *tptr)
{
}

node *tra, *stack[10];


tra

!*

= -1;

int top

= tptr ~ root;

Q. 12. G
construe

while (tra != NULL)


{

Ans.:

while. {tra ! = NULL)

inti;

node *cr
stack [++top] = tra;
tra = tra

nc

left;

ini

tra ~ stack[ top--];

if

printf (" 0/od \n", tra


tra = tra

while (tra

~data);

right;

==

NULL) && (top> -1)

{
tra = stack [top--];
printf (" 0/od \n", tra ~data);
tra = tra

right;

}
}
}

/*end of outer while *I

/*end of inorder*I

oownloaded tram FaaDoDEngineers.co

Compiled

Mayuranand Classes
25 7069
i' 6517 3281

B-403/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

Preorder Traversal :
void preorder(tree *tptr)
{

node

~tra,

*s[ 10];

int top = -1;


tra = tptr

--7

root;

while (tra ! = NULL)


{
while (tra ! = NULL)
{
printf (" 0/od \n", tra

--7

data);

s[ ++top] = tra;
tra = tra

--7

Ieft;

}
tra = s[top--];

ter tree

tra = tra

--7

right;

while ((tra == NULL) && (top > -1))


{
tra = s[top-- ];
tra = tra

--7

right;

}
}
}

/* end of outer while */

/* 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];

pos = search(pre[i], inorder, I, r);.

/* inorder and pre and arrays

*I

i++;
nptr

--7

left= create(!, pos-1);

nptr

--7

right= create(pos+1, r);

return n ptr;

}
else
{
return NULL;
}
/* end create *I

}
..

Pg. 62

Downloaded tram FaaDoDEngineers.co

'g. 63

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. fir 6517 3281

B-403/4(
B-216/217 Vard

THREADED BINARY TREE

Q. 13. Write note on threaded binary tree.


Ans.: Traversing a binary tree is a common operation and threading provides a
more efficient methoq for implementing the traversaL' Let us consider a case of
inorder traversal. We start traversing from left most lower node and whenever
subgtree is traversed, we go back to its parent, traverse it until we get back to root
and start with right subtree. In this whole process, the location (address) of the
parent of the current subtree is to be stored.

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 (n-1) finks
because address of root node is stored in a dedicated pointer (i.e. root points).
..

Total NULL links

= (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,

A Right Threaded Binary Tree :


If one utilized the right NULL links only for storing the address of successor node to
access the parent directory is called rightthreaded b'inary tree. It means we don't
have to use extra memory location to store address of parent node. Such a pointer
link is called thread. Consider a-following diagram :
n = 14 nodes

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

Cf\rnri.ilal'f """ D.-nf D.:a;a~h Rn~h.-:a

Downloaded from Faa,,

DEnginears.c m

Compiled

Mayuranand Classes
525 7069
a ss11 3281

B-403/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. ir 6517 3281

,rovides a
a case of
whenever
ck to root
55) of the

e address
~sses

field
'n' nodes

n-1) links

nts).
~decessor

node and

r node to
we don't
a pointer

Right threaded Binary Tree

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

Right thread (rtthread)

Left link
Data field
if (rtthread

== <!>)

Right link
No right thread link

if(rtthead == 1)

Right thread link

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

Downloaded tram FaaDoDEngineers.comPg.

65

Mayuranand Classes
B-403/407, KonarkDarshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai - 80. if 32~1 .472&; 6525 7069
. :. B-216/217 Vardhman Chambers, Above UTI Ban~. Nr Babubhai Jagjeevandas, Sector 17, Vashi, Ncivi Mumbai. W 6517 3281

A simple (FULLY) threaded binary tree :


It can be defined as a binary tree in which both left NULL link as well as right NULL

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.

8-403/40
8-216/217 Vardl

To implem
and right c
can observ
T[O]'s chile
T( 1] 's chile

T[2]'s chile

For any r

LINKED REPRESENTATION OF BINARY TREE

Q. 14. What are the different ways of representing Binary

Trees ;~?

Ans.: (1) Linked Representation and (2) Array Representation.


(1) Linked Representation of Binary Tree :

T[2*1NDE~

We

canal~
inde~

If

If inde:

Importar

This sho'lll
from pare

APPLl

(1) Expre

(2) Game

+
Binary Tree

Linked Representation

(2) Array Representation of Binary Tree :


In a linked representation, the pointers from parent to children are explicit in data
structure. A field is declared in each node for the pointer to the left child and a
pointer to the right child.

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

o~~~~d~ tram FaaDoDEngineers.col

Compilec

Mayuranand Classes
>525 7069
. ir 6517 3281

B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. il 3251 4726, 6525 7069
B-216/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

T[O]'s children are T[l] and T[2]


T[l]'s children are T[3] and T[4]
T[2]'s children are T[S] and T[6]

... and so on.

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 index is odd, then the parent of T[INDEX] is T[INDEX/2]

If

inde~

is even, then the parent of T[INDEX] is T[INDEX/2- 1].

Important:
This shows that the array implementation of binary tree is linked in both directions
. from parent to child and from child to parent.

APPLICATIONS OF BINARY TREE

( 1) Expression Tree
(2) Game Tree

icit in data
:hild and a

EXPRESSION TREE (HETEROGENEOUS BINARY TREE)

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 non-left nodes contain
character representing operators. Look at the following figure

3rent child

:y, level by
in the tree

1d the last

Expression tree representing


3 + 4 * (6 - 7) I s + 3

Pg. 66

oDEngineers.col

Downloaded from Faa ,

Pg. 67

Mayuranand Classes
8-403/407, Konark Darshan, Above UTI Bank, 'laver Road, Mulund (W), Mumbai - 80 .. B 3251.4726, 6525 7069
8-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. V 6517 3281

B-403/ ~
B-216/217 Va1

An expression is made up of operand and operators. The expressions which we


write are in INFIX form. This is the conventional way. But these expressions are not
evaluated, keeping the expression in infix form, rather these expressions are
converted either in prefix or postfix form and then evaluated by the system.

Q. 15.

There are three different ways of representing expressions. They are :

float eval

Ans.: C-l

#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*c-d/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(c-d/e+f*(g - h/i) + j) + k

+k

a+ b * (c- [de/]+ f*(g-hi/]) + j)

a + b*(c- [de/]+ f*[ghi/-]

a + b*(c- [del] + [fghi/-*] + j) + 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

1 postfix form (conversion)

(ii) And then, converted expressions are evaluated.

}
rn"'nil"'rl

nv

Pr-nf

Q~;,.c:h Rnt-hr-~

o,., t:.o

Downloaded tram FaaDoDEngineers.co

Compil

Mayuranand Classes
i25 7069

ir 6517 3281

which we
ns are not
;sions are

n.

B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. it 3251 4726, 6525 7069
. B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi; Navi Mumbai. V 6517 3281

Q. 15. Write a program to evaluate a given POSTFIX expression.


Ans.: C-Implementation :

#include <stdio.h> .
float evaluate (char[ ] ) ;

/*function prototype*/

void main()

{
char p[20];
float ans;

:rse polish

printf ("enter any POSTFIX exp \n");


gets (p);
ans =evaluate (p);
printf ("answer= 0/of \n", ans);
in Postfix

}
float evaluate (char p[20l)
{

inti, top = -1; val;

1- d/e
I -[del]
[de/]

float opl, op2; s[20];

/*sis a stack*/

char x;
float r;
for ( i = 0; p [ i] ! = '\ 0'; i + + )

~/-

{
X

: prefix or

= p(i];

if(x =='+'II x =='-'II x =='*'II x == '/')


{

/* x is an operator*/
opl = s[top ---]; /* pop an element*/
op2

= s[top - -];

/* pop an element* I

switch (x)
{
case'+'

r = op2 + opl; break;

case'-'

case'*'

r = op2 * opl; break;

case'/'

=op2- opl; hreak;


= op2 /opl;

s[ ++top] = r;
}

else

ersion)

/*x is an operand* I
V::; X-

'<f>';

s[ ++;top]

= v;

}
Pg. 68

/* end of for loop* I

Downloaded from Faa

oDEngineers.co

Pg. 69

Mayuranand Classes
8-403/407_, Konark Darshan, Above UTI Bank, ZaverRoad, Mulund (W), Mumbai- 80. if 3251 4726, 6525 7069
B-216/217 Vardhman. Chambers, Above UTI Bank,
Nr Babubhai Jagjeevandas,
Sector 17, Vashi, Navi-Mumbai. R 6517
3281
.
.
.
.

B-403/ ~
B-216/217 Va'

~ -

r = s[top---];

for (i

return r;

/*end ofevaluate */

Q. 16. Develop a program to convert a POSTFIX expression to INFIX or


PREFIX form.
Ans.:
/* program to convert POSTFIX to INFIX Exp OR PREFIX Exp *I
#include <stdio.h>
#include < stdlib.h>
typedef.struct node_tag
{
char data;
struc node_tag *left, *right;
} node;
void inorder (node *tra)
{
.if (tra != NULL)

{
inorder (tra

-~

left);

printf (" /oc", tra-+ data);


inorder (tra

right);

}
}

I*

void preorder (node *tra)

pr

{
if (tra != NULL)

pr

pr
printf.('' 0/oc",

tra -+ data);

pr

preorder (tra -+ left);

pr

} r

preorder (tra -+ right);


}

Q. 17.
and ir

void main()

Ans.:

#inclu

char p[20] x;

inti, top

#inclu

= -1;

#inciL

node *newrec, *opl, *op2;

typed'

node *root;
node *stack[20];

/*stack of pointers * 1

printf ("enter any postfix Exp\n");


gets (p);
Compiled by Prof. Rajesh Bothra

Downloaded from Faa

Pg. 70

oDEngineers.co

Com pi

Mayuranand-Classes
525 7069
ir 6517 3281

.B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. it 3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. ir 6517 3281

for (i = 0; p[i] != '\0'; i++)

{
X=

p[i];

==

if (ch

INFIX or

'+' II ch

== '-' II

ch

==

'*' II ch

== '/')

op 1

= stack[top--];

op2 = stack[ top--];


newrec

= (node*)

newrec

data = x;

newrec

left

/*right operand*/
/*left operand*/

malloc(sizeof(node));

= OP2;

/*left operand*/

newrec ~ right = OPl; /*right operand* I


stack[ ++top]

= newrec;

else
{

newrec

= (node*)

malloc(sizeof(node));

newrec ___,. data = x;

= NULL;

newrec

left

newrec

right

stack[ ++top]

= NULL;

= newrec;

/*end of for loop* I

root = stack [top--];


/* call inorder traversal method to print infix expression

*I

printf ("Infix Expression is \n") ;_


inorder ( ro.o t);
printf ("\n");
printf ("prefix expression is \n");
preorder (root);
printf ("\n");
}

/*end of main*/

Q. 17. Write a program to convert a given prefix expression to-postfix exp


and infix expression.
Ans.:
#include <stdio.h>
#include <stdlib.h>
#include <strlng.h>
typedef struct node_tag

{
char data;
struC:t node:_tag *left, *right;
Pg. 70

Downloaded from Faa

oDEngineers.col

Pg.71

Mayuranand Classes
8-403/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, NrBabubhai Jagjeevandas, Sector 17, Vastli, Navi Mumbai. ir 6517 3281

B-403/
B-216/217 Vc

} node;
node *getnode( c)
{
return (node *) malice (sizeof(node));
}

void postorder (node *tra)

{
!:.

if(tra ! = NULL)
{
postorder (tra

left);

postorder (tra

right);

printf ('' /oc", tra


0

~data);

roc

l*c

void inorder (node *tra)

pri

inc

if (tra ! = NULL)

pri

{
inorder (tra

printf ('' 0/oc", tra


inorder(tra

I*

left);
~

pri

data);

po

right);

pr

I*

}
void main()

Q.18.

Ans.:
char p[20J, x;

# inciL

int i, top = -1, len;

int

node *newrec, *opl, *op2, *root;

icp~

node *stack(2.Q];

S\

printf ("enter prefix expression\n");


gets(p);
len = s~rlen(p);
for(i =len -1; i >= <j>; i--)
{
X

= p[i];

if(x ==

'+' II

x == '-'

II

x == '*'

II

x == '/')

intis~

opl = stack[top--]; /*left operand*/


op2 = stack[top-'-];

l*

right b'perand*/

newrec = getnode();
newrec

data = x;

newrec

left = op 1;

Comoiled bv Prof. Raiesh Bothra

Dn

7?

Downloaded tram FaaDoDEngineers.co

Com pi

7069
6517 3281

Mayuranand Classes
B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai -80. tr 3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. tr 6517 3281

newrec

right= op2;

stack[ ++top] = newrec;


}

else

{
newrec = getnode();
. newrec ~ data=x;
newrec

left = NULL;

newrec

right = NULL;

stack[+ +top] = newrec;


}
}

/*end of for

*I

root = stack[top] ;
/*call Inorder traversal*/
printf ("Infix Expression is \n");
inorder (root);
printf ("\n");
/* call Postorder traversal

"

*I

printf ("Postfix expression is \n");


postorder (root);
printf ("\n");

/*end of main

*I

Q. 18. Write Ci program to convert Infix Exp to Postfix Exp.


Ans.:
# include < stdio.h>

int icp( char x)


{

switch (x)
{
case 'c'

return 4;

case'*'
case'/'

return 3;

case'+'
case'-'

return 2;

int isp( ch.ar x)


{

switch (x)
{
case'$'
case 'c'

return <j>;
return 1;

case'*'
Pg. 72

Downloaded from Faa

oDEngineers.co

Pg . 73

Mayuranand Classes .

B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. - ir a2514726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai' Jagjeevandas, Sector 17, Va$~i;. Nav~ Mumbai. tt 6517 3281

B-403/
B-216/217 V:

return 3;

case'/'
case'+'
case'-'

return 2;

}
void main()
{
char infix[20], p[20], stack[lS], x;

inti, j = 0, top. = -1;

whi

printf ("enter an infix expression \n");

gets (infix);

top++;
stack[top]

= 0;

for (i

= '$';
}

infix[i] != '\0', 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 "'"

o ..,.f o ,.;.,..,.h o,... .. h ...,.

Downloaded from Faa

DEngineers.c

Compile

Mayuranand .Classes
~5

7069 .
65173281

B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. II 3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr.Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. W 6517 3281

top--;

}
else

{
p[j]=ch;

j++;
}

I* end of for loop *I

while (stack[top] ! = '$')


{

= stack

p[j]

[top];

j++;
top--;

p[j] = '\0';
printf ("postfix expression is 0/os \n", p);

HETEROGENEOUS BINARY TREE : EVALBINTREE FUNCTION

This is to evaluate an expression tree (heterogenous binary tree).


The function accepts a pointer to such a tree and returns the value of the
expression represented binary tree. The function. recursively evaluate the left and
right subtree and applies the operators of the root to the two results. The function
'oper' returns the result of applying the operator to the operands.

# include <stdio .h>


# define OPERATOR 0

# 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

Downloaded tram Faa .oDEngineers.com

75
Pg.

Mayuranand Classes

B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai ~ 80. __if 3251 4726,6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. tr 6517 3281

B-403
B-216/217 I

case'+'

ans = opl + op2 ; break;

Q. 20.\

case'-'

ans = opl + op2; break;

Ans.: R

case'*' -

ans = opl _* op2; break;

# includ

case'/'

ans = op1 I op2; break;

# includ

# indue

return ;ans;

# indue

# incluc

float evalbintree(node *tree)

# definE

float op
{

float opnd1 1 opnd2;

flo.

char sym;
if (tree

sw

utype = = OPERAND)

return

tree~

opndl = evalbintree (tree

left);

opnd2 = evalbintree (tree

right);

sym = tree

numinfo;

chinfo;

return (oper (sym, opndl; opnd2));


}

}
}

void su

RECURSION

Q. 19. Write a recursive program to convert PREFIX to POSTFIX form.

Ans.: Recursive Prefix to Postfix Conversion :

int

void convert (char prefix[ ], char postfix[ ])

fo

Stl

char first[2];
}

char tl[lO], t2[10J;


first[ OJ
first[!]

float e\

= prefix[O];
= '\0';

{
fie

substr(pretix, 1,-strlen(prefix) -l, prefix);


if (first[ OJ = =

'+' II first[O] = = '-' II first[O]

= = '*'

II

cr

first[ OJ==)

if

convert (prefix, tl);


convert (prefix, t2);
strcat(tl, t2);
strcat(tl, first);

substr{tl,O,strlen(tl) ,postfix);
}

OJ

postfix[O] = first[O];

Sl

postfix[l] = '\0';

v:

v:

re
}

o~~~oaded tram FaaDoDEngineers.col

Compile

Mayuranand Classes
5 7069 .
r 6517 3281

B-403/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. ir 65173281

Q. 20. Write a recursive program tc; evaluate PREFIX expression.


Ans.: Recursive Prefix Evaluation:
# include <stdio.h>
# include <stdlib.h >
# include <conio.h>
# include <string.h>

# include <ctypc.h>
# define MAX 50

float oper(char op, float vl, float v2)


{

float ans;
switch (op)

= vl

case'+'

ans

+ v2; break;

case'-'

ans = vl - v2; break;

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 + + )

str[i] = str[pos+ i];


str[i] = '\0';
}

float eval (char prefix[ ])

{
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

Downloaded tram FaaDoDEngineers.com

77
Pg.

----------

Mayuranand Classes
B-403/407, Koliark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. tl32514726, 6525.7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas,. Sector 17, Vashi, Navi Mumbai. il 6517 3281

B-403/
B-216/217 Va

N-QUEENS PROBLEM

Q. 21. Explain n-Queens problem.

1 to 2

Ans.: Recursive program for solving n-Queens problem :

void nqueen (int k, int.n)

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 + +)

printf (" 0/o3d", x[j]);


printf ("\n");
}

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.

void tower (int

x,

int y, int z, int n)

if (n > 1)
{
tower (x, z, y, n- 1);
printf ("Disk moves from 0/od to 0/od \n", x, y);

. tower (z, y, x, n- 1);

n= 3

Comoiled bv Prof. Rajesh Bothra

Pg. 78

Com pi

oDEngineers.col----

Downloaded from Faa

Mayuranand Classes
;7069
6517 3281

B-403/407, Konark Darshan, Above UTI Bank, laver Road, Mulund (W), Mumbai - 80. V 3251 4726, 6525 7069
B-216/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

Downloaded from Faa,,

~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.

Downloaded from Faa

oDEngineers.co

. - ~-

..

-- -

- - --- - -~7---~;

'''
'/f,~l~''

WIII~~~;'Wimllml~i~AND

C: L A S S E S

MAYURANANDCLASSES
B-403 I 407, Konark Darshan,
Above UTI Bank, Zaver Road,
Mulund (W), Mumbai- 80.
C<?ntact Nos. : 3251 4726, 6525 7069

B-216/217 Vardhman Chambers,


Above UTI Bank, Near Babubhai Jagjeevandas, .:[..
Sector17, Vashi, Navi Mumbai.
Contact No. 6517 3281

Prof. Rajesh Bothra's


Private Tuitions
SEMESTE.R- V

(MECHANICAL ENGINEERING)
-Set 2(

ANALYSIS OF ALGORITHM

ALSD TEACHES

! CP-I (Sem. I)
! CP-II (Sem. II)
! DATA STRUCTURES (Sem III. : CMPN)
! NT (Sem. III)

! ANALYSIS OF ALGORITHMS (Sem IV: CMPN)

! _. DATA STRUCTURES AND ALGORITHMS (Sem IV : IT)


! OOAD (Sem. VI : CMPN/IT)
BRANCHES

Dadar + Andheri
+ Vashi + CBD

+ Mulund + Thane.
+ Panvel + Airoli

- : 2760 1081, 98.9 20 21666, 99673 :19991 .

wnloaded from Faa .oDEngineers.com:oNONLY

Downloaded from Faa

oDEngineers.co

Mayuranand Classes
B-403/407, Konark Darshan, Above UTI Bank~ laver Road, Mulund (W), Mumbai 80. if 3251 4726,6525 7069
B-216/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

(2) Linked Lists :


D Dynamic Memory and Pointers .
D Dynamic Representation, Insertion and Deletion of Nodes, Linked Stacks
and Queues

D Linked Lists as Data Structure


D Comparison of Dynamic and Array Representations
(3) Sparse Matrix :
0 Sparse Matrix Representations
D Sparse Matrix stored in Doubly Linked List
D Addition, Multiplication, Transpose of Sparse Matrices keeping them in
Doubly Linked List
( 4) Binary Tree :
D Binary Tree Operations and Applications
D Binary Tree Representations
D Array Representations
0 Evaluation of Expressions
D Applications of Trees
0 Expression Trees, Conversion of Inorder Expression to Post
Expression

l Pre-order

(5) Sorting Methods :


0 Efficiency Considerations in Sorting
D Bubble Sort
D Different Sorting Methods
D Quick Sort
0 Straight Selection Sort '
CJ Binary Tree Sort
CJ Heaps and Heap Sort
0 Insertion Sort
D Merge Sort
D Time Complexity Calculation
0 Best Case, Worst Case and Average Case Calculations of the different
sorting methods
(6) Searching Methods :
0 Efficiency Considerations in Searching
D Sequential Search
Cl Basic Searching Techniques
D Indexed Sequential Search
D Searching Ordered Table
D Interpolation Search
D Binary Search
D Implementation
D Binary Search Tree
D Insertion and Deletion
(7) Graphs :
0 .Graph Traversal
0 Minimum Spanning Tree
D Shortest Path Problem
D Connectivity in a Graph

Download~-th;~ Fil~rilingineers.coi-Pg.

Mayuranand Classes
B-403/407, Konark Darshan. Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. if 3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281

B-403/
B-216/217 Va

(8) Algorithms :
(J Analysis of all the above Algorithms
0 ~reedy Method
0 Divide and Conquer Method
0 Dynamic Programming
0 Back-tracking 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

CJ NP Hard Scheduling Problems


0 NP Hard Code Generation 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)

Implementation of Stack and its operations.


Implementation of Queue and its operations.
Implementation of Circular Queue and its operations,
Array and Dynamic Implementation of Linked List and its operations.
Binary tree Implementation, Creation ofBinary Tree, Insertion and Deletion of
Nodes in qn existing tree.
(6) Various Sorting Methods.
(7) Various Searching Techniques.
(8) Implementation of Graph along with applications.

Algorithms are to be included for all programs

3.
4.

s.
6.

YEARWISE & TOPICWISE MARKS DISTRIBUTION

~
R

CH. 1. CH. 2. CH. 3. CH.4.


List Linked Spa~se Binary
List
Matrix Tree

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

Compiled by Prof. Rajesh Bothra

CH. 5.
CH. 7.
CH. 6.
CH. 8.
Sorting Searching Graph Algorithms TOTAL
Methods Methods

o~

::

Compiled

Downloaded from Faa aDEngineers.c 1 ----

Mayuranand Classes
'26, 6525 7069
mbai.
6517 3281

8-4031407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. if 32514726, 6525 7069
. B-216/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

1-8

2.

Sorting Methods

9-29

3.

Searching Methods

30-34

4.

Graphs

35-42

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.Coi-Pg.

Downloaded from Faa .

iii

B-40~

B-216/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

-Downloaded tram FaaDoDEngineers.co

Mayuranand Classes
B-403/407, Konark Darshan, Above UTI Bank; Zaver Road, Mulund {W), Mumbai- 80. V 3251 4726, 6525 7069
B-216/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

Q. 1. What is the need of analysing an Algorithm?

OR

Write short notes on complexity of an Algorithm.


Ans.: To analyze an algorithm is to determine the amount of resources (such as
time and storage) necessary to execute it. Most algorithms are designed to work
with inputs of arbitrary length. Usually the efficiency or complexity of an
algorithm is stated as a function relating the input length to the number of steps
(time complexity) or storage locations (space or memory complexity) required
to execute .the algorithm.
Algorithm analysis is an important part of a broader computational complexity
theory, which provides theoretical estimates for the resources needed by any
algorithm which solves a given computational problem. These estimates provide an
insight into reasonable directions of search of efficient algorithms.
In theoretical analysis of algorithms it is common to estimate their complexity in
asymptotic sense, i.e., to estimate the complexity function for reasonably large
length of input.

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 2-digit integers and two
1000-digit integers using a pen and paper).

Downloaded from Faa oDEngineers.co

Pg. 1

Mayuranand Classes
B-403/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.

+ BEST, WORST, AND AVERAGE-CASE


.

the wor
... + N-

Q. 2. Explain Worst, Best and Average case complexity.


Ans.: The worst case complexity of the algorithm is the function defined by the
maximum number of steps taken on any instance of size n.

No. of
steps

Worst Case
/ . Complexity

-----

~---

Average Case
Complexity

a
a
a

Note tl
becaus

Best Case
Complexity

+
0

The ar

The average-case complexity of the algorithm is the function defined by an


average number of stepstaken on any instance of size n.
Each of these complexities defines a numericaJ function - time vs. size.

HOW TO DETERMINE COMPLEXITY

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,

if-thE

5.
6.

7.
9.

10.

Here.
Then

Solution:

Question 1. :The problem size is the number of people in the room.


Question 2 : Assume there are N people in the room. In algorithm 1 you always
ask 1 question. In algorithm 2, the worst case is if no one has your birthday. Here
you have to ask e.very person to figure this out. This is N questions. In algorithm 3,

---Downloaded from Faa

Sequc

8.

Compiled by.Prof. Rajesh Bothra

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

/ ./ /
//

B-40:
B-216/217

Pq. 2

DEngineers.c

max(

Fore
the v

Comp

l525 7069
. 2 6517 3281

Mayuranand Classes
8-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. 2' 3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. it 6517 3281

the worst case is the same as algorithm 2. The number of questions is 1 + 2 + 3 +


... + N-1 + N. We showed before that this sum is N(N+1)/2.
ned by the

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 big-0 notation.
For a problem of size.N :

. a constant-time method is "order 1 .. : 0(1)

a linear-time method is "order N.. : O(N)

a quadratic-time method is "order N sqljared .. : O(N 2 )

Note that the big-0 expressions do not have constants or low-order terms. This is
because, when N gets large enough, constants and low-order terms do not matter.

+ HOW TO DETERMINE COMPLEXITIES


In general, how can you determine the running time of a piece of code ?
The answer is that it depends on what kinds of statements are used.
led by the
Fined by an

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

oom has the

s.
ey have the
jay and ask

= time(statement

1) + time(statement 2) + ... + time( statement k)

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-then .. else Statements :


questions of
>ur birthday,
1 to find out
it is no, you
ld out about
s asked (the
each of the
quadratic in

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 worst-case 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 worst-case time for
the whole if-then-else statement would be O(N).

Downloaded from

faa oDEngineers.col

Pg. 3

Mayuranand Classes
B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai ~ 80. V 3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281

B-4
B-216/21

for Loops:

16. fo

11. for ( i = 0; i < N; i + +)

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.

15. for (i = 0; i < N; i++)

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 ).

Q. 3. What is the worst-case complexity of the each of the following code


fragments?
(A) Two loops in a row :
1.

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

2.

3.

sequence of statements

5.

for (j = 0; j < M; j + +)

6.

{
}
~hange

if the second loop went to N instead of M ?

2.

Tl
0

3.

"'

e:
ir
e

On th
inconv
with a
so tim.

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

10. {
11.

for (j = 0; j < N ; j + +)

12.

13.

14.

w
w

In gen
metho
import
time-c
pro bat
contra
compL
not rei
before

(B) A nested loop followed by a non-nested loop:

yl

Some
the pn

sequence of statements

How would the complexity

9.

+BE~

4.

7.
8.

Tl
is

Note t
to con
distrib

sequence of statements

15. }
Compiled by Prof. Rajesh Bothra

__.Downloaded from Faa

on

aDEngineers.c

Compile

Mayuranand Classes
6, 6525 7069
:>ai. B 6517 3281

B-403/407, Konark Darshan, Above UTI Bank, laver Road, Mulund (W), Mumbai- 80. if 3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. B 6517 3281

16. for (k = 0; k < N; k++)

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 N-1 times. In the last iteration of the outer loop when i is N-1 the
inner loop executes 1 time. The number of times the inner loop statements
execute is N + N-1 + ... + 2 + 1. This sum is N(N+1)/2 and gives O(N 2 ).

s, the inner
~cute

a total
case where
., the inner

+ BEST~CASE AND AVERAGE-CASE COMPLEXITY


Some methods may require different amounts of time on different calls, even when
the problem size is the same for both calls. This is what happ~ns in the worst case .
. In general, we may want to consider the best and average time requirements of a
method as well as its worst-case time requirements. Which is considered the most
important will depend on several factors. For example, if a method is part of a
time-critical system like one that controls an airplane, the worst-case times are
probably the most important (if the plane is flying towards a mountain and the
controlling program can't make the next course correction until it has performed a
computation, then the best-case and average-case times for that computation are
not relevant - the computation needs to be guaranteed to be fast enough to finish
beforethe plane hits the mountain).
On the other hand, if occasionally waiting a long time for an answer is merely
inconvenient (as opposed to life-threatening), it may be better to use an algorithm
with a slow worst..:case time and a fast average-case time, rather than one with soso times in both the average and worst cases.
Note that calculating the average-case time for a method can be tricky. You need
to consider all possible values for the important factors, and whether they will be
distributed evenly .

Pg.

Downloaded from FaaDoDEngineers.coi-Pg.


5

Mayuranand Classes

B-4(

B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. ii 3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281

B-216/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)

Traversing a set of data.

O(n lg n)

Splitting a set of data in half repeatedly and traversing each half.

O(n 2 )

Traversing a set of data once for each member of another set of equal
size.

0(2")

Generating all possible subsets of a set of data.

O(n!)

Generating all possible permutations of a set of data

no
f(n)

Graph it
in the r
(a)

Table-1 : Some Situations wherein Common Complexities Occur

Complexity

16

n = 256

n = 4k .

64k

to
in

n =1M

l.OOOE+OO l.OOOE+OO l.OOOE+OO l.OOOE+OO l.OOOE+OO l.OOOE+OO

O{lg n)

O.OOOE+OO 4.000E+OO 8.000E+OO 1.200E+Ol 1.600E+Ol 2.000E+Ol

O(n)

l.OOOE+OO 1.600E+Ol 2.560.E+02 4.096E+03 6 .554E+04 1.049E+06

(b) 0 -

w.
th
(c)

O(n lg n) O.OOOE+OO 6.400E+Ol 2;048E+03 4.915E+04 1.049E+06 2.097E+07


O{n 2 )

l.OOOE+OO 2.560E+02 6.554E+04 1.678E+07 4.295E+09 1.100E+12

0{2)

2.000E+OO 6.554E+04 1.158E+ 77

O{n!)

l.OOOE+OO 2.092E+13

---

---

---

- --

---

---

Table - 2 : The Growth Rates of the Complexities in Table 1

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

Fig. 1 : A graphical depiction of the growth rates in Table l

Compiled by Prof. Rajesh Bothra

-Downloaded from Faa

includin

Po. 6

DEngineers.c

Compiled

Mayuranand Classes
6, 6525 7069
bat. if 6517 3281

B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. if 3251 4726, 6525 7069
B-216/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.

(a) 8-notation bounds a function to within constant factors.

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) 0-notation 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) n-notation 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 ),

for example, includes all functions that grow faster than n2

including n3 and 2n.

Pg. 6

Downloaded from Faa,,

DEnginears.c m

Pg.

Mayuranand Classes
B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. if 3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. ir 6517 328.1

B-403
B-216/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.

Because e{f)n(f)and O(f) are sets, it is proper to say that a .function g is an


element of these sets. The analysis literature, however, accepts that a function g is
equal to these sets as being equivalent to being a member of the set. So, when you
see g = O(f) ~- this really means that g EO{ f).

+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

.._Downloaded tram Faa

Pg. 8

oDEngineers.co

Compile

Mayuran~nd Classes
B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W). Mumbai- 80. if 3251 4726, 6525 7069
B-216/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

CHAPTER 2 : SORTING METHODS

+ 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

+ DIFFERENT SORTING METHODS


(1) CLASSICAL BUBBLE SORT :

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 n-2 comparisons
need to be made. After n-1 passes, the array gets sorted.

,n g is an
rnction g is
, when you

Algorithm:
1)

Establish the array a[O ... n - 1] of n elements.

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 non-descending
order, then exchange the element of the pair.

3)

Return the sorted array.

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

..

The sorted array after 1 pass _is :


147 .152

ls7

1""31

The sorted array after 2 passes is :


.147

ls2

131

117

121

The sorted array after 3 passes is :


147

Pg. 8

131

117

121

122

The sorted array after 4 passes is :


l31

l17

!21

I 22

!41

Downloaded tram FaaDoDEngineers.co

Pg.9

Mayuranand Classes
8-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. B 3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. ir 6517 3281

3)

The sorted array after 5 passes is :

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

B-403 /'
B-216/217 Va

Whil1
(a)

(b)

(b.1:

4)

The sorted array after 8 passes is :

RetL

Illustrat

117 121 122 131 137. 141 147 152 157 162

The origi1

. The sorted array after 9 passes is :

117 121 122 131 137 141 147 ls2 ls7 16iJ

The sortE

Performance of the Algorithm :


The bubble sort makes total n - 1 passes. During the first pass, it makes n - 1
comparisons. During second pass it makes n - 2 comparisons, and so on~
In general, for the ith pass of the sort, n - i comparisons are made . .The total
number of comparison is the sum.
n-1

The

sort~

The sort1

(n.- i)= -n(n -l)

i=l

The number of comparisons in .classical bubble sort remains same irrespective of


nature of data. However, if the data is already sorted, no swapping takes place,
whereas if the data is sorted in reverse order, swapping takes place for every
comparison. Average case obviously lies between the two. That makes the bubble
~ort O(n 2 ).

The sort1

(2) MODIFIED BUBBLE SORT :

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)

Establish the array a[O ... n - 1] of n elements.

2)

Set the order indicator sorted to false (i.e., sorted =zero]

Comoiled bv Prof. Raiesh Bothra

Pn 1 n

--------Downloaded tram FaaDoDEngineers.co

Compiled

Mayuranand Classes
5, 6525 7069
Jai.
6517 3281

8-403/'407, Konark Oarshan, Above UTI Bank. laver Road, Mulund (W); Mumbai- 80. if 3251 4726, 6525 7069
8-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. it 6517 3281

3)

While array is still not sorted (i.e., sorted = <!>)


(a)

set the order indicator sorted to true (i.e., 1)

(b)

for all adjacent pairs of elements in the unsorted part of the array do

(b.1) if current adjacent pair is not in non-descending order, then,


(1.a) exchange the elements of the pair.
(1.b) set sorted to false.
4)

Return the sorted array.

Illustration :

The orig.inal array :


147

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

The sorted array after l pass is :


147

ls2

ls7 . 131

117

1-

The sorted array after 2 passes is :

1akes n - 1
:md so on.
~. The total

147

ls2

131

117

121

The sorted array after 3 passes is :


147

131

117

121

122

52

The sorted array after 4 passes is :

~spective

of
:akes place,
e for every
the bubble

131

lt7

121

122

141

The sorted array after 5 passes is :


117

121

122

131

137

The sorted array after 6 passes is :


!Xplain its

117

~r the array
he moment

121

122

131

137

Performance of the Algorithm


Best Case : This involves only one pass, which requires n - 1 comparisons.
Consequently, the best case is O(n).

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(n-1)/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

(3) SELECTION SORT (Straight Selection Sort) :

Q. 4. Explain Selection sort.

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 .

~~~~ 7~e~:~:_i~.::~: ~r~~y~-~ ~~~;~~ ~~~ s~:~~-~~~!~e-=~-~lec~~t~~s-t~~~-:a!r~~:;~~t

Downloaded tram Faa

oDEng1neers.co

Pg. 11

Mayuranand Classes
B-403/407, Konark Darshan, Above UTI Bank, ZaverRoad, Mulund (W), Mumbai- 80. ill 3251 4726,6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17; Vashi, Navi Mumbai. if 6517 3281

B-403
B-216/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)

Establish the array a[O ... n - 1] of n elements ..

Perforr

Set variables min to x[O] and pos to 0.

In the 2
a pass.
places c

Compare min with remaining elements of the array x


if any x[i] is found to be less than min
then

3.1

change min to x[i]

3.2

ch'ange pos to i

During
com par
The tot

4)

Swap the values of x[O] with x[pos]

n-1

5)

Repeat steps 1 to 4 for different values of min ranging from

i = 1-

L (n-i

x[i + 1] to x[n-1]
6)

Irrespe
same.:
numbe1
mechar
earlier
selectic

Return the sorted array.

Illustration :
The original array :
147

ls7

ls2

162

131

117

121

122

141

137

(4} IN

The array after 1 pass is :


117

ls7

ls2

Q. 5. E

162

131

147

121

122

141

Ans.:
array i:

137

vis~a-v

The array after 2 passes is :


lt7

121

ls2

162

131

147

ls7

122

141

137

131

147

ls7

l. s2

141

137

such t
subsec
sub-ar

The array after 3 passes is :


117

121

122

162

Algori

The array after 4 passes is :


117

121

122

131

162

147

ls7

ls2

141

137

1)

E~

2)

F1
2

The array after 5 passes is :


1'17 ' 121

122

131

137

147

ls7

ls2 141

162

The array after 6 passes is :


117

121

122

131

3)

137

141, ls7

js2

147 Tss

I
Illust

The array after 7 passes is :


117

121

122

131

137

141

147

ls2

ls7

162

137

141

147

ls2

!s7

162

The

01

The array after 8 passes is :


117

121

122

131

Compiled by Prof. Rajesh Bothra

The a,

Pn . 1?

Compil

-Downloaded from Faa oDEngineers.com----

Mayuranand Classes
'6525 7069
:~;.a 6517 3281

Jed with the


:xt smallest
~d ordering)

B-403/407, Konark Oarshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. if 3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281

The array after 9 passes is :

117

121

122

131

137

141

147

js2

js7

r62

131

37

141

147 . ls2

ls7

162

The sorted array is :

117

\21

122

Performance of the Algorithm


In the algorithm, the search for the next smaJiest element in th~ array is known as
a pass. In selection sort process one needs to take n - 1 passes since each pass
places one element in its proper place.
During the first pass; in which the largest element is found, n - 1 elements are
compared. In general, for the ith pass of the sort, n - i comparisons are required.
The total number of comparison is the sum.
n-1

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
vis-a-vis 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
sub-array in such a way that the sub-array remains sorted.
Algorithm:
1)

Establish the array a[O ... n - 1] of n elements.

2)

From second elements to the last element tq the array do

3)

2.1

consider the size one less than the index of the element.

2.2

in the size find the appropriate position of the element under


consideration.

2.3

insert the element in its appropriate position.

Return the sorted array.

Illustration :
The original array :
1

47 . s7
1

s2

62

31

17

21 . 22
1

41

37

The array after 1 iterations is :

js7

Pg. 12

I
Downloaded from Faa

oDEngineers.col

Pg. 13

Mayuranand Classes
B-403/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 MumbaL if 6517 3281

The array after 2 iterations is :

147 152 157 162 131 111 121 122 141 137
The array after 3 iterations is :

147 152.157 162 131 117 121 122 [41 137


The array after 4 iterations
1

31 147

i~

B-4
B-216/21

3)

4)

5)

6)

7)

52 157 16~ 111 121

The array after 5 iterations is :

Illust

22 141 137

The ur

117 .131 147 152 1s1 162 (21 122 141 137

The s<

The array after 6 iterations is :

117 121 131 147 1s2 1s7 162 122

41

62 141

37

The

S<

The

S<

The array after 7 iterations is :


1

17 1-21 122 131

47 152 157

37

The array after 8 iterations is :

l11 l21 122 l31 141 147 ls2 ls7 162 137 J

The~

The _array after 9 iterations is :

111 121 122 131 137 141 147 1s2 157 162
Perfo

The sorted array is :

!11 121 122 131 13 7 141 147 1s2 1s7 162]


Performance of the Algorithm
The best case of insertion sort occurs when the initial array is already sorted, as
only one comparison is made in each pass and the efficiency of sort is O(n). The
worst case occurs when the array is initially sorted in the reverse order, since the
total number of comparisons are,

The a
the c1
insert
increr
eleme
insert
show~

(6) fJ

(n-l)+(n-2)+ ...... +3+2+1=(n - 1) * n/2

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

'

(5) SHELL SORT (Diminishing Increment Sort)

Algo

Q. 6. Explain Shell Sort.


Ans.: This technique is also known as 'Sorting with diminishing increments'. Shell
sort, named after its inventor Shell, divides the array in sub-:array and sorts these
sub-arrays individually in place. To create these sub-arrays, initial increment size is
set to half the array-size and then it is subsequently halved. In the last iteration,
the increment size is unity, thereby sorting the array completely.

1)

2)

3)
4)

Algorithm :

5)

1)

Establish the array a[l. ... n] of n elements.

5)

2)

Set increment inc to arraysize div 2.

6)

Compiled by Prof. Rajesh Bothra

.............Downloaded from

Po " 14

Com pi:

Faa oDEngineers.com----

Mayuranand Classes
26, 6525 7069
1bai. ir 6517 3281

B-403/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 MumbaL ir 6517 3281

3)
4)
5)
6)
7)

Divide the array into inc sub-arrays with inc as the increment size.
Sort these sub-arrays individually.
Reduce the inc to inc div 2.
Repeat steps

3to 5 till inc equals unity.

Return the sorted array.

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

(6) MERGE SORT :

Q. 7. Explain Merge Sort.

worst case
:e of array.
number of

Ans.: An element by itself can be considered to be a sorted sub-array. To start


with, pairs of subsequent array elements are formed and each individual pair is
merged together to form sorted sub-arrays of size 4 each. The process is repeated
till the entire array is sorted.
Algorithm:

~nts'.

Shell
;orts these
1ent size is
t iteration,

I
Pg. 14

1)

Establish the array a[O ... n - 1] of n elements ;

2)

Consider size equal to unity.

3)

Subdivide the array in sub-arrays of size size.

4)

Merge these sub-arrays in pairs of two such that they remain sorted.

5)

Double the size.

5)

Repeat steps 3 to 5 till size exceeds the arraysize.

6)

Return the sorted array.

Downloaded from Faa,,

DEnginears.c m

Pg.

15

Mayuranand Classes
B-403/407, Konark Darshan, Above UTI Bank, laver Road, Mulund (W), Mumbai- 80. if 3251 4726, 6525 7069
8-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas. Sector 17, Vashi, Navi Mumbai. if 6517 3281

B-2161

iiiiiiiiiiiiiii

C-lmplementation :

The~

Non-recursive merge-sort
void merge-sort (int x[J, int n)

The~

inti, j, /1, 12, u1, u2, k;


int size = 1, temp[SO];

The~

while (size < = n - 1)


{

i1 = ~; k

The~

= -1;

while (/1 + size < n- 1)


{

12

= /1

rl

= /2-1;

Perf

+ size;

Assu

= (r1 + size
i = 11; j = 12;

r2

In r
<= n- 1) ? r1 + size : n- 1;

Duri1
max
sort

while (i < r1) &&(j <= r2)

How
requ

if (x[i] < x[j])


temp[ ++k]

= x[i++ ];

(7)

else

Q.S
temp[ ++k]

= x[j++ ];

Ans
step
with
sma
tech

while (i < = r1)


temp [ ++k] = x[j++ ];

can

while (j < = r2)

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

The original X array :

type
147

ls7

ls2

162

131

117

121

122

141

121

122

141

The sorted array with merge size 1 is :


147

ls7

ls2

162

117

131

} st

Comoiled bv Prof. Raiesh Bothra

Pa. 16

---Downloaded tram FaaDoDEngineers.co

Com

Mayuranand Classes
1525 7069
if 6517 3281

B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. til 3251 4726, 6525 7069
B-216/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

The sorted array with merge size

The sorted array with merge size 8 is :

117 121 122 131 141 147 ls2

ls1

162

The sorted array is :

117 121 122 131 141 147 ls2 ls7 162


Performance of the Algorithm :
Assume that file size (array size) n is a power of 2, say n = 2m, so that m = log 2 n.
In merge sort, it is obvious that no more than m passes will be required.
During each pass, maximum n comparisons will be required. This indicates that
maximum m * n comparisons will be required. m * n is n log 2 n. Therefore, merg_e
sort is O(n log n).
However, it must be noted that it requires extra space for the temp array is
required for the merge sort.

(7) QUICK SORT (Partition Sort) :


Q. 8. Explain Quick Sort.
Ans.: This is a method, which performs very well on large arrays or files. At each
step in the method, the goal is to place a particular element in its final position
within the array. In doing so, all elements, which precede this element, have
smaller or equal values, while all elements that follow it have larger values. This
technique essentially partitions the array into two sub-arrays. The same process
can then be applied to each of these sub-arrays and repeated until all records are
placed in their final positions.
Algorithm:
Each time an array is partitioned into two smaller sub-array, these can be
processed in turn using either an array iterative or recursive approach. A general
algorithm bas~d on a recursive approach follows :
1)

Partition the current array into two sub-arrays.

2)

Invoke quick sort to sort the left sub-array.

3)

Invoke quick sort to sort the right sub-array.

Non-recursive quick-sort
# define size 10

typedef struct stack-tag


:.'" .. .

{
int s[size];
int top;
} stack;

Pg.

16

Downloaded from Faa oDEngineers.coi-Pg.


17

Mayuranand Classes
B-403/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

B-4(
B-216/21i

void initialize (stack * sptr)

Illustr

The ori
sptr

~top

= -1;

lb

void push (stack *sptr, int p)

=0

{
if (sptr

~top

>= size -1)

lb

=0

lb

=0

lb

=0

lb

=2

pri nt("stack overflow\n ");


else
sptr--)> s[sptr--)> top]

= p;

int pop (stack * sptr)


{

if (sptr--)> top <= -1)


printf("stack underflows\n");
else
return sptr --)> s[sptr

top--];

lb =

void quick-sort (int left, int right)


lb = (.

{
stack s;
initialise (&s);

lb =!

push (&s, left);


push (&s, right);
while (s--)otop != -1)

lb

=I

right = pop (&s);


lb =

left= pop (&s);


if (left < right)
{

lb =
pos = partitions (left, right);
push (&s, pos+l);
The :

push (&si, right);


push (&s, left); .

push (&s, pos-1);

}
}
}

P:e rf

/* end if*/

/* end while loop* I

ASSL

/*end of quick-sort

ASSL

midc
the
appr
com
files
subCompiled by Prof. Rajesh Bothra

-Downloaded from Faa

Pg. 18

oDEngineers.col

COm(

6525 7069
i. ir 6517 3281

Mayuranand Classes
B-403/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 :

The original X array :


140
lb

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

1-34

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

The sort array is :

l1o

112

114

P:e rformance of Quick Sort Algorithm:

Assume that file size (array size) n is a power of 2, say n

= 2m, so that m = log 2 n.

Assume that the proper position for the pivot always turns out to be the exact
middle of the sub-array. In that case, there will be approximately n comparisons on
the first pass, after which the file is split into two sub-files each of size n/2
approximately. For each of these two sub-files, 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 sub-files. After halving the
sub-files m times. there are n files of size 1.

Pg. 18

l
Downloaded from Faa

oDEngineers.com

Pg. 19

Mayuranand Classes
B-403/407, Konark Darshan, Above UTI Bank, laver 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. if 6517 3281

Thus, the total number of comparisons for the entire sort is approximately,
n

+ 2(n/2) +4(n/4) + .... n(n/n)

8-'
B-216/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
sub-files of size 0 and n-1. If this process continues, a total of n-1, 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

n + (n -1) + (n- 2)+ ..... +2 which is O(n 2 )


Therefore, quick sort behaves most inefficiently if the original data is already
sorted.
(8) HEAP SORT :

Q. 9. Expla.i n Heap Sort.

Ans~:

The drawbacks of the binary tree sort are remedied by the heap sort,
an in-place 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)

Establish the array a[O ... n-1] of n elemen~s.

2)

With the element of the array create an in-place max heap.

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

again represent a max heap.

5)

Repeat steps 3 and 4 for subsequent element.

6)

Return-the sorted arrayi

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

adjust (a, i, n);

Compiled by Prof. Rajesh Bothra

Pg. 20

._Downloaded from Faa oDEngineers.com

Cor

Mayuranand Classes

525 7069
if 6517 3281

B-403/407; Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. if. 3251 4726,65257069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281_

void adjust (int a[], inti, int n)


{

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

if(j < n) && (a[j] < a[j + 1])


j = j

+ 1;

if(x > a[j])


break;

a [j/ 2] = a [j] ;

is already

= 2 * j;

a[j/2]

= x;

. heap sort,
he order of

void heapsort (int a[], int n)


{

inti, temp;

an almost
than or
descending
the largest
~ss

for (i = 1; i < = n - 1 ; i + + )

{
. temp= a[l];

array and

a[l] = a[n + 1- i];


a[n + 1 - i]

= temp;

adjust (a; 1, n - i);


}

}
Illustration :
ay so as to

The original array is :


45 , , 55
40
50 I

24

10

14

15

34

30

10

Max Heap (Ascending Priority Queue) :


Adjust parents such that values at all parents must be greater than the values at
their child locations.

ng order*/

Min-Heap (Descending Priority Queue) :


Adjust parents such that values all the parents should be less than the values at
their child _location.

Pg.

20

Downloaded tram Faa

oDEngineers.co

Pg, 21

Mayuranand Classes
B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W}, Mumbai- 80. 'a 3251 4726, 6525 7069
8-216/217 Vardhman Chambers, Above UTI Bank, Nr Bab.ubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281

Heapify' process

B-216/~

After

In general

~
0 .b

Left Child

- Location

Right Child

2*i+l

1.

x = 24, i = 5 (Adjust 5th parent)


2.

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

* parent is at proper place,


no adjustment is required.

5.

X=

40, i = 1

Aft

45

3~

@
6

8.
7

10
Compiled by Prof. Rajesh Bothra

Pg. 22

-Downloaded tram FaaDoDEngineers.co

Con

Mayuranand Classes

7069
6517 3281

B-403/407, KonarkDarshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. tl 3251 4726,6525 7o69
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, NaviMumbai. V 6517 3281.

After heapifying an array :


xation

55

50

45

40

30

10

14

15

34

24

10

) Right Child

+1

Pass No.1

1. Swap (a[i], a[10])

2. Adjust parent i = 1, n = 9; x = 24.

45

3'\

@@
6

10

After pass No. 1 :

ace,

50

40

45

34

30

10

14

15

24

55 )

10

red.
Pass No.2

1. Swap (a[1], a[9])

2. Adjust parent i

= 1, n = 8; x = 24

After pass No. 2 :

45

40

24

34

30

10

14

15

50

55

10

Downloaded from Faa oDEngineers.co

Pg. 23

Mayuranand Classes
B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. if 3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. ir 6517 3281

.B-403
B-216/217 I

Pass No.3
1.

2. Adjust parent i = 1, n = 7; x = 15

Swap (a[1], a[8])

1. Swc

24

3~

@
6

........ 4

@
8

After~

After pass No. 3 :


~~~-3-4~-2-4~--15~--30~--10~--14~--4-5~-5-0~-5-5~

10

Ppss No.4
1.

swap (a[1], a[7])

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.

Swap (a[1], a[6])

2. Adjust parenti

= 10

After

15
4

= 1, n = 5;

10

. After pass No. 5 :

30

15

24

10

14

34

40

45

50

55

10

Compiled by Prof. Rajesh Bothra

-Downloaded from Faa

Pg. 24

DEngineers.c

Compi l

6, 6525 7069
bai.
6517 3281

Mayuranand Classes
B-403/407, Konark Darshan, 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, Navi Mumbai. ir 6517 3281

Pass No.6
X=

15

2. Adjust parent i

1. Swap (a[1], a[S])

= 1, n = 4;

= i4

3~

After pass No. 6 :

24

15

14

10

30

34

40

45

50

55

10

Pass No.7

2. Adjust parent i = 1, n = 3; x = 10

1. Swap (a[1], a[4])


( = 14

14

......... 2

(24::}

r~ai
.......

.......

After pass No. 7 :

15

10

14

24

30

34

40

45

so

55

10

Pass No.8

2. Adjust parent i = 1, n = 2; x = 14

1. Swap (a[1], a[3])


= 10

15
2

After pass No. 8 :


1

Pg.

24

14

10

15

24

30

34

40

45

5o 1 55
9

10

Downloaded from Faa ,oOEngineers.co

Pg. 25

Mayuranand Classes
8-403/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.

Swap (a[l], a[2])

. B-40:
B-216/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.

Performance of the Algorithm :

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 in-place
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 less-significant position are already
sorted on a less significant position.

(10) B

It may be noted that the sort works on positive numbers only.

First

Algorithm:

Secane
a sorte

Q. 11.
Ans.: l
p~

1)

Establish the array a[O ... n-1) of n elements.

2)

Call bucket sort repeatedly on least to most significant digit of each element as
the key.

Algori1

Return the sorted array.

2)

3)

1)

3)

4)

Compiled by Prof. Rajesh Bothra

Compile<

-oownloaded from Faa aDEngineers.c 1: ---

Mayuranand Classe s
525 7069
6517 3281

B-403/407, Konark Darshan, Above UTI Bank, laver Road, Mulund (W), Mumbai- 80. ir 3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, NrBabubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. W 6517 3281

Illustration (for 3 digits numbers)

= io

The original array :

[ 294 1 357 1 392 1 5s41 370 1 927 1~

370

392

423

554

927

L.J 1357 1 (__J

(._J l___j 12941 t___j


2
4
3
5

L__j L_j

. 0

(__J

The array is sorted on least significant digit.


1

:ollect the
but at the
smallest)
ty queue.
f the heap

37o 1 3921 423 1 294 1 5541 357 1 927 1


0

L..J

(__J

1423 1 927
0

complete
the depth
1 array we
each step
pth of the
:n logz n).
:age area,
l in-place

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

I Sorted array I 294 I 357 I 370 I 392 I 423 I 554 I 927 I


Performance of the Algorithm

The algorithm takes O(n) time per bucket sort.


There are log1qk = O(log n) bucket sorts.
numbers
rst so that
ving same
e already

So the total time is O(n log k).

(10) BINARY TREE SORT :

- Q. 11. Explain Binary Tree Sort.


Ans.: This has two phases.

First phase is creating a binary search tree using the given array elements.
Second phase is traverse the created binary search tree in-order, thus resulting in
a sorted array.

dement as

Pn ?t;

Algorithm:
1)

Establish the array a[O ... n - 1] of n elements.

2)

Create a binary search tree with the elements of the array.

3)

Traverse the tree inorder and store the elements back in the array.

4)

Return the sorted array.

Downloaded from Faa

oiEngineers.col

Pg. 27

Mayuranand Classes
B-403/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-~

B-216/2'

C - implementation :

typedef struct node

While
the ef
decidE
prefer
other
select

int data;
node * left, *right;
} node;

SE

It is d
meth'
the t
distrit

void modi_inorder (node * root, int x[])


{

static int T = O;

Selecj
For a
increc

if( root)
{

If the
adopt
to 0( 1

modi_inorder(root- > left, x);


x[i++ ]= root- > data;
modi_inorder (root - > right, x);

If the
heap
whicr
avoid

}
void bin.;...tree_sort(int x[], int n)
{

inti;
node * root = NULL;
for ( i

= 0;

i < n; i + +)

add (&root, x[i]);


modi_inorder(root, x);
return;
}

Illustration :
The original X array :

I 40

56

4si 53

24

10

14

12

34

34

40

45

53

56

The sorted array is :

10

12

14

24

Performance of the Algorithm:


The average number of comparisons for this method is O(nlog 2 n). But in the worst
case, the number comparisons required is O(n 2 ), a case which arises when the sort
tree is severely unbalanced. e.g., original data : 4, 8, 12, 17 1 26
In this case, the resultant binary tree will in fact be a linear liked list. The insertion
of the first node requires no comparisons, the third node three comparisons, and so
on. Thus, the total number of comparisons is
1 + 2 + 3 + ...

Comoiled bv Prof. Raiesh Bothra

+n

= n(n

+ 1) I

--Downloaded from Faa

= O(n 2)

Pg. 28

oDEngineers.co

Com~

Mayuranand Classes
6525 7069
li. ir 6517 3281

B-403/407, Konark Darshan, AboveUTI Bank, Zaver Road, Mulund {W), Mumbai- 80. if 3251 4726,6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, NrBabubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281

SELECTION OF SORTING TECHNIQUES

While selecting a sorting technique for a given data, it is necessary to determine


the efficiency of the algorithm as compared to other algorithms. Two criteria, which
decide the efficiency, are computing ' time and additional storage space. It is
preferred if the time required as well as additional memory space is less than any
other algorithm. The nature of original data, if known, may also play a major role in
selecting the right technique of sorting.
It is difficult to assert that a particular sorting technique is always superior to other
methods for all inputs. Choice of one method over other many times depends on
the type of input to be sorted. Properties of input to be considered are size,
distribution, order etc.
Selection and bubble sort techniques can be used if the size, n of the input is smalL
For a size more than 1000 they are considered to be unsuitable as the time
increases more rapidly with size in worst case (O(n 2 )).

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 .

Downloaded tram Faa ,oDEngineers.c 1-----Pg.


29

Mayuranand Classes
B-403/407, Konark Oarshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai 80. V 3251 4726,6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. ir 6517 3281

B-403/
B-216/217 Va

AOA

However,
of the ori,

CHAPTER 3 : SEARCHING METHODS

However,
the senti
linked li~
contain in
linked lis

SEQUENTIAL
SEARCHING (LINEAR. SEARCH)
.

Q. 1. Write an algorithm for sequential search.


Ans.: Given an element no and a list of data find whether or not no is present in
the list of size n using sequential search. If present, it returns the position of no in
the list, -1 otherwise.
Algorithm .:
1)

Establish an array [0 .... n - 1] of n element

2)

Set i

3)

while (i < = n- 1) && (x != a[i]) do

Es

2)

SE

3)

SE

4)

5)

if

+ 1;

if ( i < = n - 1) then

Perforr

return i;

It is ob

else return -1;

linearly
instead
sentine
more e

Performance of the Algorithm:


It is obvious that the algorithm is O(n).

1)

= <1>;
i = i

4)

Algoritl'l

+ "IN[

SEQUENTIAL SEARCH WITH SENTINEL VALUE

Q.3.E

Q. 2. How to improve the efficiency of sequential search ?


Ans.: During every iteration of sequential searching two comparisons are done,
i.e., i < n and a[i] == n 0 The first comparison checks for the data exhaustion and
second comparison checks for the required data. The first comparison can be
avoided if we know in advance that the data exists in the list. That will make the
total number of comparisons half.
Such advance knowledge is usually unlikely. In a technique called 'sequential
search with sentinel value' the data to be searched is initially added at the end of
the list before the sequential search starts. Such an added value is called 'sentinel
value' and is not part of the data. When the sequential search is carried out, no
consideration needs to be given to da.ta exhaustion as we have put the data at the
end of the list and the search loop is bound to get terminated after finding the
same at least at the end of the list. It is also possible that the original data contains
the element to be searched. In such a case, the search loop will be terminated
early, i.e., before getting to the end of the list.
After the termination of the loop, we can check for the reason for termination of the
search loop. If it is due to sentinel value i.e., the data is found at the last position
in the list, then we can conclude that the element wa.s not present in the original
list. If it is not the sentinel value, then we can conclude that the element was
present in the original list and return the position of the same.
Sequential search can be carried out when the list is in the form of an array or a
linked list. However, sentinel search technique is more useful in array
implementation than in linked list implementation due to following reasons.
In case of array implementation, addition of sentinel value in the origiAal list at the
end is done by simple .assignment statement. It also does not alter the original data
if the size of the array is not altered. Under such circumstances; the sentinel value
forms part and start of the garbage value.
'Compiled by Prof. Rajesh Bothra

Pg. 30

--Downloaded from Faa .oDEngineers.col

Ans.: it invol

inCI-ex

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
B-403 I 407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. if 3251 4726,6525 7069
B-216/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)

Establish an array [0 ... n-1] of n elements.

2)

Set a[n] to x.

3)

set ito 0.

4)

while (x ! = a[i])

i++;
5)

if (i <= n -1) return i


else return -1;

Performance of the Algorithm :

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.

INDEXED SEQUENTIAL SEARCH

(~

C :r-,

...,

-~

1.
: .

,. f.i

/\
:)

Q. 3. Explain Indexed sequential search with example.


are done,
1ustion and
on can be
I make the
'sequential
the end of
~d 'sentinel
ed out, no
data at the
finding the
ta contains
terminated
3tion of the
3St position
:he original
ement was

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 is-carfe"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
a-index 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'

The algorithm used for searching an indexed sequential file is straightforward . .

Algorithm:

1)

Establish an array a[O .... n-1] of n elements . .

2)

Establish an index array to store every


array.

3)

Search the index array for an entry greater than or equal to ~

4)

Calculate lower and upper bound using index array.

4th

entry (h ~stepwise) of the original

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 th-e
in thefi'fe must be accessed, yetfth~-

-records

DIEngineers.col'ar:. ~:

Downloaded from Faa

\
/
fi{

Mayuranand Classes
8-403/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. 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.

8-403
B-216/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)

Fig. : Indexed-Sequential File

2)

Compiled by Prof. Rajesh Bothra

Pg. 32

-Downloaded tram FaaDoDEngineers.co

Comp

Mayuranand Classes
6525 7069
La 6517 3281

8-403/407, Konark Darshan, Above UTi Bank, Zaver Road, Mulund (W), Mumbai- 80. it 32514726,6525 7069
8-216/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

Q. 4. Writ.:! an algorittlm for Binary search.

t"

Ans.: Given an element no and a set of data that is strictly non-descending


numerical order, find whether or not no is present in the set in binary search
technique. If present, it returns the position of no in the list, -1 otherwise.
Algorithm:
1) Establish ordered array size n and the value sought no.

2)

Establish the ordered data set a[O ... n-1].

3) Set upper and lower limits (i.e., initially left = 0 and right = n - 1);
- (a)
(b)

Compute the middle position of remaining array segment to be searched.

If the value sought is equal to a[mid] then return mid


else if the value sought is greater than current a[mid]

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)

Efficiency of the Algorithm:


Assume that the array size n is a power of 2, say n = 2m, so that, m = log 2 n.
In binary search, it is obvious that no more than fn passes will be required. During
each pass, maximum only two comparisons will be required (one for the equality
and if failed, another to decide which part of the array the next search need to be
carried out). This indicates that maximum 2 * m comparisons will be require 2 * m
is 21og2n. Therefore, binary search is 0 (log n).

INTERPOLATION SEARCH

Q. 5. Write short note on Interpolation search.


Ans.: Another technique for searching an ordered array is called interpolation
search. If the keys are uniformly distributed between k(O) and k(n-:-1), the method
may be even more efficient than binary search.
Initially, as in binary search, left is set to 0 and right is set to n-1, and throughout
the algorithm , the argument key key is known to be between k(left) and k(right).
On the assumption that the keys are unifo'rmly distributed between these two
values, key would be expected to be at approximately position.
mid

= left + (x -

a[left]*(right- left)

1 (a[right]

-a[left])

If key is lower than k(mid), reset right to mid-1; 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)

Establish ordered array size n.

2)

Establish the ordered data set a [0 ... n -1].

Downloaded from Faa

oOEngineers.co

Pg. 33

Mayuranand Classes
B-403/407, Konark Oarshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. 2 3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281

3)

Set upper and lower .limits (i.e., initially left

= 0 and

right

=n -

a)

Compute the position mid by using interpolation formula.

b)

If the value sought is equal to a[mid] then return mid.

8-41
. B-216/21 .

1).

else if the value sought is greater than current a[mid]

+IN'

then
b.l) adjust lower limit accordingly (i.e. , left= pos+l)
b.l) aojust upper limit accordingly (i.e ., right = pos-1)

Performance of the Algorithm :


Indeed; if the keys are uniformly distributed through the array, interpolation search
requires an average of log2 (log2n) comparisons and rarely requires much more,
compared with binary search's log 2 n (again, considering the two comparisons for
equality and inequality of key and k(mid) as one).

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

Q. 6. Write short note on hashing.


Ans.: H~hing ~_Q_ne_ ~of the fastest searchinQ tec~niques. In this method we are
using a function (hash fUQ_~t1onl -whfcl1--wfr[gJ_\'e the vaTue"-of the mdex or aaaress1o
be searched in thear@_y ~or !b_~ ~~~. -Ifff1e-~~~~ ..9.Y_aii~.QJg_ In~tlie ~-~-ress
given by tne hash function we can s!Pr~.~~~-~["~!JJ!J.9~l~.~.r~,.,.~!":.~.~Jf. If the key is not
available in the specified address tflen will search the next location of the table.
This process is known as linear _probing. If we want to use the hash searching
technique to search for a .giverrt<ey, tFlen the table or array is created using the
same hash function and the same linear probing technique. ,

The g

Efficiency of the Algorithm :

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.

Compiled by Prof. Rajesh Bothra

---Downloaded from Faa

Pn_ 14

DEngineers.c

Com pi

Mayuranand Classes
525 7069
il 6517 3281

B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. if 3251 4726, 6525 7069
- B-216/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

INTRODUCTION AND TERMINOLOGY

A graph G consists of two sets V and E. V is a finite non.,..empty set of vertices, E is


a set of pairs of vertices; these pairs are called edges. V(G) and E(G) will
represent the sets of vertices and edges of graph G. We will also write G = {V, E) to
represent a graph. In an undirected graph the pair of -vertices representing any
edge is unordered. Thus, the pairs (V1, V2) and (V2, V1) represent the same edge.
In a directed graph each edge is represented by a directed pair <V1, V2>. V1 is the
tail and V2 the head of the edge. Therefore, <V2, V1> and <Vl, V2> represent
two different edges.

can have
)nsistently
rates into
eater than
:er around

Gl
od we are
aaaressto
ie--acra-ress
k-e-y-~is' "n ot
the table.
searching
using the

II be very
other two

G2

G3

The graphs G1 and G2 are undirected G3 is a directed graph or digraph.


V(G1) = (1,2,3,4}

E(G1)= {(1,2)r(1,3),(1,4),(2,3),(2,4),(3,4)}

V(G2) = ( 1,2,3,4,5 ,6, 7)

E(G2)= { ( 1,2),( 1,3),(2,4 ),(2,5),(3,6),{3, 7),{ 4,5),(6, 7)}

G(G3) = (1,2,3}

E(G3)= {<1,2>,<2,1>,<2,3>}

The maximum number of edges in an undirected graph of n vertices is n(n-1)/2.


An n vertices graph with exactly n(n-1)/2 edges is said to be complete. G1 is the
complete graph on 4 vertices while G2 and G3 are not complete graphs. In the case
of directed graph on n vertices the maximum number of edges in n(n-1).
If (Vi, V2) is an edge in graph, tf1en we shall say the vertices V1 and V2 are
adjacent and edge (Vl, V2) is incident on vertices Vl and V2.
A subgraph of G is a graph whose all vertices as well as nodes are included in the
graph G.

A path from vertex Vp to vertex Vq in graph G is a sequence of vertices

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 path is the number of edges in it.


A simple path is a path in which all vertices expect possibly the first and last are
distinct. A path such as ( 1, 2), (2, 4 ),( 4, 3) we write as 1, 2, 4, 3. Paths 1, 2, 4, 3
and 1, 2, 4, 2, are both of length 3 in G. First path is a simple path while the
second is not.

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.

In an undirected graph, G, two vertices V1 and V2 are said to be connected if


there is a path in G from Vl to V2. An undirected graph is said to be connected
if for every pair of distinct vertices Vi and Vj in V(G) there is a path from Vi to Vj
in G.

Pg. 34

oDEngineers.col

Downloaded from Faa .

Pg. 35

Mayuranand Classes
B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. if 3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281

B-4l
8-216/21"

GRAPH REPRESENTATION

Q. 1. Write short note on Graph representation.


Ans.: Graph can be represented in several forms. We shall study only the two most
commonly used forms viz., adjacency matrix representation and adjacency Jist
representation.

ADJACENCY MATRIX REPRESENTATION

Let G =(V, E) be a graph with n vertices, n ~ 1. The adjacency matrix of G is is two


dimensional n x n array, say A, with the property that A[il[j] = 1 if and only if the
edge (vi,vj) is E(G). A [i] [j] = o if there is no such edge in G.
}

The adjacency matrix for the graph Gl is given below :


Ad' =
J

[~ ~ ~ ~

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)

If Adh [i] [j]


of length 2.
2)

= true

or 1, then we can say that there exists a path from i to j

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:

The function for creating the adjacency matrix is as follows .:


#define size 10

L] [ ],

entrie~

the n u
in the
the n

Each

CREATING AN ADJACENCY MATRIX

void create-graph (int

Using

The d

int, int);

#defil

void main()

typed

int g[SIZE] [SIZE], n v, e,


printf ("how many vertices\n");
scanf (" 0/od" &v);

} nex

printf ("howmany edges\n");

nextn

scanf (" 0/od", &e);


create-graph(g, v, e).;

}
void create-graph (int g[ ][ ], int v, int e)

{
int i, j, a, b;
Compiled by Prof. Rajesh Bothra

----Downloaded from Faa,,

Pg. 36

Com pi

DEnginears.c m----

Mayuranand Classes
525 7069

ss17 32a1

B-403 I 407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. if 3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank. Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. 2 6517 3281

for (i = 1; i <= v; j++)


for (j
~two most
3Cency .list

= 1; j < = v;
g[i][j] =

j + +)

~;

for(i = 1; i <= e; i++)

{
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;

/*plane undirected graph*/

}
}

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

3. For weighted undirected


4.

For weighted

dir~cted

g[a][b] = g[b][a]

= w .. ./*w is weight or cost*/

g[a][b] = w

ADJACENCY LIST REPRESENTATION

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

Downloaded from Faa

oDEngi eers.co1

Pg. 37

Mayuranand Classes
8-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. if 3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281

edge t
criteric
minim1

Adjacency list representation for Graph Gl is given below:

Li2IJ--1

Vl

Uill-----1
Uill-----1
Uill-----1

V2
V3
V4

V3
N3

V2
V2

I H
I H
[ H
I H

B-4!
B-216/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
Con-s 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

Q. 3. Write short notes on spanning trees, spanning trees of minimum cost.


Ans.: :'&'.Y_!r~-~-~~nsl,~!-~. 9. S<?I~.-~Y . .Qf ~_99es qf a_ g_~C3PQ a~d including _al_l _the v~rtic.es of
t_~e graph is known as a spanning tree. Th~ spanning tree resulting_Jrom . a d~pth

llrsr. search.....,s

ae-iith-~~i~st sp~~ning-lree ana _J h~ -~P~D.Qing __ ~c~~


first 'sea'(ch "'is known as . brea~th first spanning t~~e.
Th~__
fol_l~~~n-g flgy_r.~__Sh<?.\Y.S _a -~_om_p-le~e 'graph _and thr~~-~ot' 'i ts span~ing trees: ) .
.

resulting''lrom'

knowr:,.-/as

a breadth

:'...

;f

t/

Sta

MINIMUM COST SPANNING TREE

(Giv~_n ~-~~grm_~-~!~. d. 'l'{~jg_bted___9r9Pb ~__it__js . Qft~n de~"i~_g_~o

<:reate a ~panning tre~J


for G such thatthe sum of, the weights of the tree edges in T us .is small as
possibl~: --su-ch a tree --is called (;l- mi.nimum cost spanning tree and. represents--H1e
"cne.a pest way of connecting ail the nodes in G. \ .
.., ..

...

-.

'

Stc

A greedy method to obtain a minimum cost-spanning tree would build this tree
rni'Y'\nilorl h\1

Prnf

Q~iPc:h Rnthrr~

----Downloaded from Faa

Pg. 38

oDEngi eers.co1--

Mayuranand Classes
B-403/407, Konark Darshan, Above UTI Bank, laver Road, Mulund (W), Mumbai- 80. if 3251 4726,6525 7069
B-216/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: Jhese-ar-eh~~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

for . the. spiinning

... d.ecreasin1 order ~fC:Q?~~) The set T edges -so


seiecfed .
tree~
be such that it
possible to compete T into a tree. Thus, T may not be a tree
at all stages in the algorithm. T can be completed into a tree if and only if
there are no cycles in T. This method is known as Kruskal's algorithm.

is

Consider the following graph.

~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 small-as
presents -the
. Ji\d this tree
Pg. 38

Downloaded from Faa

DEngineers.c

Pg. 39

Mayuranand Classes
B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W). Mumbai- 80. V 3251 4726, 6525 7069
B-216/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

B-4
B-216/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

SHORTEST PATH PROBLEM

In a weighted graph, it is frequently it is .frequently desired to find the shortest


path between two nodes s and t. The shortest path is defined as a path from s to t
.such that the sum oft~e weights of the edges on the path is minimized.

initial
visite
addqt

GRAPH TRAVERSAL

while

Q.

4~

Explain traversal method for graph with example.

Ans.: Given an undirected graph G = (V, E) and a vertex V in V(G) we are


interested in visiting all vertices in G that are reachable from V (i.e., all vertices
connected to V). We shall look at two ways of doing this : Depth first search and
Breadth first search.

DEPTHFIRSTSEARCH

Depth first search of an undirected graph proceeds as follows :


The. starting vertex v is visited. Next an unvisited vertex w adjacent to v is selected
and a depth first search from w initiated. When a vertex u is reached such that all
its adjacent vertices have been visited, we back up to the last vertex visited which
has an unvisited vertex w adjac.ent to it and initiate a depth first search from w.
The search terminates when no unvisited vertex can be reached from any of the
visited ones.
Compiled by Prof. Rajesh Bothra

-Downloaded from Faa

Pg. 40

oDEngi eers.co1

Each
most
each

Com pi

25 7069
il6517 3281

Mayuranand Classes
B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund {W), Mumbai- 80. if 3251 4726, 6525 7069
B-216/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.

BREADTH FIRST SEARCH

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

are visited and so on .

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

initialize queue (q); {q is a queu}


. visited [v] : = true;
addqueue (q, v); {add vertex vto queue
while not empty queue (q)
{

for all vertices w adjacent to v o

) we are
I vertices
arch and

if not visited [w], then


{
addqueue (q,w);
visited [w] :=true;
}

:selected
h that all
:ed which
from w.
1y of the

Pg. 40

deletequeue

(q,\~);

{remove from queue vertex v}

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 ) _

Downloaded from Faa,


!

DEnginears.c m

Pn 41

Mayuranand Classes
B-403/407, Koriark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. 2 3251 4726, 6525 7069
B-216/217Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. 2 6517 3281

.B-216.

Consider the graph given below :

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

"

--Downloaded from Faa

Pa. 42

oDEngineers.co

Com

Mayuranand Classes
; 7069
~ 6517 3281

B~03 1407, Konark Darshan, Above UTI Bank, laver Road, Mulund (W), Mumbai- 80.

B 3251 4726, 6525 7069


8-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. tr 6517 328~

AOA
CHAPTER 5 -: ALGORITHMS
.~;_ .

~\
''

GREEDY METHOD

Q. 1. write short note on 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 work-efficient. 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

( Gr~E!dY algorithms ar~_ typic(311y used to solve _()Ptimization problef!1s.'YExamples)


include~J[.Q_9in_ g t,~-~.?..b:9rt_~_~!--~~~t~ ~~~61 -~~-~-~~o"~~-:_t.~ ani?~-~~-~) through a netwod(, 'o r .
( tl!J_gln9 . t.b~~---~~s.t .<?.n:!~-~--_to __ ~.><-~S.':Jt~ ~ . s._~t <?.fJ<>~S. 00 a COfl1puter) In such a context a
greedy algorithm works by choosing the i~, or the job, that seems most promising
0
at any instant; it( !'lever reconsidE!r.s . ~-IS- ' ~.E!C:i.J.9.!1} whatever situation may arise
later. There is nc)--need_,_ to . evaluate --alternatives, or to employ elaborate
book-keeping procedures allowing previous decisions to be undone.

GENERAL CHARACTERISTICS OF GREEDY ALGORITHMS

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>

As the algorithm proceeds, we accumulate two other sets. One contains


candidates that have already been considered and chosen, while the other
contains candidates that have been considered and rejected.

)o>

There is a function that checks whether a particular set of candidates provides


a solution to our problem, ignoring questions of optimality for the time being.
For instance, do the coins we have chosen added upto the amount to be paid ?
Do the selected edges provide a path to the node we wish to reach ? Have all
the jobs been scheduled ?

)o>

A second function checks whether a 'Set of candidates is feasible, that is,


whether or not it is possible to complete the set by adding further candidates
so as to obtain at least one solution to our problem. Here too, we are not for
the time being concerned with optimality. We usually expect the problem to
have at least one solution that can be obtained using candidates from . the set
initially available.

)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?

Downloaded from Faa

oDEngineers.com' shal:gs::

..

Mayuranand Classes

B-403/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

B-4
B-216/21

Consid

.fat at times there may be several plausible selection functions, so we have to


choose the right one if we want our algorithm to work properly.
We have already used this greedy strategy in Dijskatra's algorithm, Prim's
algorithms etc. Another example of greedy algorithm is the knapsack problem. It
may however, be noted that greedy algorithm need .not necessarily give an
optimum solution, e.g., traveling salesperson's problem.

KNAPSACK PROBLEM

.Q. 2. Explain Knapsack problem.


Ans.: We will see how the greedy strategy can be applied to solve the knapsack
problem.
Problem Definition :
We are given n objects and a knapsack. Object I has a weight w, and the .knapsack
has a capacity M. If a fr~ctlon x1, o s x1 s 1, of object I is placed Into the knapsack
then a profit .of ~x 1 Is earned. The objective is to obtain a filling of the knapsack
that maximizes the total profit earned.

Final

So, the problem may be formally stated as


Maximize
n

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:

Find an optimal solution to the knapsack instance.

Q. 3.

n = 7, M = 15,

Ans.:

de con
the ~

(Pl,p2, .....p7) =(10,5,15,7,6,18,3) and

subin ~

(w1,w2 , ....w7 ) = (2;3,5,7,1,4,1)

sol uti ~

Solution:

Two

Initially, we calculate profit


order:

Dl

I weight ratio and then arrange them in descending

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-'---

.:

'i' ' ; ','<

;::~-

'

'

Mayuranand .Classes
7069
)517 3281

B-403/407, Konark Darshan, Above UTI Bank, laver Road, Mulund (W), Mumbai- 80. if 3251 4726, 6525 7069
.
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. ir 6517 3281

Considering in the order of rank :


1ave to
Prim's
>lem. It
~ive an

1apsack
..

napsack
napsack
napsack

1.

item No. 5 - weight = 1, profit = 6


Balance Knapsack Capacity = 15 - 1

= 14

2.

Item No. 1 - weight = 2, profit = 10


Balance Knapsack Capacity = 14 - 2

= 12

3.

Item No. 6 - weight = 4, profit = 18'


Balance Knapsack Capacity = 12 - 4 = 8

4.

Item No. 3 - weight = 5, profit = 15


Balance Knapsack Capacity = 8 - 5 = 3

s.

Item No. 7 - weight := 1, profit = 3


.Balance Knapsack Capacity = 3 - 1

6.

Item No. 2 - weight = 2, profit = 10/3


Balance Knapsack Capacity = 2 - 2 = 0 .

=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

DIVIDE AND CONQUER

Q. 3. Write short note on Divide and Conquer approach.

Ans.: Divide-and-conquer is a technique for designing alg9rithms that consists of


decomposing the instance to be solved into a number of smaller subinstances of
the some pt'oblem, solving successively and independently each of these
subinstances and then combining the subsolutions thus obtained . to obtain the
solution of the original instance.
scendlng

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
divide-and-conquer technique lies in the answe'r.to this latter question".

THE GENERAL TEMPLATE

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-~nd-conquer 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

Downloaded from Faa

oDEngineers.col

Pg. 45

Mayuranand Classes
B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. if 3251 4726, 6525 7069
B-216/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

recombine the y 1's to obtain a solution y for x

Q.4.W

return y

Ans.: R
type of
may chi

Some divide-and-conquer algorithms do not follow this outline exactly; for


instance, they could require that the first subinstance be solved before the second
subinstance is formulated.
The number of subinstances, /, is usually small and independent of the particular
instance to be solved. When I = 1, it does not make much sense to "decompose x
into a smaller instance x1 " and it is hard to justify calling the technique
divide-and-conquer. Nevertheless, it does make sense to reduce the solution of a
large instance .to that of a smaller one. Divide-and-conquer goes by the name ofsimplification in this case. When using simplification, it is sometimes possible to
replace the recursivity - inherent in divide-and-conquer by an iterative loop.
Implemented in a conventional language such as C on a conventional machine that
runs an unsophisticated compiler, an alternative is likely to be somewhat faster
than the recursive version, although only by a constant multiplicative factor. On the
other hand, it may be possible to save a substantial amount of storage in this way;
for an instance of size n, the recursive algorithm uses a stack whose depth is often
is n(log n) and in bad cases even in n(n).

B-403
B-216/217'

USE OF DIVIDE AND CONQUER APPROACH IN SORTING PROBLEM

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

if the list has more than one element .


{

partition the ljst into lowlist and highlist;


sort(lowlist);
sort(highlist);
combine(lowlist, high list);
}

}
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

---rD~~~~d~ tram Faa

oDEngi

eerSa.Com---C-ompil

Mayuranand Classes
169
i17 3281

B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80 . .if 3251 4726, 6525 706~
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi MumbaL B 6517 3281

DYNAMIC PROGRAMMING

Q. 4. Write short note on 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.

Previously, we saw that it is often possible to divide an instance into subinstances,


to solve the subinstances (perhaps by dividing them further), and then to combine
the solutions of the subinstances so as to solve the original im~tance. It sometimes
happens that the natural way of dividing an instance suggested by t~e structure of
the problem leads us to consider several overlapping sub instances. If we solve each
of these independently, they will in turn create a host of identical subinstancs. If we
pay no attention to this duplication, we are likely to end up with an inefficient
algorithm; if, on the other hand, we take advantage of the duplication and arrange
to solve each subinstances only 0r1~e, saving the solution for later use, then a more
efficient algorithm will .result.' The underlying idea of dynamic programming is thus
quite simple : avoid calculating the same thing twice, usually by keeping a table of
kndWn results that fills up as subinstances are solved.
, Divide-and-conquer is a top-down method. When a problem is solved by
divide-and-conquer, we immediately attack the complete instance, which we then
divide into smaller and smaller subinstances as the algorithm progresses. Dynamic
programming on the other hand is a l?_o,t~QJl'I.:UP techni.que. We usually start with
the smallest, and hence the simplest,~sillJinstances. By combining their solutions,
we obtain the answers to subinstances of increasing size, until finally we arrive at
the solution of the original instance.

BACKTRACKING

Q. 5. Write short note on Backtracking and also explain N-Queen's


problem.
Ans.: Often the original problem translates to searching for a specific node, path or
pattern in the associated graph. If the graph contains a large number of nodes, and
particularly if it is infinite, it may be wasteful or infeasible to build it explicitly in
computer storage before applying one of the search techniques we have
encountered so far.

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 depth-first 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 t-ho n~rti~l c::nl11tinn rnnc::tn1rt'Prl c::n f::tr r::~nnot be

Downloaded from Faa oDEngineers.com!:~c::

. Mayuranand Classes
8-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund CN), Mumbai- 80. V 32514726,6525 7069
8-216/217 Yardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Yashi, Navi Mumbai. if 6517 3281

B-403/
B-216/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

This is a classic combinatorial problem to place n queens on an n x n chessboard so


that none of them "attack" each other. In other words, no two of them are on the
same row, column, or diagonal.

void ma

. For solving this problem, we are using a design strategy known as backtracking.
Let us consider the problem for n = 8.

ir

In 8 queen's problem, the result or solution can be expressed as (xl,X;u ....Xa),


where iS X1 is the position of the 1st queen, Xz is the position of the 2nd queen and
so on. Queens are numbered from 1 to 8 and without losing generally we are
assuming that Queen 1 will be placed in row 1, queen 2 will be placed in 2nd row
and so on. So x1 will be any value from 1 to 8 since there are 8 columns in the
row.
To solve this problem, first we are finding a placed for the first queen. Let it be 1.
i.e., x[l] = 1.

{
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 <= k-1) && (flag)

{
if( (x[i]

== x[k]

! ! (abs(i-k)

==

abs(x[i] - x[k] )))

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(i-k) 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

B-403/407, Konark Darshan, Above UTI Bank, laver Road, Mulund (W), Mumbai- 80. if 3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 11, Vashi, Navi Mumbai. 2 6517 3281

~ts

back
solution

1oard so
! on the

row position of ith queen.

row position of kth queen.

x[i]

column position of fh queen.

x[k]

column position of kth queen.

void main()
{

racking.

int n;
printf ("how many queens\n");

~, .... x8)'

scanf (" 0/od:; &n);

~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;

while ((x[k] <= n) && (!place(k)))


x[k]

= 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

Downloaded tram FaaDoDEngineers.co

Pg. 49

Mayuranand Classes
B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. if 3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281

Prob

BRANCH AND BOUND

Q. 6. Write short notes on Branch and Bound method.


Ans.: Branch and bound is a general algorithmic method for finding optimal
solutions of various ,~9J!.lj_mJ_~~l!.Q..n.,. . . problems, especially in -~J~.r,~l~. and
com~l'!~,~~-rJ~I __~p-~J".li~,~~i()~: It b~longst~ t~e class of imP._~i~it en_ um~rat_i()ll
m E!thods. The method was first prO'posed 'by A. H. Land and A. G. Doig in i960
for--linear programming.

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:Jranch-and-bound proc:edure
~~9U..ir.e~- -~wotogl~. .
--- -

... ... The

B-216/

~rst

one is a smart way of covering the feasible region by several smaller


fe-ailbfe s~B"re9k>ns (ideally, s'J:>Utting into subregions)_. This ls called _brand1lng,
since - the'' 'pr6cedure is 'repeate'd recursively to each of the subregions and all
produced (~.~J?.T~9i2:~?- ..-natu. r,C311Y .f2CQ'1 . a .. 1r~--~ s;ructurel, c:~ll~d __-~~ar.c:.~ tre~.. or
Pranch-()n(j-l)ound-t~ee) or something similar. Its nodes are the constructed
subre~}'lor15':- -
. -~- ' ........... ..

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

(The efficiency of the method depends critically on the effectiveness of the


b-r~6.sbl.Q_g and - -~o~~-!:l~J.lr1g -~lg_qrith_ ms tJsed~~r bad choices could lead to repeated
branching, wlfhout any pruning, until the sub-regions become very small. In that
case, the method would be reduced to an exhaustive enumeration of the domain,
which is often impractically large. There is no universal bounding algorithm th_at
works for all problems, and there is little hope that one will ever be found;
therefore the general paradigm needs to be implemented separately for each
application, with branching and bounding algorithms that are specially desig-ned
for it.

TRAVELLING SALESMAN PROBLEM

Q. 7. Write short notes on Travelling salesman problem


Ans.:

If a salesman starts at point A, and if the distances


between any two points is known, what is the
shortest round-trip the salesman can make which
will visit all points once and return to point A ?
The travell~ng salesman problem (TSP) is a
in
di_s crete_ or
combinatorial
problem
optimization. It 1s a prominent iiTustration Of-a
class of problems in computational complexity
theory which are han:lTc>solve.---------------- ------. __..___ _____

Compiled by Prof. Rajesh Bothra

-oownloaded from Faa,,

Pg. 50

CompilE

DEnginears.c m----

Mayuranand Classes
B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. if 3251 4726, 6525 7069
B-216/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 round-trip route that visits each city exactly once and then
returns to the starting city ?

optimal
and
eration
in 1960
:.~

An equivalent formulation in terms of graph theory is : Given a complete


weighted graph (where the vertices would represent the cities, the edges would
represent the roads, and the weights would be the cost or distance of that road),
find a Hamiltonian cycle with the least weight.
It can be shown that the requirement of returning to the starting city does not
change the computational complexity of the problem.

Je of a
easible
)Cedure

A related problem is the bottleneck traveling salesman problem (bottleneck


TSP) : Find a Hamiltonian cycle in a weighted graph with the minimal length of
tile longest edge.
lThe problem is of considerable practical importanc~ apart from evident
transportation and logistics areas.(__ A classic example is in printed circuit
manufacturing : scheduling of a route of the drill machine to drill holes in a PCB.
In robotic machining orctrtttfffg applications, ttie "cities" are ~arts to machme or
holes (of different sizes) to drill, and ~ostortravel" includes time for retooling
the robot( single machine job sequencing problem).

smaller

ldili'lg,
and all
tree or
;tructed
bounds

Algorithms:
task) if

The traditional lines of attack for the NP-hard 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).

Devising "suboptimal" or heuristic algorithms, i.e. algorithms that deliver


either seemingly or probably good solutions, but which could not be proved to
be optim~l.

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

Downloaded from Faa,,

DEnginears.c m

Pg.

51

Mayurariand Classes
B-403/407, Konark Darshan, Above UTI Bank, laver Road, Mulund (W), Mumbai- 80. V 3251 4726,6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281

(2) M

AOA

The a
instea
there

CHAPTER 6 : SPARSE MATRIX

8-L
B-216/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 5-Q) 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.

TERMS AND DEFINITIONS

In general, a matrix is a 2-dimensional array, together with some operations, such


as multiplication and addition, defined for the array.
For the sake of simplicity, this chapter assumes that all the matrices are n-by-n
"square" arrays : the number of rows and columns are the same. Generalizing the
ideas to work with rectangular arrays is left as an exercise.

Note:
The subscripts or indices of the elements of the matrix range from (0,0) (at the
upper left corner of the array) to (n-1, n-1) (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 zero-based 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].

MATRIX ADDITION AND MULTIPLICATION

(1) Addition :

Ho~

Addition of two matrices is very simple. ~he sum of two matrices


composed of the sums of elements of the two matrices.

intri
alga

i~

the matrix

t"fo\Ai

void mm.-.add (intA[N][N], int B[N][N], int C[N][N])

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

Algorithm is clearly O(n ).

r:omoiled bv Prof. Raiesh Bothra

-Downloaded from Faa

Pg. 52

oDEngineers.col

Corr

Mayuranand Classes
}

7 3281

8-403 I 407, Konark Darshan,Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. ir 3251 4726, 6525 7069 .
8-216/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 + +)
{

.-by-n
19 the

sum += A[i][k]

* B[k][j];

}
C[i][j]

= sum;

}
at the
-his is
;cripts
;ier to
Jld be

FASTER MATRIX MULTIPLICATION ALGORITHMS :

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 big-0 of the fastest possible general matrix multiplication
algorithm is * ***. Perhaps there are some useful and theoretically important
discoveries still to be made .

****.

. OPERATIONS ON SPARSE MATRICES


As implied earlier, there are tricks that can be used to speed . up matrix
multiplication if the matrices are known to have particular properties.
One kind of matrix that can be multiplied quickly is a sparse matrix.
A sparse matrix, like a sparse array, is a matrix where most of the elements are
the same value. In most cases, the common value is zero, but this is not
necessarily the case. In this section, we'll begin by exploring how sparse matrices
that are mostly zero can be multiplied quickly, but at the end we will see how the

Pq. 52

Downloaded from Faa

oDEngi eers.com

Pg.

53

Mayuranand Classes
8-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai - 80. if 3251 4726, 6525 7069
8-216/217 Vardhman Champers, Above UTI Bank, NrBabubhai Jagjeevandas, Sector 17, Vashi, Navi. Mumbai. if 6517 3281

BB-216/2

principles for handling these matrices can also be used to speed up operations on
other kinds of sparse matrices.

MULTIPLYING .SPARSE MATRICES

A simple-minded approach to matrix multiplication is to blindly use algorithm


again, but instead of using the ordinary array operations to access to matrix
elements, use the sparse array (or multi list) operations to access them:
void mm_mul_sa (sa_t *A, sa_t *B, sa_t *C)
{

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);

saSet (C, i , j, sum);


}
}

}
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 (non-zero) 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

void mm_mul_sa_fast (sa_t *A, sa_t *B, sa_) *C)

We'l
***:

This

int i, j, sum;

This
an e

sa_cell_t *row_p, *col_p;


for (i

= 0;

i < A-> num_rows; i++)

Ho\t\

c--- ! 1 -

...J

l.i..

iS VE

"'--L

for (j = 0; j < B -> num_cols; j++)

The1

At t
nov..

F"\'-..":-.-L

n-&..1.-. - -

---Downloaded tram Faa

Q,..

I:A

oDEngineers.co

Com

Mayuranand Classes
J69
517 3281

B-403/407, Konark Oarshan, Above UTI Bank, laver Road, Mulund (W), Mumbai- 80. if 3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank; Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281.

ons on

row_p = A - > rows [i];


col_p = B - > cols [j];
sum.= 0;
while ((row_p != NULL) && (col_p != NULL))

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

OTHER SPARSE MATRICES

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

Downloaded tram FaaDoDEngineers.co

Pg. 55

Mayuranand Classes
B-403/407, Konark Darshan, Above UTI Bank, Zaver Road; Mulund (W), Mumbai- 80. if' 3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, SeCtor 17, Vashi, Navi Mumbai. it 6517 3281

BB-216/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

Downloaded from Faa

oDEngineers.com____

Con

Mayuranand Classes
9
7 3281

8-403/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, 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)

Develop a program for merge sort algorithm.

(b)

Write note on algorithm complexity.

(c)

List and describe


implementation.

computer

(a)

Implement the algorithm for binary search using single dimensional


array as data structure.

(b)

Develop a program for carrying out indexed search using single


dimensional array as data structure. Also develop a program for
creation of indexed array for the parent array.

10

(a)

Explain binary tree and heap as a data structure.

various

data

structures

for

(b) Implement heap sort, keeping data in singly (doubly linked list.
4.

5.

6.

7.

8.

9.

Develop recursive program for :

16

(a)

Binary tree creation.

(b)

Swapping the tree.

(c)

Copying the tree.

(d)

Counting number of leaf nodes of the tree.

(a)

Explain binary tree traversals.

(b)

Develop program for binary search tree detection with the help of a
subprogram for binary search tree search.

10

(a)

\"!rite note on sparse matrix representation.

(b)

Develop an object oriented program in C++ to carry out


multiplication of two sparse matrices, keeping the matrix (data) in
doubly linked list. The resultant matrix needs to be stored in a
doubly linked list. Also print the resultant matrix In natural form.

12

(a)

Write note on expression trees and explain conversion of infix


expressions to postfix expressions using binary tree structure.

(b)

Write the algorithm for conversion of infix expression to postfix


expression.

(c)

Develop algorithm for evaluation of postfix expression.

(a)

Write notes on directed graph, undirected graph and its


representation as Adjacency list, Adjacency matrix and Edge list
representation.

(b)

Develop an object oriented program in C++ to create an Adjacency


li~t to represent a directed graph and carry out Breadth First
search.

12

(a)

Explain greedy method with the help of Knapsack problem.

(b)

Explain shortest path algorithm, (any one) and develop a program


for that method.

10

Write notes on any three of the following :

18

10.

Pg. 56

14

(a)

Branch and Bound method

(b)

NP hard problems

Downloaded tram FaaDoDEngineers.co

Pg. 57

Mayuranand Classes

B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80.
3251 4726; 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai.
6517 3281

(c)

NP complete problems

(d)

Dynamic programming

(e)

Travelling salesman problem

B-216/;

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 step-by-step (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)

Straight selection sort selecting max in each pass

(c)

Heap sort in ascending order using in place max heap

(d)

Two-way merge sort

(e)

Binary tree sort

(a) Write a program in 'C' to implement push


a stack maintained using arrays.

10

(b)

Write a program in 'C' to implement Insert I delete


operations on a circular queue maintained using arrays .

I display

10

(a)

Write a program in 'C' to implement add I remove


operations on a linked list maintained using pointers.

I display

(b)

Write a program in 'C' to implement the following operations on a


BST maintained using pointers :

4.

5.

I pop I peek operation on

2.

(i)

In-order traversal

(ii)

Pre-order traversal

(iii)

Post-order traversal .

(iv)

Search for a given element

3.

Write a program in 'C' for the following sorting methods. Also


derive the efficiency analysis (i.e. big o notation) of the same
methods for best, worst and average cases :
(a)

Simple insertion sort.

10

(b)

Quick sort using recursive or non-recursive approach.

10

(a)

Write a program in 'C' for the following binary search technique.


Also derive the efficiency analysis of the same for bestr worst and
average cases.

10

(b)

Explain representation of sparse matrices using arrays and doubly


linked lists. Also discuss the advantages and disadvantages of each.

10

6.

4.

5.

Explain the following terms for graphs with any suitable examples :
(a)

Adjacency matrix representation.

(b)

Linked list (using pointers) representation.

(c)

Path matrix calculation and transitive closure.

(d)

Depth first search.

(e)

Indexed sequential search.

(f)

Minimum cost spanning tree ..

Cr--"-"" ......

n--&

n-~--h c - .. h~.., .

--Downloaded from Faa

Pn

t;A

6.

Con

oDEngi eers.co1----

~t~;~;~::}.

: ..

.' .
~

Mayuranand Classes
69
17 3281

B-403/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 two-dimensional 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.

In the 'Josephus Problem', a group of soldiers is surrounded by the


enemy and one soldier is to be selected to ride for help. The
selection is made in the following manner. An integer n and a
soldier are selected randomly. The soldiers are arranged in a circle,
and they count off, beginning with the randomly selected soldier.
When the count reaches n, that soldier is removed from the circle,
and counting begins again with the next soldier. This process
continues until only one soldier remains, who is then the one
selected to ride for help. Write an algorithm that implements this
selection strategy, assuming that a circular linked list is used to
store the names (or numbers) of the soldiers. Write a program that
solves the Josephus problem described above.

20

4
4

4
4

4
10
10

Use . N = randomize (25, 100); the statement to generate random


numbers between 25 and 100. Also use output statements to trace
the selection process, showing the contents of the list at each
stage.

3
3
3
3.

(a)

Implement the algorithm for Hash search and discuss the algorithm
complexity.

10

{b)

Develop a program for carrying out indexed search using single


dimensional array as data structure. Also develop a program for
creation of indexed array for the parent array.

10

(a)

Explain binary tree traversals and develop recursive program for

binary tree creation and traversals.

. 10
10
10

10

.4.

5.

(b) Implement merge sort, keeping data in doubly linked list.

(a)

Develop a program for Quick sort algorithm and (discuss its


complexity in terms of big o .notation).

10

(b)

Write notes on :

10

(i)

(ii) Graph representation

6.

(a)

Sparse matrix

Develop algorithms for:

(i)

Conversion of infix expression to postfix expression.

(ii)

Evaluati~m

(b)

of postfix expression.

Develop an object oriented program in C++ to create an Adjacency


list to represent a directed graph and carry out Breadth First search.
11,...,....
...J-~- ~"----'- -!~
- ~
-~ ~ - -- - y
4""tll"ll"

--

Downloaded from

10

FaaDoDEngineers.col_
: - . - - ._1--.--.-.&..-.-J

-!.-

Mayuranand Classes
B-403/407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai ~ 80. if 3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank, Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6"517 3281

821 1
iiiiiiiiiiiiii

7.

20

Write notes on the following :


(a)

Branch and Bound method.

(b)

NP Complete problems.

(c)

Greedy method applied in Knapsack problem.

(d)

Backtracking algorithm.

6.

MAY 2005

.1.

(a)

Write a program in 'C' using array representation for a stack, to


perform the following operations :

10
7.

(i) Push a new elem.e nt onto the stack.

(ii) Pop an element from the stack.


(iii) Peek into the stack.

(b)

Write a program in 'C' using array representation for a queue, to


perform the following operations :
(i)

10

Add a new element to the queue.

(ii) Delete an element from thequeue


(iii) Display all the elements of the queue.

2.

1.

(a)

Explain static memory allocation (i.e. array based) and dynamic


memory allocation (i.e. pointer based) with suitable examples. Also
compare the advantages and disadvantages of both the methods of
memory allocation.

10

(b)

Write a program in 'C' using pointer representation for unordered


. doubly linked list (DLL) to perform the following operations :

10

(i)

Insert a new node at the beginning of the DLL.

(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)

Add a new node to the BST.

(ii) Pre-order traversal of the BST.

(iii) In-order traversal of the BST.

2.

(iv) Post-order traversal of the BST.

4.

5.

Co

(b)

Explain briefly the application of binary tree concept to the problem


of conversion of infix expressions to prefix expressions and infix
expressions to postfix expressions. Also explain briefly how you
would evaluate a simple arithmetic expression [(3 + 4) * (9 - 7)]
~epresented by an. appropriate binary tree.

10

(a)

Write an algorithm and also a program in 'C' to implement straight


selection sort selecting max in each pass.

10

(b)

Write an algorithm and also a program in 'C' to .implement heap


sort using in-place max heap.

10

(a)

Write an algorithm and also a program in 'C; to implement binary


search technique using either recursive or non-recursive approach .

10

(b)

Explain the indexed sequential search technique with the help of


suitable examples. Discuss how this technique will cope up with
new insertions into and deletions from the table of data.

10

.. . . . -

, - - , - -._ ... -

LL - -

Pn

hn

Cc

--Downloaded from Faa oDEngineers.col----

Mayuranand Classes
' 3281

8-403/407, Konark Darshan, Above UTI Bank. Zaver Road, Mulund (W), Mumbai- 80. ~ 3251 4726, 6525 7069
8-216/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

Answer any two from the following :

6.

10

(i)

Explain graph representation using adjacency matrix and how you


will arrive at path matrix from the adjacency matrix. Illustrate your
answer with a suitable example.

10

(ii)

Explain traversal methods for a graph with a suitable example;


Depth First Search (DFS) and Breadth First Search (BFS).

10

(iii)

For a well connected weighted graph, explain the concept of


Minimum Spanning Tree with a suitable example.

10

7.

10

Answer any two from the following :


(i)

Sparse matrix representation using DLL, i.e. Doubly Linked Lists.

10

(ii)

Backtracking methods and the 8-Queen's problem.

10

(iii)

Greedy method and Knapsack problem.

10

(iv)

Dynamic programming method with any suitable example.

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)

Select suitable data structure and write C


two large integersof length upto 300 digits.

10

10

10

C++ program to add

10

One approach is to treat each number as a list, each of whose


elements is a block of digits of the number. For example, the
integer 179, 534, 672, 198 might be stored with block[1] = 198,
blotk[2] = 672, block[3] = 534, block[ 4] = 179, then add the two
integers (lists) element by element, carrying from one element to
the next when necessary.

2.
10

10

A magic square is an N x N matrix in which each of the integers 1, 2,


3, N x N appears exactly once and all column sums, row sums and
diagonal sums are equal. For example, -the following is a 5 x 5 magic
square in which all the rows, columns and diagonals add up to 65.

20

Magic square
10
10
10
10

. 60

17

24

15

23

14

16

13

20

22

10

12

19

21

11

18

25

Following is the procedure for constructing an N x N magic square for


any odd integer N. Place 1 in the middle of the top row. Then after K
has been placed, move up one row and one column to the right to
place the next integer K + 1, unless one of the following occurs.

Downloaded tram Faa

aDEngineers.c

Pg. 61

Mayuranand Classes
B-403/407, Konark Darshan. Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. 2 32514726, 6525 7069
B-216/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)

If a move takes you to an already filled square or if you move out of


the square at the upper right hand corner, place K + I immediately
below it.

B-4(
B-216/21'

1.

(c:

Write C I C++ program for the creation and display of magic


square.
3.

(a)

(b)

In the Josephus Problem, a group of soldiers is surrounded by the


enemy, and one soldier is to be selected to ride for help. The
selection is made in the following manner. An integer n and a
soldier are count off, beginning with the randomly selected soldier.
When the count reaches n, that soldier is removed from the circle,
and counting begins again with the next soldier.. This process
continues until only one soldier remains, who are then the
un(fortunate) Ofle selected to ride for help. Write a C I C++
program that implements the selection strategy assuming that a
circular linked list is used to store the names of the soldiers.

10

Develop a class in C++ for the creation and manipulation of the


following . :

10

(i)

(I

Creation

(ii) Insertion of a new node


(iii) Deietion of node
(iv) Display of the list

2.

Develop a class for binary tree manipulations consists of following


functions :

4.

(i)

20

Creation

(ii) Traversals

(iii) Counting number of leaf nodes


(iv) Copying the tree
(v) Swap the tree
5.

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)

Write a note on sparse matrix representations explaining at least


four types of representation.

10

(b)

Write a note on graph -representation both directed graph and


undirected graph:.

10

(a)

Write algorithms for :

10

(i)

3.

4.

Conversion of infix expression to postfix expressio_n

(ii) Evaluation of postfix expressions


(b)

Write notes on spanning trees, spanning trees of minimum cost and


greedy algorithms.

10

5.

Compiled by Prof. Rajesh Bothra

-Downloaded from Faa

Pg. 62

oDEngineers.com

Comp

Mayuranand Classes
69
17 3281

B-403/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. if 6517 3281 .

MAY 2006

1.

(a)

In the Josephus Problem, a group of soldiers is surrounded by the


enemy, and one soldier is to be selected to ride for help. The
selection is made in the following manner. An integer n and a
soldier are count off, beginning with the randomly selected soldier.
When the count reaches n, that soldier is removed from the circle,
and counting begins again with the next soldier. This process
continues until only one soldier remains, who are then the
un(fortunate) one selected to ride for help. Write a C I C++
program that implements the selection strategy assuming that a
circular linked list is used to store the names of the soldiers.

10

(b)

Explain with examples the interrelationship of data structure and


algorithms in process of problem solving.

10

10

Also find the time complexity of the following piece of code :


maxi = 10; maxj = 10;
for (i = 7; i <=maxi; i++)
for (j = 3; j < = m a xj; j + +)

{
10

if ( i > j)
printf ("HELLO \n");
else
break;

}
2.

(a)

20

Write a program in 'C' using array representation for a stack to 10


perform the following operations/:
(i)

Push a new etement into the stack.

(ii)' Pop an element from the stack.


(iii) Display all element of the stack.
(b)

Write a program in 'C' using array representation for a queue to . 10


perform the following operations :
(i)

20

Add a new element into the queue.

(ii) Delete an element from the queue.


(iii) Display all the elements of the queue.

10

3.

10
10

Write an algorithm and also a program in 'C' to implement straight


selection sort selecting max in each pass.

10

(b)

Write an algorithm and also a program in. 'C' to implement heap


. sort using in place max heap"

10

4.

10

5.

'g. 62

(a)

Explain the following terms for graphs with any suitable example :
(a)

Adjacency matrix representation.

(b)

Linked list (using pointers) representation.

(c)

Path matrix calculation and transitive closure.

(d)

Depth first search .

(e)

Breadth first search.

(a)

Write a note on sparse matrix representation. Also develop an 10


object oriented program in C++ to carry out multiplication of the
two sparse matrices, keeping the matrix (data) in doublylinked list. ,

Downloaded from Faa

DEngineers.c

Pg. 63

Mayuranand Classes
B-403 I 407, Konark Darshan, Above UTI Bank, Zaver Road, Mulund (W), Mumbai- 80. if 3251 4726, 6525 7069
B-216/217 Vardhman Chambers, Above UTI Bank. Nr Babubhai Jagjeevandas, Sector 17, Vashi, Navi Mumbai. if 6517 3281

6.

(b)

Develop a program for carrying out indexed search using single 10


dimensional array as data structure. Also develop a program for
creation of indexed array for the parent array.

(a)

Write algorithms for :

(b)

7.

(i)

Conyersion of infix expression to postfix expression.

(ii)

Evaluation of postfix expression.

Write notes on spanning trees, spanning trees of minimum cost and


greedy algorithm.

lQ

Write short notes on any four :


(a)

Backtracking algorithms

(b)

Dynamic programming algorithms

(c)

N P hard problems

(d)

N P complete problems

(e)

Branch and Bound method

! ! !

rnmniiPrl hv Prnf

R;:~ipc::h Rnthr;:~

:.

...

Pn ,:;,4

....._Downloaded tram FaaDoDEngineers.co