33% found this document useful (3 votes)
1K views407 pages

DS Book

This document discusses data structures and algorithms. It covers topics like arrays, linked lists, stacks, queues, trees, graphs, sorting, searching, hashing and files. It includes sample programs in C language and multiple choice questions for each chapter to help students learn.

Uploaded by

Saqib Kamal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
33% found this document useful (3 votes)
1K views407 pages

DS Book

This document discusses data structures and algorithms. It covers topics like arrays, linked lists, stacks, queues, trees, graphs, sorting, searching, hashing and files. It includes sample programs in C language and multiple choice questions for each chapter to help students learn.

Uploaded by

Saqib Kamal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 407

DATA STRUCTURES AND ALGORITHM

ALGORITHMS WITH ANALYSES MULTIPLE CHOICE QUESTIONS AND ANSWERS QUESTIONS OF UNIV
ERSITIES, GATES AND SOLUTIONS
SAMPLE PROGRAMS FOR LINKED REPRESENTATION OF STACK, QUEUE AND TREES
Dr.Arup Kr.Bhaumik Santanu Haldar Subhrajit Sinha Roy

CONTENTS
Preface Acknowledgements 1. INTRODUCTION
1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 Information and Data Basic Operation of a Co
mputer Solvability of Problem and Data Structure Mathematical Modeling of Data R
epresentation of Numbers in Computer Group Data or Structured Data Algorithm and
Notations Used in The Book MCQ Chapter 1 Exercises Chapter 1
2. PRELIMINARIES
2.1 2.2 2.3 2.4 2.5 Definition of algorithm Properties of an Algorithm Algorithm
Development Life Cycle Example of some Algorithms Complexity of Algorithms (Ana
lyzing phase) 2.5.1 Asymptotic notations 2.5.2 How can we estimate the time comp
lexity in big Oh(O) notation? 2.5.3 How can we improve the complexity of algorit
hms? 2.5.4 Properties of Big Oh 2.5.5 Rate of growth of Big Oh notation Some pop
ular Mathematical Notations and Functions Algorithmic Notation MCQ Chapter 2 Exe
rcises Chapter 2
2.6 2.7 2.8 2.9
3. ARRAY 3.1 Introduction and Definition 3.2 Declaration of Array 3.3 Memory Rep
resentation of Array 3.4 Insertion in one dimentional Array 3.5 Deletion from on
e dimentional Array 3.6 Travarsing one dimentional Array 3.7 Merging two one dim
entional Array 3.8 Matrix Addition 3.9 Sparse Matrix 3.10 Polynomial Representat
ion 3.11 MCQ Chapter 3

3.12 4
Exercises Chapter 3
STRUCTURE AND POINTER 4.1 Definition of Structure 4.2 Basic of Pointer 4.3 Struc
ture and Pointer 4.4 Passing Structure to Pointer 4.5 Self Refferential Structur
e 4.6 Dynamic Memory Allocation 4.7 MCQ Chapter 4 4.8 Exercises Chapter 4
5. STRINGS 5.1 Definition 5.2 Concatenation and substrings 5.3 String operations
5.3.1 Alphabet of a string 5.3.2 String substitution 5.3.3 String homomorphism
5.3.4 String projection 5.3.5 String Right quotient 5.3.6 String Syntactic relat
ion 5.3.7 String Right cancellation 5.3.8 String Prefixes 5.4 String Topology 5.
5 String datatypes 5.6 String length 5.7 String Representations 5.8 String as Ve
ctors 5.9 String processing algorithms 5.9.1 String searching algorithms 5.9.1.1
Basic classification 5.9.1.2 Single pattern algorithms 5.9.1.3 Algorithms using
finite set of patterns 5.9.1.4 Algorithms using infinite number of patterns 5.9
.2 String manipulation algorithms or String Functions 5.9.3 String Sorting algor
ithms 5.9.4 Regular Expression Algorithms 5.9.5 Parsing a String 5.10 String Imp
lementations 5.11 MCQ Chapter 5 5.12 Exercises Chapter 5 6. STACK 6.1 Definition
6.2 Basic Operations 6.3 Implementation of stack using array 6.4 Implementation
of stack using dynamic memory allocation 6.5 Arithmetic Expressions

6.6 Converting Infix expressions to postfix notation 6.7 Converting Infix expres
sion to prefix notation 6.8 Evaluating Postfix Expression 6.9 Evaluating Prefix
Expression 6.10 Application of Stack 6.11 Reversing a string 6.12 Checking balan
ced parenthesis 6.13 Multiple Stacks 6.14 MCQ Chapter 6 6.15 Exercises Chapter 6
7. QUEUE 7.1 Definition 7.2 Implementation of queue using array 7.3 Implementat
ion of Queue using dynamic memory allocation 7.4 Limitation of linear queue 7.5
Circular Queue 7.6 Deque(Double Ended Queue) 7.7 Priority Queue 7.8 Implementati
on of queue using stacks 7.9 Application of Queue 7.10 MCQ Chapter 7 7.11 Exerci
ses Chapter 7 8. LINKED LIST Introduction Definition Advantages Disadvantages Op
erations on Linked List Types of Linked List Singly Linked List Reversing a Sing
ly Linked List Polynomial using singly linked list Advantages and disadvantages
of singly linked list Circular linked list Double linked list MCQ Chapter 8 Exer
cises Chapter 8 9. RECURSION Definition Types of recursion Linear recursion Bina
ry recursion Multiple recursion Some recursive algorithms Factorial function GCD
of two numbers

Exponential Power Fibonacci sequence Towers of Hanoi Tail of recursion Disadvant


ages of recursion Recursion Vs Iteration MCQ Chapter 9 Exercises Chapter 9 10. T
REE Definition Basic terminologies Binary tree Types of binary trees Properties
of binary trees Representation of binary tree Binary tree traversal methods Crea
tion of binary tree from preorder and inorder traversal Creation of binary tree
from postorder and inorder traversal Expression tree Binary search tree Heap Wei
ght balanced binary tree AVL Search tree / Height balanced binary tree Threaded
binary tree M-way search tree B-Tree/Balanced M-way search tree Red/Black tree M
CQ Chapter 10 Exercises Chapter 10 11. GRAPH Definition Basic Terminologies Repr
esentation of a graph Operations on a graph Traversal of a graph Breadth first s
earch Depth first search Shortest path calculation (Dijkstras algorithm) Warshalls
algorithm MCQ Chapter 11 Exercises Chapter 11 12. SORTING 12.1 Definition 12.2
The family of sorting methods 12.3 Bubble Sort 12.4 Insertion Sort

12.5 Selection Sort 12.6 Merge Sort 12.7 Quick Sort 12.8 Heap Sort 12.9 Radix So
rt 12.10 Comparison study of different sorting 12.11 MCQ Chapter 12 12.12 Exerci
se Chapter 12 13. SEARCHING 13.1 Introduction 13.2 Sequential Search 13.3 Binary
Search 13.4 MCQ Chapter 13 13.5 Exercises Chapter 13 14. HASHING 14.1 Introduct
ion 14.2 Hash Table 14.3 Hash Functions 14.4 Collision 14.5 Clustering 14.6 Coll
ision resolution Technique 14.7 Load Factor 14.8 Analysis of Open Addressing and
Chaining 14.9 MCQ Chapter 14 14.10 Exercises Chapter 14 15. FILES 15.1 Introduc
tion 15.2 Definition 15.3 File Classification 15.3.1 Non Structured file 15.3.1.
1 Text File 15.3.1.2 System File 15.3.1.2.1 Command File (.COM): 15.3.1.2.2 Exec
utable File (.EXE) 15.3.1.2.3 Dynamic Link Laboratory File(.DLL) 15.4 Structured
File 15.4.1 Sequential File 15.4.2 Index Sequential File 15.5 MCQ Chapter 15 15
.6 Exercises Chapter 15 16. Various Questions on Data Structure

Preface
The data nowadays play very important role in computation. Versatile usage of co
mputers in every spheres of life enhances handling of different kinds of data an
d its representation in computers memory. But a programmer must have clear idea ab
out requirement of data structure and algorithm for writing solution of a proble
m in computer. Otherwise, efficiency will never be achieved. Though there are se
veral books on data structure available in the market but in a particular book a
ll the topics like algorithms, analyses, equivalent programs in C language , Multi
ple Choice Questions (MCQ ) and excersies are not available. On delivering lectu
res for 10 years since in theory and lab classes in this subject we have faced m
any questions of students and their suggestions. In many occasions we have used
our intuition to make the students understanding in different topics of this sub
ject. We have incorporated all of these strategies in our book and also programs
are written in C language to encourage students to try for testing of algorithms.
The book has been written by covering syllabi of B.Tech, B.E., MCA, BCA & Bsc.
Computer sc. courses of all most all Indian and Foreign Universities. Ho.pe ever
ybody from new learner to expert programmer may get help from the book.

Acknowledgements
The most inspiaratation that all of us have received from our beloved students,
thus we must thank them at first. Secondly, Mr. S.K.Bagal and Mr. Lahiri of S. C
hand & Co.Ltd. both of them have tendered their help, courage and moral support
to write the book, all of us are very thankful to both of them. While preparatio
n of this manuscript we have received help and criticisims from our colleague Mr
. Animesh Hazra, Lecturer Computer Sc. & Engg. So we convey our thanks to Mr.Haz
ra.

Chapter 1 Introduction
1.1: Information and Data
Information: The Oxford dictionary meaning is (1) Facts or Knowledge provided or
learned. (2) Computer Data. Data: The Oxford dictionary meaning is (1) Facts or
statistics used for reference or analysis (2) The quantities, characters or sym
bols operated on by a Computer. Thus, from the definitions of the dictionary one
can assume that the terms information and data can be used interchangeably. But
in context of the computer any recorded or stored fact, which needs for process
ing by the Central Processing Unit (CPU) is called data i.e. for example Students
name, Address, Marks obtained in different subjects when recorded is called dat
a and when a program is written to find grades of students on the basis of marks
obtained in various subjects the output will appear as A, B, C etc. or First Class,
d Class etc., which are information. Moreover, if grades are recorded or stored f
or further computation then these will be termed as data also. 1.2 Basic Operati
on of a Computer Any computer has three distinct units, viz. Input/Output, Memor
y and Central Processing Unit (CPU). The input unit is used to feed data to the
computers memory and the output unit is used to show the result after computation
. The memory unit is used to store data and program. The CPU is the main unit co
mprising of two sub units viz. Control unit (CU) and the Arithmetic Logic Unit (
ALU). The CPU does following operations in steps in repeated manner: Step 1: Fet
ch an instruction from memory Step 2: Decode the instruction Step 3: Fetch the o
perands needed for the operation Step 4: Execute the instruction in ALU It is cl
ear from the steps of operations that first of all computer needs an instruction
i.e. a command (to do some operations) and then operand (or data) is required f
or completion of operation. The operations performed by a bare CPU are very basi
c such as Addition, Subtraction, Multiplication, AND, OR, NOT etc. on binary dat
a. Thus, if everything i.e. instructions and data are represented in binary then
the binary sequence is called machine code. But to work with machine code is ve
ry difficult either to write a full program or later on to debug it. To make the
understanding of machine code just easy the equivalent hexadecimal representati
on is used. Thus, for a bare CPU the data types like integers, real etc. has no
meaning, these are the descriptions of data done through high level language (HL
L) and the translator program i.e. either compiler or interpreter takes responsi
bility to convert integer, real etc. data type to binary format and vice versa.
1.3 Solvability of Problem and Data Structure
There are various types of problem framed in different aspects of life in our so
ciety e.g. computation of salary, income tax etc. for employees, debit, credit a
nalysis and budgeting of any firm, weather forecasting, designing and analyzing
structures for cars, airplane, building etc., analysis for gene etc. The quicker
solutions of these

problems ensure progress of a society. Nowadays, computers are used in every sph
ere of life to get solutions of problems in a quickest and accurate way. But com
puter needs appropriate program for each problem. Problems like computation of f
actorial of a positive integer, sorting a list of names, computation of salary o
f employees, computation of free memory blocks etc. are required different metho
ds with different data set (values) to solve each of these. Whenever a problem i
s to be solved through a computer, a program is required to develop, and in a pr
ogram data are passed through variables, where variables are used to represent m
emory references either in single location or in a group of locations to store a
tomic or group data respectively.
1.4 Mathematical Modeling of Data
In our mathematics any real value is classified into: i) ii) Integer numbers (bo
th +ve and ve) e.g. 0, 1, 2, 3, . . . etc Rational numbers: Number derived from divi
sion of two integers (x, y) such as x/y, where y 0. The number x/y is also calle
d a fraction and if the magnitude of x is less than y then the fraction is prope
r. Otherwise, if magnitude of x is greater than y then the fraction is improper
fraction. Thus, 1/2 , 5/2, 1/3, 1/7 etc. are all fractions out of which 5/2 is o
nly improper fraction. But 1/3 and 1/7 do not provide exact values since divisio
ns will never terminate. These are called periodic or recurring fractions. In ma
thematics value of 1/3 is written as 0.3, which represents 0.333333333 nd vlue
of 1/7 is written s 0.1428571, which represents 0.14285711428571 . iii) Irrtion
l Numbers: These re the numbers obtined from non-rtionl roots of lgebric e
qutions such s 2, 3, 5 etc. These numbers cnnot be expressed either s terminti
ng deciml or  periodic deciml. These re represented geometriclly by points,
nmely the gps between rtionl points on  line.
1.5 Representtion of Numbers in Computer
Almost ll Compilers / Interpreters written for high level lnguges e.g. FORTRA
N, C, COBOL, PASCAL etc. llow dt to be declred in following types: A. Numeri
cl (i) Integer: generlly two bytes i.e. 16 bits re considered to represent bo
th negtive nd positive integers. With 16 bits or two bytes deciml integers, n
umbers from -32768 to +32767 only cn be represented. Where for representtion o
f ve numbers 2s complement nottion is used. Since in 2s complement nottion -32768
is 1000 0000 0000 0000 & +32767 is 0111 1111 1111 1111. However, in cse of onl
y positive numbers the rnge of deciml numbers 0 65535 is represented. Therefor
e it is observed tht  very smll deciml vlue cn be represented by 16 bits o
r two bytes of dt. But in our environment often we need lrge vlues to repres
ent physicl quntities such s net sset vlue of  smll compny 10,00,000,000
/- (Rs.10 Crore), popultion of ny country 100,00,000,000 ( 100 Crore) etc. Thu
s further grouping of bytes re required to represent lrge numbers. The simple
integers re clled primitive dt types. Almost ll high level lnguges provid
e dditionl dt types to ccommodte lrge vlues in computers. For exmple, w
hen 4 bytes re grouped, the rnge of deciml vlues -2,147,483,648 to 2,147,483
,647 re

represented . In generl the following formul is used to estblish reltionship


s between binry numbers nd the equivlent deciml integers. -2n-1 +1 N 2n-1 -1
, Where n = no. of bits, N= deciml integers. Negtive numbers re represented
by 2s complement nottion. In C-lnguge the following dt types re used to rep
resent integers. Rnge Bytes Represents -32768 - 32767 2 Whole numbers 0 - 65535
2 -do-2,147,438,648 4 -do2,147,438,647 Unsigned long 0 - 429,496,7295 4 -doIn h
igh level lnguges there is nother dt type vilble to represent frctionl
deciml numbers, which is clled flot in C Lnguge nd Rel in FORTRAN. But in C
lnguge to ccommodte more deciml digits double nd long double types re ls
o used, which is described below: Type int Unsigned int long
Type
Rnge From To -38 Flot 3.4 x 10 - 3.4 x 10-38 -308 double 1.7 x 10 1.7 x 10-308
long double 3.4 x 10-4932 3.4 x 10-4932
Bytes Represents 4 8 10 Frctionl numbers -do-doB.Chrcter Single chrcters e.g. letters, digits, punctution symbols etc. re
represented by chrcter dt type in C lnguge the keyword chr is used to declr
e chrcter dt type. Either ASCII or EBCDIC formt is used for depicting  ch
rcter nd one byte of spce occupied in memory for storing the sme. The ASCII
formt hs been used in C lnguge to describe chrcter dt type nd if nybody
wnts to write  in computer, ctully the binry sequence 10010111, equivlent to
ASCII vlue 97 is stored in memory.
1.6 Group Dt or Structured Dt
The most rigorous usge of computers hppen in the res of bnking, insurnce,
helth, university etc. where dt re generlly represented in the form of reco
rd, which represents  group of moleculr or elementl informtion. As for exmp
le  record of  registered student of ny university looks like: 103000532 Mnm
ohn Sing B.Tech CSE 2007
Where the first element represents Registrtion number, the second element is n
me, the third one is the course of study, fourth one is the subject nd the lst
one is the yer of registrtion. All the elements together comprise

 record of  registered student nd crry meningful informtion. But no single


(primitive) dt types vilble in ny HLL to represent the entire record in c
omputer. However, ll third genertion lnguges hve provision of declrtion o
f record to support different dt types. But do not llow populte dt in file
with different structues, e.g. COBOL lnguge llows three kinds of file struct
ure like Sequentil, Rndom nd Index Sequentil. On the contrry the C Lngu
ge does not llow Rndom nd Index Sequentil file structure in generl to popul
te dt, specil progrms re required for these files.
1.7 Algorithm nd Nottions Used in The Book
We hve used C Lnguge nd its nottion in this book for writing lgorithms,
but the full syntxes of the lnguge hve not been considered. Thus, one cn c
onvert lgorithms to equivlent progrms very esily just by minting syntxes
only. Moreover, very simple conventions hve been followed to nme vribles or
identifiers in our progrm e.g. if the vribles strt with i it represents inte
gers dt type etc. ---------------------write for others. The book hs been div
ided into --- nos of chpters, where in chpter-1, following topis re covered -------we hve provided questions nd solutions of these, where questions re co
llected from different Universities to provide guide line for preprtion of dif
ferent exmintions.
1.8 MCQ Chpter 1
1. The most widely used method for interpreting bit setting s non-negtive inte
ger is ()Binry number system (b)BCD system (c)ASCII system (d)None of the bov
e 2. Any string of bits of length n represents  unique non-negtive integer bet
ween () 0 nd 2n-1-1 (b) 0 nd 2n-1 (c) 1 nd 2n-1 (d) None of the bove 3. Wit
h 1 s complement method, the rnge of the numbers tht cn be represented using
n bits is : ()  1 followed by using n - 1 zeroes to  0 followed by n - 1 one
s (b)  0 followed by using n - 1 ones to  1 followed by n - 1 zeroes (c) 2n-11 to 2n-1-1 (d) None of the bove. 4. Using 2s complement method, the rnge of
the numbers tht cn be represented using n bits is : ()  1 followed by using
n - 1 zeroes to  0 followed by n - 1 ones (b)  0 followed by using n - 1 ones
to  1 followed by n - 1 zeroes (c) 2n-1-1 to 2n-1-1 (d) None of the bove. 5. K
ey concept for representing  rel number is  mntiss times () 10 rised to 
n exponent (b) 2 rised to n exponent (c) bse rised to n exponent (d) None o
f the bove.

6. The set of ntive dt types tht  prticulr computer cn support is determ
ined by : () type of hrdwre compny (b) wht functions hve been wired into h
rdwre (c) wht softwre support is required (d) None of these. 7. While consid
ering dt structure implementtion, the fctor(s) under considertion is (re)
: () time (b) time nd spce (c) time, spce nd processor (d) None of these. 8
. Which is not true ? () Abstrct dt type is the useful tool for specifying t
he logicl properties of the dt type (b) While defining n bstrct dt type
s  mthemticl concept, the spce nd efficiency is not of mjor concern (c)
Every bstrct dt type cn be implemented using ny progrmming lnguge (d) N
one of these. 9. The number of 1s in the binry representtion of 3 * 4096 + IS
* 256 + 5 * 16 + 3 re () 8 (b) 9 (GATE-1995) (c) 10 (d) 12. 10. Consider the f
ollowing floting point representtion 31 24 23 Exponent Mntiss (GATE- 1996) 0
The exponent is in 2 s complement representtion nd mntiss is in the sign m
gnitude representtion. The rnge of the mgnitude of .the normlized numbers in
this representtion is () 0 to 1 (b) 0.5 to 1 -23 (c) 2 to 0.5 (d) 0.5 to (1-2
-23). 11. The octl representtion of n integer is 3428. If this were to be tre
ted s n eight bit integer, its deciml equivlent is (GATE-1998) () 226 (b)
-98 (c) 76 (d) -30 12. Zero hs two representtions in: () Sign mgnitude (c) A
ll of the bove (GATE-1999) (b) 2s complement (d) None of the bove.
13. Consider the vlues A = 2.0 x 1030, B = - 2.0 x 1030, C = 1.0, nd the seque
nce (GATE-2000) X := A + B Y := A + C X := X + C Y:= Y + B executed on  compute
r where floting point numbers re represented with 32 bits. The vlues for X n
d Y will be

() X = 1.0, Y = 1.0 (b) X = 1.0, Y = 0.0 (c) X = 0.0, Y = 1.0 (d) X = 0.0, Y =
0.0 14. The number 43 in 2 s complement representtion is () 01010101 (b) 1101
0101 (d) 10101011 (c) 00101011 15. Which of the following is (re) exmple(s) of
dt bstrction? () List of student informtion (b) File of employee records
(c) Bnk ccount dtbse (d) All of the bove. 16. Dt structure mens () The
seprtion of the representtion of dt from the pplictions tht use the dt
 t  logicl level (b)the logicl picture of  dt type, plus the specificti
ons of the opertions required to crete nd mnipulte objects of this dt typ
e (c) collection of dt elements whose orgniztion is chrcterized by ccess
ing opertions tht re used to store nd retrieve the individul dt elements
(d) None of these. 17. Abstrct Dt Type mens tht () The seprtion of the r
epresenttion of dt from the pplictions tht use the dt t  logicl level
(b) The logicl picture of  dt type, plus the specifictions of the opertio
ns required to crete nd mnipulte objects of this dt type (c) A collection
of dt elements whose orgniztion is chrcterized by ccessing opertions th
t re used to store nd retrieve the individul dt elements (d) None of these.
18. Why is writing esily modifible code importnt? ) Esily modifible code
generlly hs  quicker run time. b) Most rel world progrms require chnge t
some time. c) Most text editors mke it esy to modify code. d) Severl people m
y be writing the sme function t the sme time. 19. Which phse of the softwr
e life-cycle is usully the most expensive? ) Anlysis nd specifiction of the
tsk b) Design c) Implementtion d) Mintennce nd evolution 20. Wht will hp
pen if  function is executed nd the precondition for the function is not met?
) An error messge will be printed. b) The progrm will loop indefinitely. c) T
he system will crsh. d) Any of the bove results could hppen. 21. If the preco
ndition fils, it is  good ide to write  useful error messge nd then hlt t
he progrm. Why is the progrm hlted? ) Most operting systems forbid continu
tion. b) The function is no longer gurnteed to mke the postcondition true. c)
The functions memory requires hve become exponentil (or worse). d) The funct
ions running time hs become exponentil (or worse).

22.
23.
24.
25.
26.
27.
Which of these is used to stop the progrm execution when  precondition is not
met. ) ssert(); b) exit(); c) return(); d) void(); Which of these sttements w
ill lwys cuse  progrm to hlt? (x is n int vrible). ) ssert(10 > 0); b
) ssert(10 < 0); c) ssert(x < 0); d) None of the bove will lwys cuse  pro
grm to hlt. Wht does  run-time nlysis usully count? ) The number of rit
hmetic nd other opertions required for the progrm to run b) The number of meg
bytes required for the progrm to run c) The number of seconds required for the
progrm to run d) The number of seconds plus the number of megbytes e) The num
ber of seconds times the number of megbytes Why is it importnt to test boundr
y vlues when testing progrms? ) Clculting by hnd, its esy to find the ri
ght nswers for boundry vlues. b) Debuggers re esier to use when testing bou
ndry vlues. c) In prctice,  lrge proportion of errors rise from boundry v
lues. d) The correct execution of  function on ll boundry vlues proves  fu
nction is correct. How my boundry vlues for  function be found? ) Pick vlu
es tht re one step wy from different behvior. b) Pick vlues tht mke the
precondition equl to the postcondition. c) Pick vlues where the precondition i
s flse. d) Pick vlues where the postcondition is flse. Which softwre tool wi
ll best help you determine whether your test cses re fully exercising your cod
e? ) Compiler b) Debugger c) Mke d) Pine e) Profiler 28. A text is mde up of
the chrcters , b, c , d, e ech occurring with the probbility .12, .4, .15,
.08 nd .25 respectively. The optiml coding technique will hve the verge len
gth of () 2.15 (b) 3.01 (c) 2.3 (d) 1.78 29. In the previous question, which of
the following chrcters will hve codes of length 3? () Only c (b) Only b (c)
bnd c (d) Only d 30. Which of the following bstrct dt types cn be used to
represent  mny to mny reltion? () Tree (b) Plex (c) Grph (d) Queue 31. Th
e principle of loclity justifies the use of () interrupts (b) DMA (c) polling
(d) cche memory
32. Unrestricted use of goto is hrmful, becuse it () mkes debugging difficul
t (b) increses the running time of progrms (c) increses memory requirement 9f
progrms (d) results in the compiler generting longer mchine code

33. The min() function is lwys () clled function (b)  clling function (c
) recursive function (d) used t the end of the progrm (e) None of these. 34. T
he first digit of  deciml constnt must be () zero (b)  non-zero number (e)
 negtive number (d) n integer (e) None of these. 35. Floting point numbers 
re used insted of integers to () permit the use of deciml points in numbers (
b) void being too specific bout wht vlue  number hs (c) concel the true v
lue of the numbers (d) All of the bove (e) None of these. 36. An expression (
) is  collection of dt objects nd opertors tht cn be evluted to  singl
e vlue (b) is  nme tht substitutes for  sequence of chrcters (c) cuses t
he computer to crry out some ction (d) All of the bove (e) None of these. 37.
Consider the following rithmetic expression 2 * x / (3 * y) Suppose x nd y r
e floting-point vribles tht hve been ssigned the vlues x = 8.8 nd y = 3.
5. Wht would be the vlue of the expression? ()1.61373 (b) 20.53333 (c)1.67619
(d) None of these (e) 2.51429 38. The sttement (i = (j = 4) + (k = 9): () ss
igns  vlue 13 to i (b) ssigns  vlue 4 to i (c) gives n error messge (d) 
ssigns  vlue 7 to i (e) None of these. 39. If p nd q re ssigned the vlues
2 nd 3 respectively then the sttement p = q++ () gives n error messge (b) 
ssigns  vlue 4 to p (c) ssigns  vlue 3 to p (d) ssigns  vlue 5 to p (e)
None of these. 40. If the vribles i,j nd k re ssigned the vlues 5, 3 nd 2
respectively, then the expression i=j+(k++=6)+7): () gives n error messge (b
) ssigns  vlue 16 to i (c) ssigns vlue 18 to i (d) ssigns  vlue 19 to
i (e) None of these.

41. Which of the following is not  progrmming control structure? () Repetitio
n (b) selection (c) Sequency (d) Sorting. 42. Externl documenttion includes (
)  printout of the progrms code (b) flowchrts (c) IPO chrts (d) pseudocode
(e) All of the bove. 43. Errors in  progrm re clled () ccidents (b) nnoy
nces (c) bugs(d) mistkes (e) typing errors. 44. Typing the instruction grosspy
= hoursWorked hourlypy is n exmple of () n entry error (b)  function error
(c)  logic error (d)  syntx error. 45. The step-by-step instructions tht so
lve  problem re clled () n lgorithm (b)  list (c)  pln (d)  sequentil
structure. 46. The set of instructions for how to tie  bow is n exmple of th
e structure () control (b) repetition (c) selection (d) sequence (e) switching.
47. Which of the following control structures is used in every progrm? () Rep
etition (b) Selection (c) Sequence (d) Switching. 48. The instruction "If its r
ining outside, then tke n umbrell to work" is n exmple of the structure (
) control (b) Repettion (c) selection (e) switching. 49. The recipe instruction
"Bet until smooth" is n exmple of the structure () control (b) repetition (
c) selection (d) sequence (e) switching. 50. Sending  copy of dt to  progrm
module is clled () pssing  vlue (b) mking  reference (c) recursion (d) s
etting  condition. 51. Pying ttention to the importnt properties while ignor
ing inessentil detils is known s. () selectiveness (b) polymorphism

(c) bstrction (d) summrizing. 52. A progrm tht predicts the exct sequence
in which events will tke plce is sid to be () compiled (b) interpreted (c) p
rocedurl (d) object-oriented. 53. Using  sttement t the wrong time or with 
n inpproprite object cretes  () logicl error (b) syntx error (c) compiler
error (d) lnguge error. 54. A trnsltor tht notes whether you hve used  l
nguge correctly my be clled  () thesurus (c) coder (b) compiler (d) decod
er.
Solutions:
1.  16. c 31. d 46. d 2. d 17. b 32.  47. c 3.  18. b 33. b 48. c 4.  19. d
34. b 49. b 5. c 20. d 35. b 50.  6. b 21. 36.  51. d 7. c 22. b 37. b 52. c 8
. c 23. d 38.  53.  9. c 24.  39. c 54. b 10. d 25. d 40.  11. d 26. 41. c 1
2.  27. b 42.  13. d 28.  43. c 14. c 29.  44. c 15.d 30. b/c 45. 
1.10 Exercise Chpter 1 1. Describe one good method for precisely specifying wh
t  function must do, without indicting how the function ccomplishes its work.
Provide n exmple, using  smll function. 2. Wht is  precondition? Wht is
 post-condition? 3. Its recommended tht the precondition be checked t the st
rt of  function. Whts  good pproch if  function discovers tht its preco
ndition is not true? 4. Is it lwys possible for  function to check tht its p
recondition is true? 5. Suppose tht you ccidentlly cll  correctly implement
ed function, but the precondition is flse. Is the function gurnteed to hlt w
ith  nice messge? Is the function llowed to erse everything on your hrd dri
ve? 6. Write the first few lines of this function so tht it uses the ssert fc
ility to check its precondition:
void exm(int i) // Precondition: i is not equl to 42. ...
7. Give  concise formul tht gives the pproximte number of digits in  posit
ive integer. The integer is written in bse 10. 8. Why is the order of n lgori
thm generlly more importnt thn the speed of the processor? 9. With bout thre
e or four sentences, explin the bsic fetures of your debugger nd how they he
lp you find bugs.
Chpter - 2

PRELIMINARIES
2.1 Definition of lgorithm
An lgorithm is  set of steps to solve  prticulr problem. When we write the
different steps for the preprtion of  cup of te or coffee then it is lso n
lgorithm. The word lgorithm is  Persin term derived from the nme of  Pers
in uthor nd gret mthemticin Abu Abd Allh Jfr Mohmmd ibn Musb l Khow
rizmi. He ws born on 780 A.D. in Bghdd. He worked on lgebr, geometry nd s
tronomy.
2.2
Properties of n Algorithm
Properties of n lgorithm include the following criteri: 1) Input: An lgorith
m should hve some inputs. Exmple: If we wnt to write n lgorithm to check 
given number is odd or even, we cn tke the number s its input. 2) Output: At
lest one output should be returned by the lgorithm fter the completion of the
specific tsk bsed on the input(s) given. Exmple: If we wnt to write n lgo
rithm to check  given number is odd or even, we cn return 0 indicting tht th
e number is odd nd 1 indicting the number is even. 3) Definiteness: Every stt
ement of the lgorithm should be cler nd unmbiguous. Exmple: If we write  s
ttement like iResult = iNumber % x or y, then this is not cler tht wht operti
on should be done. Tht sttement should be either iResult = iNumber % x or iResult
= iNumber % y. 4) Finiteness: No infinite loop should be llowed in n lgorithm
. Exmple: while(1<2) { iNumber = iNumber/2; } This type of loop should not be 
llowed in the lgorithm s it leds n infinite loop (becuse 1 is lwys less t
hn 2). 5) Effectiveness: Writing n lgorithm is  priori process of ctul imp
lementtion of the lgorithm. So,  person should do nlysis of lgorithm in fi
nite mount of time with pen nd pper to judge the performnce for giving the f
inl version of the lgorithm.
2.3
Algorithm Development Life Cycle
The life cycles of n lgorithm includes the following phses: 1) Design Phse:
Some of the techniques used in the design phse of n lgorithm re (i) Brute-Fo
rce Method (ii) Divide-Conquer Method (iii) Greedy Method (iv) Dynmic Progrmmi
ng (v) Bcktrcking 2) Writing Phse: Bsiclly lgorithm is written in  modul
r pproch. Actully  function written to solve  prticulr problem is itself
n lgorithm. To mke cler ech nd every step in the lgorithm, write comments
wherever necessry.

3) Testing Phse: After writing n lgorithm, it is necessry to check tht the


lgorithm gives correct result for every vlid input. 4) Anlyzing Phse: Suppos
e for  problem P, ten correct lgorithms re designed. Now which one is to be c
hosen tht depends on the performnce of them. Minly this performnce is judged
bsed on how much time nd spce the lgorithm tkes. Tht is fter testing ph
se of n lgorithm it is required to nlyze the time complexity nd spce compl
exity of it. In section 2.5 this is discussed in detils.
2.4
Exmple of some Algorithms
Exmple 1: Write n lgorithm to find the sum of two integer numbers. Inputs : T
wo numbers. Formul: sum of two numbers is sum = number1 + number2; input two nu
mbers in number1 & number2 vribles nd dd these two by ddition opertion nd
put the result in third vrible sum. Output : Sum of these two input numbers.
1. 2. 3. 4. 5. 6. 7. 8. Algorithm fnSum(iNumber1,iNumber2) // Purpose : This lg
orithm finds the summtion of two numbers. // Inputs : Two numbers re iNumber1
nd iNumber2. // Output : iSum = Sum of iNumber1 nd iNumber2.; the vribles r
e lbled with i s prefixed becuse //integer numbers re considered. { iSum = iNu
mber1 + iNumber2; //Find the summtion. return(iSum); //Return the vlue. }//End
of Algorithm
Exmple 2: Write n lgorithm to find the roots of  qudrtic eqution Ax2 + Bx
+ C = 0. Inputs: Vlues of the coefficients A, B nd C. Formul: X = (-B + (B^2
4*A*C)) / 2 * A nd X = (-B - (B^2 4*A*C)) / 2 * A Output: Roots for rel cses 
nd for imginry roots, output is Imginry Root 1. Algorithm fnQudrticEqution
(fA,fB,fC) 2. // Purpose : This lgorithms computes the roots of  qudrtic equ
tion. 3. // Input : fA,fB nd fC re the vribles to hold vlues of the coeffi
cients A, B nd C respectively. 4. // fA, fB nd fC re rel or flot vribles,
nd to represent flot vribles f is used s prefix. 5. // Output : Roots for re
l cses for imginry roots, output is Imginry Root 6. { 7. fY = fB2 4*fA*fC;
8. if(fY>0) //If two different roots exist. 9. { 10. fX1 = (-fB + sqrt(fY))/2*fA
; //Compute the first root. 11. fX2 = (-fB sqrt(fY))/2*fA; //Compute the second
root. 12. print(fX1,fX2); //Print the clculted vlues. 13. } 14. elseif(fY=0)
//If only one root exists. 15. { 16. fX=-fB/2*fA; //Compute the only root. 17. p
rint(fX); //Print the clculted vlue of the only root. 18. } 19. else //If no
rel solution exists. 20. print(Imginry Root); 21. }//End of Algorithm

Exmple 3: Write n lgorithm to find the lrgest element from  non-empty rry
. Inputs: Totl number of element nd the rry. Formul: The logic; ssume init
illy first element is the lrgest one. Check rest n-1 elements of the rry wit
h the first one one by one nd if ny one is found lrger the first updte the f
irst the current lrger nd so Output: The lrgest element. 1. Algorithm fnFindL
rgestElement(iN, rrDt[]) 2. // Purpose : This lgorithms find the lrgest el
ement from  non-empty rry. 3. // Input : iN is totl number of elements nd 
rrDt[] is the rry . 4. // Output : iLrgest which contins the lrgest eleme
nt. 5. { 6. iLrgest = rrDt[0]; //Assume initilly first element is the lrge
st one. 7. for (iCounter = 1;iCounter<n;iCounter++) //Check rest n-1 elements of
the rry. 8. if(iLrgest<rrDt[iCounter]) 9. iLrgest = rrDt[iCounter]; 1
0. return(iLrgest); //Return the vlue of iLrgest. 11. }//End of Algorithm Ex
mple 4: Write n lgorithm to find the fctoril vlue of  given element. Input
s: The given element. Formul: N! = 1.2.3N Output: The clculted fctoril vlue
. 1. Algorithm fnFctoril(iNumber) 2. // Purpose : This lgorithm finds the fc
toril vlue of  given number. 3. // Input : iNumber is the required number. 4.
// Output : iFctoril which is fctoril of iNumber. 5. { 6. iFctoril = 1; 7
. for(iCounter = 2;iCounter<=iNumber;iCounter++) 8. iFctoril = iFctoril*iCou
nter; 9. return(iFctoril); 10. }//End of Algorithm
2.5
Complexity of Algorithms(Anlyzing phse):
Generlly the complexity of n lgorithm is mesured in two phses. When one me
sures the complexity of n lgorithm by pen nd pper, he/she cn only predict t
he complexity which gives n ide of how much time or spce this lgorithm tkes
to finish its execution. This phse is clled the priory nlysis. After implem
enting the lgorithm in computer, we get the ctul time nd spce. This phse o
f nlyzing the lgorithm is clled the posteriori nlysis. Complexity of n l
gorithm cn be of two types: (1) Time complexity: The nlysis of lgorithm for
the prediction of computtion time for execution of ech nd every instruction i
n the lgorithm is clled the time complexity of the lgorithm. (2) Spce Comple
xity: The nlysis of lgorithm for prediction of memory requirement to run the
lgorithm is clled the spce complexity of the lgorithm. 2.5.1 Asymptotic not
tions There re some nottions to determine the complexity of n lgorithm in pr
iory nlysis. The term Asymptote mens  line whose distnce to  given curve i
s tends to zero. An symptote my or my not intersect its ssocited curve. The
nottions re s follows:

Big Oh (O) nottion: The function f(n) = O(g(n)) (red s f of n is big Oh of g


of n) iff f(n) c*g(n) for ll n, n n0 where c nd n0 re positive constnts. The
function g(n) indictes the upper bound of f(n) nd so g(n) should be s smll
s possible for which the sttement f(n) = O(g(n)) is true. Exmple: Suppose Now
we cn write f(n) f(n) = 2n3 + 3n2 + n + 10 = 2n3 + 3n2 + n + 10 for ll n 2
5n3 i.e. here c = 5,n0 = 2 nd g(n) = n3.
Hence we cn write f(n) = O(g(n)) = O(n3) See here the sttements f(n) = O(n4) o
r f(n) = O(n5) nd so on re lso true. But we should not write so becuse the v
lues of g(n) for the sttements re not s smll s possible for which the stt
ement f(n) = (g(n)) is true. c*g(n) f(n) Time i
n0 n (Problem Size) Figure 2.1: Upper Bound of n lgorithm (Big Oh (O) nottion
) Omeg () nottion: The function f(n) = (g(n)) (red s f of n is omeg of g of n
) iff f(n) c*g(n) for ll n, n n0 where c nd n0 re positive constnts. The fun
ction g(n) is only  lower bound of f(n) nd so g(n) should be s lrge s possi
ble for which the sttement f(n) = (g(n)) is true. = 2n3 + 3n2 + n + 10 = 2n3 + 3
n2 + n + 10 2n3 for ll n 1 3 i.e. here c = 2,n0 = 1 nd g(n) = n . Exmple: Sup
pose Now we cn write f(n) f(n) Hence we cn write f(n) = (g(n)) = (n3) Observe th
t, for the bove exmple the sttements f(n) = (n2) or f(n) = (n) or f(n) = (1) r
e lso correct. But we should not write so becuse the vlues of g(n) for the st
tements re not s lrge s possible for which the sttement f(n) = (g(n)) is tr
ue.

f(n) c*g(n) Time


n0 n(Problem Size) Figure 2.2: Lower Bound of n lgorithm (Omeg () nottion) Th
et () nottion: The function f(n) = (g(n)) (red s f of n is thet of g of n) if
f c 1*g(n) f(n) c2*g(n) for ll n, n n0 where c1,c2 nd n0 re positive constnt
s. The function g(n) is  tight bound of f(n) becuse g(n) is both upper nd low
er bound on f(n). Exmple: Suppose Now we cn write, f(n) = 2n3 + 3n2 + n + 10 3
5n 2n3 + 3n2 + n + 10 2n3 for ll n 2 i.e. here c1 = 5, c2 = 2, n0 = 2 nd g(n)
= n3. Hence we cn write f(n) = (g(n)) = (n3) c1*g(n) f(n) c2*g(n) Time
n0 n (Problem Size) Figure 2.3: Tight bound of n lgorithm (Thet () nottion) L
ittle oh (o) nottion: The function f(n) =o(g(n)) (red s f of n is little oh o
f g of n) iff f(n) lim n g(n) =0

f(n) = 2n3 + 3n2 + n + 10 limn (2n3 + 3n2 + n + 10)/n4 = limn (2/n + 3/n2 + 1/n3 + 1
0/n4) =0 i.e. here g(n) = n4. Hence we cn write f(n) = o(g(n)) = o(n4) Exmple:
Suppose Now we cn write Little omeg () notation: The function f(n) = (g(n)) (re
ad as f of n is little omega of g of n) iff g(n) lim =0 n f(n) Exmple: Suppose f(n)
= 2n3 + 3n2 Now we cn write limn n/(2n3 + 3n2) = limn (1/2n2 + 1/3n) =0 i.e. here
g(n) = n. Hence we cn write f(n) = (g(n)) = (n) During the execution of a program
, estimating the upper bound of time (CPU time) that the program takes to finish
its execution is the main factor. If it takes the less time than our estimation
then the CPU performance ill be improved. But if it takes more time than our c
alculation then it ill cause the degradation of CPU performance. No e kno e
ll that the Big Oh (O) notation gives the upper bound estimation and thats hy e
ill discuss about big Oh (O) notation in details through out the book. 2.5.2 H
o can e estimate the time complexity in big Oh(O) notation? Assumptions: 1) Al
l the statements take equal time for execution. 2) Each statement takes unit tim
e to execute. Example 1: Calculate the time complexity for the folloing algorit
hm. 1. Algorithm fnSearch(arrData[],iN,iItem) 2. // Purpose : This algorithm sea
rches a particular element in an array. 3. // Input : arrData[] is an array of i
N(= n) integers. Search for the element iItem in the array. 4. // Output : The a
lgorithm returns 1 for successful search and 0 for an unsuccessful search. 5. {
6. for(iCounter = 0;iCounter<iN;iCounter++) 7. if(arrData[iCounter]==iItem) 8. r
eturn 1; //Successful search. 9. return 0; //Unsuccessful search. 10. }//End of
Algorithm Solution: Line 7 and line 8 take unit time to execute and line 6 takes
n time to execute. So lines 6, 7 and 8 take 2n time for execution. Line 9 takes
unit time to execute. Therefore, f(n) = TL6 * (TL7 + TL8) + TL9 = n(1+1) + 1 =
2n + 1 3n for all n 1 No from the definition of big Oh(O) notation e can rite
f(n) = O(n) Example 2: Comment on the time complexity of the folloing algorithm
. 1. Algorithm fnMatrixMultiplication(arrA,arrB,iN) 2. // arrA and arrB are to
matrix each of the order nXn. Value of the variable iN = n.

3. { 4. for(iX=0;iX<iN;iX++) 5. { 6. for(iY=0;iY<iN;iY++) 7. { 8. arrC[iX][iY]=0


; //arrC is the resultant matrix 9. for(iZ=0;iZ<iN;iZ++) 10. arrC[iX][iY] = arrC
[iX][iY] + arrA[iX][iZ]*arrB[iZ][iY]; 11. } 12. } 13. //Print the contents of th
e resultant matrix. 14. for(iX=0;iX<iN;iX++ 15. for(iY=0;iY<iN;iY++) 16. print(a
rrC[iX][iY]); 17. }//End of Algorithm Solution: For calculating the time complex
ity of the above algorithm e can divide it into to segments. Segment 1 is a ne
sted for loop containing line 4 to line12 and segment 2 is a nested for loop con
taining line14 to line 16. In segment 1: Line 10 takes unit time for execution.
Line 9 takes n times for execution. Line 8 takes unit time for execution. Line 6
takes n times for execution. Line 4 takes n times for execution. No segment 1
takes T1 = TL4 * (TL6 * (TL8 + TL9 * TL10)) = n*(n*(1+ n*1) 2 3 =n +n In Segment
2: Line 16 takes unit time to execute. Line 15 takes n times to execute. Line 1
4 takes n times to execute. So segment 2 takes T2 = TL14 * TL15 * TL16 =n*n*1 Th
erefore the total time f(n) = T1 + T2 = (n + n ) + n
3 2 2 3 2 3
= n + 2n 3n
for all n 1
3

No from the definition of the big Oh (O) notation e can conclude f(n) = O(n ).
Example 3: Calculate the time complexity for the folloing recurrence relation.
T(n) = 2T(n-1) + 1 for n > 1 =1 for n = 1 Solution: T(n) = 2T(n-1) + 1 = 2[2T(n
-2) + 1] + 1 2 = 2 T(n-2) + 2 + 1 = . = . k = 2 T(n-k) + . + 2 + 1 [up to k
n-1
+ ..+ 2 + 2
1
0
[Let n-k = 1. So T(1) = 1]

= (2 1)/(2-1) =2 12
n n
n
for all n 1
n

Therefore, from the definition of the big Oh (O) notation e can conclude f(n) =
O(2 ). Example 4: Calculate the time complexity for the folloing recurrence re
lation. T(n) = 2T(n/2) + n for n > 1 =1 for n = 1 Solution: T(n) = 2T(n/2) + n 2
= 2[2T(n/2 ) + n/2] + n = 2 T(n/2 ) + 2n = = k k = 2 T(n/2 ) + kn [u
Let 2 = n. So, k = logn] = n + nlogn [ as T(1) = 1] 2nlogn for all n 2 Hence, f
rom the definition of the big Oh (O) notation e can rite f(n) = O(nlogn). 2.5.
3 Ho can e improve the complexity of algorithms? Example 1: Write an algorithm
to calculate the sum of first n natural numbers. Procedure 1: Inputs: iNumber 
hich contains the value of n Output: iSum hich contains the calculated sum 1. A
lgorithm Summation(iNumber) 2. { 3. iSum = 1; 4. for(iCounter = 2;iCounteriNumber
;iCounter++) 5. iSum = iSum + iCounter; 6. return(iSum); 7. }//End of Algorithm
Complexity: Line 3 takes unit time for execution. Line 4 takes n times for execu
tion. Line 5 takes unit time for execution. Line 6 takes unit time for execution
. Therefore f(n) = TL3 + TL4*TL5 + TL6 = 1 + n*1 + 1 = n + 2 2n for all n 2 So,
f(n) = O(n) Procedure 2: The problem is S = 1+2+3+4+. + n = n(n+1)/2 No e can dir
ectly compute the value of S ithout using any loop. Inputs: iNumber hich conta
ins the value of n Output: iSum hich contains the calculated sum 1. Algo Summat
ion(iNumber) 2. { 3. iSum = iNumber*(iNumber + 1)/2;
k 2 2

4.
return(iSum); 5. }//End of Algo Complexity: Line 3 takes unit time. Line 4 takes
unit time. Therefore, f(n) = TL3 + TL4 =2 So, f(n) = O(1) i.e. the algorithm of
procedure 2 takes constant time and obviously the second approach is better tha
n the first one in respect of time complexity. Example 2: Write an algorithm to
compute the value of x here n is integral poer of 2. Procedure 1: Inputs: iX =
the value of x and iN = the value of n. Output: iResult = the calculated result
. 1. Algorithm Poer(iX,iN) 2. { 3. iResult = 1; 4. for(iCounter = 1;iCounteriN;i
Counter++) 5. iResult = iResult*iX; 6. return(iResult); 7. }//End of Algo Comple
xity: Line 3 takes unit time for execution. Line 4 takes n times for execution.
Line 5 takes unit time for execution. Line 6 takes unit time for execution. Ther
efore, f(n) = TL3 + TL4*TL5 + TL6 = 1 + n*1 + 1 = n + 2 2n for all n 2 So, f(n)
= O(n) Procedure 2: Suppose n=8. We can calculate the value I folloing ay: iRe
sult = x 2 iResult = iResult * iResult = x iResult = iResult * iResult = x
4 8 n
iResult = iResult * iResult = x i.e. after logn time e are getting the desired
result. Inputs: iX = the value of x and iN = the value of n. Output: iResult = t
he calculated result. 1. Algo Poer(iX,iN) 2. { 3. iResult = x; 4. for(iCounter
= 1;iCounterlog(iN);iCounter++) 5. iResult = iResult*iResult; 6. return(iResult);
7. }//End of Algo Complexity: Line 3 takes unit time for execution. Line 4 take
s logn times for execution. Line 5 takes unit time for execution. Line 6 takes u
nit time for execution.

Therefore,
f(n) = TL3 + TL4*TL5 + TL6 = 1 + (logn)*1 + 1 = logn + 2 4logn for all n 2 So, f(
n) = O(logn). Hence e are getting better time complexity in second approach. In
this section e examine the asymptotic behavior of polynomials in n. In particu
lar, e ill see that as n gets large, the term involving the highest poer of n
ill dominate all the others. Therefore, the asymptotic behavior is determined
by that term. Theorem: Consider a polynomial in n of the form

here
. Then
. . Since n is non-negative, a particular term ill be . Recall too that e have
.
Proof: Each of the terms in the summation is of the form negative only if
. Hence, for each term in the summation,
stipulated that the coefficient of the largest poer of n is positive, i.e.,
Note that for integers
,
for
. Thus
No the constants .
and
, such that for all
,
. Thus,
This property of the asymptotic behavior of polynomials is used extensively. In
fact, henever e have a function, hich is a polynomial in n, e ill immediate
ly ``drop the less significant terms (i.e., terms involving poers of n hich
are less than m), as ell as the leading coefficient, , to rite .

2.5.4 Properties of Big Oh


In this section e examine some of the mathematical properties of big oh. In par
ticular, suppose e kno that f1(n) = O(g1(n)) and f2(n) = O(g2(n)). Theorem 1:
If f1(n) = O(g1(n)) and f2(n) = O(g2(n)), then f1(n) + f2(n) = O(max(g1(n), g2(n
))). Proof: From the definition of big O notation, there exist four positive con
stants n1, n2, c1 and c2 such that f1(n) c1*g1(n) for n n1 and f2(n) c2*g2(n) fo
r n n2 Let n0 = max(n1,n2) and c0 = 2*max(c1,c2). No, f1(n) + f2(n) c1*g1(n) +
c2*g2(n) c0*(g1(n) + g2(n))/2 c0*max(g1(n), g2(n)) f1(n) + f2(n) = O(max(g1(n),g
2(n))) for n n0
Thus,
Theorem 2: If f1(n) = O(g1(n)) and f2(n) = O(g2(n)), then f1(n)*f2(n) = O(g1(n)*
g2(n)). Solution: By Definition, there exist four positive constants, n1,n2, c1
and c2 such that f1(n) c1*g1(n) for all n n1 and f2(n) c2*g2(n) for all n n2. Le
t n0 = max (n1, n2) and c0 = c1*c2. Consider the product f1(n)*f2(n) for n n0. N
o, f1(n) + f2(n) (c1*g1(n)) * (c2*g2(n)) for n n0 c0*(g1(n)*g2(n)) Thus, f1(n)*
f2(n) = O(g1(n)*g2(n)). Theorem 3: If f1(n) = O(g1(n)) and g2(n) is a function 
hose value is non-negative for integers n0, then f1(n)*f2(n) = O(g1(n)*g2(n)). So
lution: By definition, there exist to positive constants n1 and c1 such that f1
(n)c1*g1(n) for all nn1. Since g2(n) is never negative, f1(n)*g2(n) c1*g1(n)*g2(n)
for all n n1 Thus, f1(n)*f2(n) = O(g1(n)*g2(n)) (Transitive Property) Theorem 4
: If f(n)=O(g(n)) and g(n)=O(h(n)) then f(n)=O(h(n)). Solution: By definition, t
here exist four positive constants, n1, n2, c1 and c2 such that f(n) c1*g(n) for
all n n1 and g(n) c2*h(n) for all n n2. Let n0 = max (n1, n2) and c0 = c1*c2. T
hen, f(n) c1*g(n) for all n n1 c1*(c2*h(n)) for all n n0 c0*h(n) Thus, f(n)=O(h(
n)).
2.5.5 Rate of groth of Big O notation
Suppose there are to algorithms A and B. No e say A is better than B in respe
ct of time complexity if A takes less time to execute than B. Comparison beteen
algorithms is generally done by some standard functions described in the follo
ing table. O(1) Constant time O(logn Logarithmic time ) O(n) Linear time c Polyn
omial time O(n ) O(c )
n
Exponential time

and their orders are: O(1) < O(logn) < O(n) < O(nlogn) < O(n2) < O(n3) < O(2n) N
ote that, time complexity O(1) of an algorithm does not mean that the algorithm
takes unit time to execute rather it takes some constant time.
2.6
Some popular Mathematical Notations and Functions

1. Floor function ( ): This function takes the nearest loer integer value of a fr
actional number. e.g. floor(3/2) = 1.ss 2. Ceiling function ( ): This function tak
es the nearest upper integer value of a fractional number. e.g. ceiling(3/2) = 2
. 3. Mod function (%): This function gives the remainder value of a division ope
ration. e.g. 12 mod 5 = 2. 4. a0 + a1 + a2 + .. + an = (an-1 -1)/(a-1). 5. 1 + 2 + 3
+ ..+ n = n(n+1)/2 6. 12 + 22 + 32 + .+ n2 = n(n+1)(2n+1)/6 7. Logax = k(logbx) he
is some constant.
2.7
Algorithmic Notation
This section describes the format that is used to rite an algorithm throughout
the book. As C is most popular language, e have folloed most syntax of C. 2.7.
1 Algorithm number: Each algorithm is assigned a unique number to identify a par
ticular algorithm. For example Algorithm 10.2 denotes second algorithm in chapte
r 10. 2.7.2 Line number: In each algorithm e specify line numbers to analyze or
describe it easily. 2.7.3 Comments: The statement after double slash (//) denot
es a comment .At the beginning of each algorithm e have specified purpose of th
is algorithm, input(s) needed for this algorithm, output returned by this algori
thm and some special comments if necessary. Each line of an algorithm may contai
n some comments to specify its purpose. 2.7.4 Variable names: The name of an int
eger variable starts ith i, name of a float variable starts ith f, name of a c
haracter variable starts ith c, name of a pointer variable starts ith ptr, nam
e of an array starts ith arr and name of a function or algorithm starts ith fn
. But in some algorithm e have not folloed this syntax for simplicity. 2.7.4 O
perator: We ill use basically three types of operators 1. Assignment operator 2
. Relational operator 3. Relational operator
2.7.4.1 Assignment operator: Our assignment operator is = like as C. For example
iElement = arrData[3] assigns the value of arrData[3] to iElement.

2.7.4.2 Relational operator: These operators are used to compare to operands to
check hether they are equal to each other or unequal or one is greater than th
e other. The folloing figure shos these operators along ith their orks. Oper
ator Operation < Less than > Greater than <= Less than or equal to >= Greater th
an or equal to == Equal to != Not equal to 2.7.4.3 Logical operator: Logical ope
rators are logicl nd denoted by &&, logicl or denoted by || nd logicl not denote
y !. Their truth tbles re described below: Logicl nd (&&) Exp1 0 0 1 1 Exp2 0
1 0 1 Result 0 0 0 1 Exp1 0 0 1 1 Logicl or (||) Exp2 0 1 0 1 Result 0 1 1 1 Lo
gicl not(!) Exp1 0 1 Result 1 0
2.7.5 Input nd Output: Dt my be tken s input from the user by scn with th
e following form: scn(Vrible nmes); Similrly to print some output print st
tement is used with the following form: print(sttement nd/or nme of vribles
); 2.7.6 Control structures: Control sttements re lso similr to C lnguge.
Bsiclly there re three types control structures: 1. Sequentil: 2. Condition
l 3. Repetitive 2.7.6.1 Sequentil logic: In  sequentil pproch ll the stte
ments re executed in the sme order s they re written. 2.7.6.2 Conditionl lo
gic: In this pproch, bsed on some condition, the different sets of sttements
re executed. An if sttement is  conditionl control structure tht executes 
set of sttements bsed upon some specified criteri. 7.6.1.1 Simple if sttement:
The syntx is if(conditions) { -------------Sttements -------------} The logic
of this structure is if the condition is true then the sttements in the if block
re executed otherwise the sttements re skipped. 7.6.1.2 Simple else sttement:
The syntx is if(conditions) {

-------------Sttement 1 -------------} else { -------------Sttement 2 ------------} If the condition of if sttement is true then sttement 1 is executed other
wise sttement 2 is executed. 7.6.1.3 Nested if sttement: This structure hs the
form: if(condition 1) { -------------Sttement 1 -------------} else if(conditio
n 2) { -------------Sttement 2 -------------} else if(condition n) { ----------} else { -------------Sttement n+1 -------------} Here only one block
is executed bsed on the specified criteri. 7.7.6.3 Repetitive logic: Here dif
ferent sets of sttements re executed repetedly for some time. Time of repetit
ions is clled number of itertion. For this purpose we will use three kinds of
loops: 1. for loop 2. while loop 3. do-while loop 2.7.6.3.1 for loop: The syntx is:
(initilize counters; test condition; increment counters) { ------------------St
tements;

------------------} 2.7.6.3.2 while loop: The syntx is: while(conditions) { -----------------Sttements; ------------------} do-while loop: The syntx is: do { -----------------Sttements; ------------------} while(conditions);
2.7.6.3.3
2.8 MCQ Chpter 2
1. Exmple(s) of O(1) lgorithms is (re): () printing  chrcter to the scree
n (b) incrementing  vrible (c) dding two numbers together (d) All of the bo
ve. 2. Exmple(s) of O(N) lgorithms is (re): () initilizing ll of the eleme
nts in n one-dimensionl rry to zero (b) incrementing ll the elements in n
one-dimensionl rry (c) multiplying two numbers by performing successive ddit
ion opertions (d) All of the bove. 3. Exmple(s) of O(N2) lgorithms is (re)
() initilizing ll the elements in  two dimensionl rry to zero (b) printin
g out ll the elements in  two dimensionl rry (c) serching for the smllest
element in n unsorted two-dimensionl rry (d) All of the bove. 4. Three lg
orithms do the sme tsk. Algorithm 1 is O(N2), Algorithm 2 is O(N), nd Algorit
hm 3 is O(Log2 N). Which lgorithm should execute the fstest for lrge vlues o
f N? () O(N) (b)O(N) (c)O(log2 N) (d) None of these. 5. Which of the following
lgorithm should execute the slowest for lrge vlues of N? () O(N) (b) O(N2) (
c) O(log2 N) (d) None of these. 6. Wht should never be found in the top level o
f  top-down design?

() Detils (b) Coding (c) Decisions (d) None of these 7. Describe Process Progr
m File in terms of Big-O, if N refers to the number of lines in the Progrm Fil
e () O(N) (b) O(1) (c) O(log2 N) (d) O(N2). 8. Describe Line Sttus of the Proc
ess Progrm- File in terms of Big-O, if N refers to the number of lines in the P
rogrm File () O(N) (b) O(1) (c) O(log2 N) (d) O(N2). 9. Which of these is the
correct big-O expression for 1+2+3+...+n? . O(log n) b. O(n) c. O(n log n) d. O
(n) Which of the following formuls in big-O nottion best represent the expressi
on n+35n+6? . O(n) b. O(n) c. O(n) d. O(42) Wht term is used to describe n O(n)
lgorithm. . Constnt b. Liner c. Logrithmic d. Qudrtic Here is some code f
or n integer vrible n:
while (n > 0) { n = n/10; // Use integer division }
10.
11.
12.
Wht is the worst-cse time nlysis for the bove loop? . O(1) b. O(log n) c.
O(n) d. O(n) Express the formul (n - 2)*(n - 4) using big-O nottion: . O(1) b.
O(n2) c. O(log n) d. O(n)
13.

e. None of the bove 14. The running time of n lgorithm T(n), where n is the
input size is given by T(n) = 8T(n/2) + qn, if n > 1 = p, if n = 1 where p, q 
re constnts. The order of this lgorithm is () n2 (b) nn (c) n3 (d) n
15. Consider the following two functions. f(n) = n3, if 0 :s; n < 10,000 n2, oth
erwise g (n) = n, if 0 :s; n < 100 n2+5n, otherwise Which of the following is/r
e true? () f(n) is O(n3) (b) g(n) is O(n3) (c) O(f(n)) is sme s O(g(n)) (d) g
(n) is O(n2) 16. The recurrence reltion tht rises in reltion with the comple
xity of binry serch is () T(n) = T(n/2) + k, where k is  constnt (b) T(n) =
2T(n/2) + k, where k is  constnt (c) T(n) = T(n/2) + log(n) (d) T(n) = T(n/2)
+ n 17. . The order of n lgorithm tht finds whether  given Boolen function
of n vribles, produces  1 is () constnt (b) liner (c) logrithmic (d) e
xponentil 18. The Ackermnns function () hs qudrtic time complexity (c) c
nt be solved itertively (b) hs exponentil time complexity (d) hs logrithmi
c time complexity
19. The running time of n lgorithm is given by T(n) = T(n - 1)+ T(n - 2) - T(n
- 3), if n > 3 = n, otherwise. The order of this lgorithm is () n (b) log n (
c) nn
(d) n2
20. Wht should be the reltion between T(l), T(2) nd T(3), so tht the previou
s question, gives n lgorithm whose order is constnt? () T(l) + T(2) = T(3) (
c) T(1) - T(3) = (2) (b) T(1) + T(3) = 2T(2) (d) T(1) + T(2) = T(3) 21. The runn
ing time T(n), where n is the input size of  recursive lgorithm is given s
follows. T(n) = c + T(n - 1), if n > 1 d, if n = 1 The order of this lgorithm i
s () n2 (b) n (c) n3 (d) nn 22. There re 4 different lgorithms Al, A2 , A3 ,
A4 to solve  given problem with the order log(n), log(log(n)), nlog(n), n log(n
) respectively. Which is the best lgorithm? () Al (b) A2 (c) A4 (d) A3

23. The concept of order (Big 0) is importnt becuse () it cn be used to deci
de the best lgorithm tht solves  given problem (b) it determines the mximum
size of  problem tht cn be solved in  given system, in  given mount of tim
e (c) it is the lower bound of the growth rte of the lgorithm (d) none of the
bove 24. An lgorithm is mde up of 2 modules M1 nd M2. If order of M1 is f (n
) nd M2 is g (n) then the order of the lgorithm is () mx (f (n) , g (n) ) (b
) min (f (n) , g (n) ) (c) f(n) + g(n) (d) f(n) * g(n) 25. Let m, n be positive
integers. Define Q(m,n) s Q(m, n) = 0, if m < n = Q(m - n, n) + p, if m n Then
Q(m, 3) is ( div b, gives the quotient when  is divided by b) ()  constnt (
b) p * (m mod 3) (c) p * (m div 3) (d) 3 * p
Solutions:
1. d 16.  2. d 17. d 3. d 18. c 4. c 19.  5. b 20.  6. c 21. b 7.  22. b 8.
c 9. b 23. ,b 24.  10. b 25. c 11. b 12. b 13. b 14. c 15.c, d
Excersies Chpter 2
1. Find () 4.3 , - 4.3 (b) 4.3 , - 4.3 2. Find (a) 50%6, 80%6 (b) -70%6, -45%10
Define Algorithm development life cycle. 4. Define Algorithm and design an algor
ithm to find out the total number of even and odd number in a group of 50 number
s. 5. Explain the different ays of analyzing algorithms. 6. What are the differ
ences beteen bottom up and top don approach of programming? 7. What is structu
red and modular programming? Differentiate beteen them. 8. Solve the recurrent
relation T(n) = T(n/2) + 1 T(1) = 1 9. Solve the recurrent relation T(n) = T(n/2
) + n T(1) = 1 10. Solve the recurrent relation Xn = 2Xn-1 1, n>1 X1=2
(GATE 1988)
(GATE 1989)

11. Convert each time formula to the best possible big-O notation. Do not includ
e any spurious constants in your big-O anser. Time Formula 10n 2n 2n + 10n . . .
Big-O
3 times log (base 2) of n .
12. Write the simplest big-O expression to describe the number of operations req
uired for the folloing algorithm:
for (i = 1; i < N; ++i) { ...statements that require exactly i operations... }

Chapter - 3 ARRAY
3.1 INTRODUCTION & DEFINITION
Depending upon the requirement of data and its structures needed to represent var
ious kinds of problems and deriving out solutions through computer the Data Stru
cture is classified into linear and non linear classes. The array supports linea
r representation of homogeneous data elements, hich facilitates to put a group
of same data items together and hence it allos to formation of a structure. An
array is referred by to things one is index i.e. the location and the other is
value in the location. In Programers vie point an array is seemed to be formed i
n contiguous locations of computer memory but it is not true alays in systems pe
rspective. One of the major advantages of array is that to use in a program is v
ery easy but the main difficulty lies in the fact as array is formed in primary
memory of a computer thus it is volatile.
DEFINITION
An array is defined as a finite ordered set of homogeneous elements. Finite mean
s there is a specific number of elements. Ordered means the elements of the arra
y are indexed. Homogeneous means all the elements of the array must be of same t
ype (e.g. int, float, char etc.).
3.2
DECLARATION OF ARRAY
3.2.1 Declaration: One dimensional array: int iarrMarks[100] // Declares array i
arrMarks[] ith 100 integers float farrNum[100] // Declares array farrNum[] ith
100 floating point numbers. char carrName[100] // Declares array carrName[] it
h 100 characters In General case, consider an array as a[l1..u1] Obviously the a
bove array contains (u1 l1 + 1) elements. In C, the loer index l1 for an array i
s 0. To dimensional array: int iarrMatrix[20][30] //Declares to dimensional ar
ray ith order 20X30 (i.e. 20 ros and 30 columns). No consider a to dimension
al array in general as a[l1..u1][l2..u2] Then the above array contains (u1 l1 + 1
) ros and (u2 l2 + 1) columns. So the total number of elements in the array is (
u1 l1 + 1) (u2 l2 + 1). N dimensional array: If e interpret the indices to be N-d
imensional (i1, i2, i3, in) then it is called an N-dimensional array. In the N-di
mensional array, if the array is declared as a[l 1u1][l2u2] [lnun] here li and ui a
re the loer bound and upper bound respectively of the ith dimension then The to
tal number of elements = (u1-l1+1)(u2-l2+1)(un-ln+1) n = (ui-li+1) i=1

3.3
MEMORY REPRESENTATION OF ARRAY
There are to ays to store an array into memory-1) Ro major ordering and 2) Co
lumn major ordering. They are described in this section. Here it is considered t
hat each element takes only one byte to store its value. 3.3.1 Ro major orderin
g: In ro major ordering the ros of the array are stored first. Consider an one
dimensional array a[l1..u1]. Suppose its base address (address of the first ele
ment) is . 1 1+1 . i1 . u1
Then the address of the eement a[i1] is + i1 1. Now consider a 2-dimensiona a
rray a[0..3][0..3]. Its rows and eements in each row are depicted beow. a[0][0
] a[0][1] a[0][2] a[1][0] a[1][1] a[1][2] a[2][0] a[2][1] a[2][2] a[3][0] a[3][1
] a[3][2] Row 4 Row 3 Row 2 Row 1
For a genera case suppose the decaration of a 2-dimensiona array be a[ 1u1][
2u2] and the base address is . 2 2+1 . i2 . u2 1 2 +1 . i1 -1 i1 . u1

Now to cacuate the address of the eement a[i1][i2], first traverse the i1-1
rows (each row contains u2-2+1 eements ) and then i2-2 eements. Hence the ad
dress of a[i1][i2] = + (i1-1)(u2-2+1)+(i2-2). Now consider a 3-dimensiona ar
ray a[0..2][0..2][0..1]. a[0][0][0] a[0][0][1] a[0][1][0] a[0][1][1] a[0][2][0]
a[0][2][1] a[1][0][0] a[1][0][1] a[1][1][0] a[1][1][1] a[1][2][0] a[1][2][1] a[2
][0][0] a[2][0][1] a[2][1][0] a[2][1][1] a[2][2][0] a[2][2][1] Row 3 Row 2 Row 1
Page 3 Row 3 Row 2 Row 1 Page 2 Row 3 Row 2 Row 1 Page 1
If a decaration of a 3-dimensiona array be a[1u1][2u2][3u3] and the base addre
ss be then the address of the eement a[i1][i2][i3] = +(i1-1)(u2-2+1)(u3-3+1)
+(i2-2) (u3-3+1)+(i3-3) Hence for an N-dimensiona array a[1u1][2u2]..[nun], i
f the base address be (i.e. the address of a[1] [2]..[n]), then the address o
f a[i1][i2]..[in] = + (i1-1)(u2-2+1)(u3-3+1)( un-n+1) + (i2-2)(u3-3+1)(u4-
4+1)( un-n+1) + . + . + (in-n) n = + j=1.n (ij-j)aj with aj= (uk-lk+1) k=j+1 an=

3.3.2 Column major ordering: In this technique e store the columns of an array
first. Consider an one dimensional array a[l1..u1]. Suppose its base address (ad
dress of the first element) is . 1 1+1 . i1 . u1
Then the address of the eement a[i1] is + i1 1. Consider a 2-dimensiona array
a[0..3][0..2]. Its coumns and eements in each coumn are depicted beow. a[0]
[0] a[1][0] a[2][0] a[3][0] a[0][1] a[1][1] a[2][1] a[3][1] a[0][2] a[1][2] a[2]
[2] a[3][2] Coumn 3 Coumn 2 Coumn 1
Suppose the decaration of a 2-dimensiona array be a[1u1][2u2] and the base add
ress be . 2 2+1 . i2-1 i2 . u2 1 2 +1 . i1 . u1 Now to cacuate the address of a
[i1][i2] first traverse the i2-2 coumns (each coumn has u1-1+1 eements) and
then i1 1 eements. Hence the address of a[i1][i2] = + (i1-1)+(i2-2) (u1-1+
1).

Now consider a 3-dimensiona array a[0..2][0..2][0..1] ; a[0][0][0] a[0][1][0] a


[0][2][0] a[0][0][1] a[0][1][1] a[0][2][1] a[1][0][0] a[1][1][0] a[1][2][0] a[1]
[0][1] a[1][1][1] a[1][2][1] a[2][0][0] a[2][1][0] a[2][2][0] a[2][0][1] a[2][1]
[1] a[2][2][1] If a decaration of a 3-dimensiona array be a[1u1][2u2][3u3] and
the base address be then the address of a[i1][i2][i3] = +(i1-1) +(i2-2)(u1-1
+1)+(i3-3)(u2-2+1)(u1-1+1) Hence for an N-dimensiona array a[1u1][2u2][nun],
if the base address be (i.e. the address of a[1,2,..,n]) then the address of
a[i1][i2][in] = + (i1-1) + (i2-2)(u1-1+1) + . + . + (in-n) (un-1-n-1+1)(u1-1+1)
= + j=1.n (ij-j)aj with 1 aj= (uk-lk+1) k=j-1 a1= 1 Column 2 Column 1 Page 3 Colu
mn 2 Column 1 Page 2 Column 2 Column 1 Page 1

3.4
INSERTION INTO ONE DIMENSIONAL ARRAY
Algorithm 3.1 describes the process of insertion into one dimensional array. Alg
orithm 3.1 1. Algorithm fnInsertion_into_ 1D_Array(arrData, n, k, item) 2. // Pu
rpose : This algorithm inserts an element into one dimensional array. 3. // Inpu
t : arrData[] is an one dimensional array ith n number of elements. Element ite
m is to be inserted into the kth position in the array. 4. // Output : None. 5.
{ 6. for(i=n-1;i>=k-1;i--) 7. arrData [i+1]= arrData [i]; 8. arrData[k-1]=item;
// Insert the item. 9. n=n+1; // Set size of the array. 10. }// End of Algorithm
. Example: Consider an array arrData[] ={10,30,40,50}; Index Element 0 1 0 1 3 0
2 4 0 3 50
We have to insert 20 in to the 2nd position in the array. So, here non=4, k=2,
item=20 fnInsertion_into_ 1D_Array (arrData, 4, 2, 20) { for(i=3;i>=1;i--) i.e.
the for loop ill be executed for 3 times. i=3 arrData[3+1]= arrData[3]; Index 0
Element 1 0 i=2 arrData[2+1]= arrData[2]; Index 0 Element 1 0 i=1 arrData[1+1]=
arrData[1]; Index 0 Element 1 0 Execution of for loop is stopped here. arrData[
k-1]=item; or arrData[1]=20; Index 0 Element 1 0 n=n+1; or n=5;
1 3 0 1 3 0 1 3 0 1 2 0
2 4 0 2 4 0 2 3 0 2 3 0
3 5 0 3 4 0 3 4 0 3 4 0
4 50
4 50
4 50
4 50

} So finallyIndex Element 0 1 0 1 2 0 2 3 0 3 4 0 4 50
3.5
DELETION FROM ONE DIMENSIONAL ARRAY
Algorithm 3.2 describes the process of deletion from one dimensional array. Algo
rithm 3.2 1. Algorithm fnDeletion_from_1D_Array (arrData, n, k) 2. // Purpose :
This algorithm deletes an element from one dimensional array. 3. // Input : arrD
ata[] is an one dimensional array ith n number of elements. Element item is to
be deleted from the kth position of the array. 4. // Output : Deleted element it
em. 5. { 6. item= arrData[k-1]; //Item deleted. 7. for(i=k-1;i<n-1;i++) 8. arrDa
ta[i]= arrData[i+1]; 9. n=n-1; //Set size of the array. 10. return item; 11. }//
End of Algorithm Example: Let array arrData[]={10,20,30,40,50}; 0 1 2 1 2 3 0 0
0 nd We have to delete the 2 element from the array. Therefore, n=5, k=2 fnDelet
ion_from_1D_Array(arrData,5,2) { item = arrData[1] = 20; for(i=1;i<5-1;i++) i.e.
the for loop ill be executed for 3 times. i=1 arrData[1]= arrData[1+1]; Index
0 1 2 Element 1 3 3 0 0 0 i=2 arrData[2]= arrData[2+1]; Index 0 1 2 Element 1 3
4 0 0 0 i=3 arrData[3]= arrData[3+1]; Index 0 1 2 Element 1 3 4 0 0 0 Execution
of for loop stops here. n=n-1; or n=4; } Index Element 3 4 0 4 50
3 4 0 3 4 0 3 5 0
4 50
4 50
4 50

So finally Index Element 0 1 0 1 3 0 2 4 0 3 50


3.6
TRAVERSING ONE DIMENSIONAL ARRAY
Traversing means to access all the elements of the array (starting from the firs
t element up to the last one). Algorithm 3.3 describes the process. Algorithm 3.
3 1. Algorithm fnTraverse_1D_Array(arrData, n) 2. // Purpose : This algorithm pr
ints all the elements of a one dimensional array. 3. // Input: arrData[] is an o
ne dimensional array ith n number of elements. 4. // Output : None. 5. { 6. for
(i=0;i<n;i++) 7. print arrData[i]; 8. }//End of Algorithm
3.7
MERGING TWO ONE DIMENSIONAL ARRAYS
Merging means combining the elements of to arrays into a third array. The gener
al technique is first copy all the elements of the first array into third array
and then copy the elements of the second array. If you ant to get a sorted arra
y then you can sort the resultant third matrix. Another approach is sorting hil
e merging. For this technique merging is done of to sorted arrays. This techniq
ue is described in chapter 12 (Merge sort) in details. Here e ill discuss the
first approach of merging i.e. e are bothered about hether the resultant array
is sorted or not. Suppose e have to merge the elements of the arrays arrA and
arrB into the resultant array arrC. First Array Second Array Third Array arrA[0]
arrA[1] arrA[2] arrA[3] arrA[4] 10 55 45 30 20 arrB[0] arrB[1] arrB[2] arrB[3]
15 12 27 24 arrC[0] arrC[1] arrC[2] arrC[3] arrC[4] arrC[5] arrC[6] arrC[7] arrC
[8] 10 55 45 30 20 15 12 27 24
Algorithm 3.4 describes the procedure. Algorithm 3.4 1. Algorithm fnMerge(arrA,
arrB, arrC, AN, BN) 2. // Purpose : This algorithm merges to one dimensional ar
rays. 3. // Input : arrA and arrB are to one imensional arrays and contain AN a
nd BN elements respectively. Elements of arrA and arrB are copied into arrC. 4.
// Output : None. 5. {

6. //First copy the elements of arrA into arrC. 7. for(i=0;i<AN;i++) 8. arrC[i]


= arrA[i]; 9. //No copy the elements of arrB into arrC. 10. for(i=0;i<BN;i++) 1
1. arrC[AN+i] = arrC[i]; 12. }//End of Algorithm
3.8
MATRIX ADDITION
A= 9 6 2 5 B= 8 1 4 7
Consider to matrices A and B.
Then their addition produces resultant matrix C as C= 9+8 6+1 2+4 5+7 = 17 7 6 1
2
Algorithm 3.5 describes the matrix addition procedure. Algorithm 3.5 1. Algorith
m fnMatrix_Addition(arrA,arrB,arrC,iN,iM) 2. // Purpose : This algorithm perform
s the addition of to matrices. 3. // Input : arrA and arrB are to iN X iM matr
ices. arrC is resultant matrix. 4. // Output : None. 5. { 6. for(i = 0;i<iN;i++)
7. for(j=0;j<iM;j++) 8. arrC[i][j] = arrA[i][j] + arrB[i][j]; 9. }// End of Alg
orithm
3.9
SPARSE MATRIX
Matrices ith a relatively high proportion of zeros are called sparse matrices.
If the matrix is sparse e must consider an alternate ay of representing it rat
her than the normal ro major or column major arrangement. This is because if ma
jority of elements of the matrix are 0 then an alternative through hich e can
store only the non-zero elements and keep intact the functionality of the matrix
can save a lot of memory space. Example of a sparse matrix is: 0 1 2 3 4 0 0 0
3 0 0 1 0 0 0 0 1 4 2 0 0 0 0 0 3 0 0 0 0 0 4 0 0 0 1 0 0 5 0 0 0 0 0 6 0 8 0 0
0 7 0 0 4 0 0 0 8 0 0 0 0 1 9 15 0 0 0 0

5 6 7 8
0 0 0 0
0 0 0 0
2 0 0 0 0
0 0 9 0
0 0 0 0
0 3 1 0 0
0 0 0 0
0 0 0 -2
0 0 0 0
0 0 0 0
The above 9 X 10 sparse matrix takes 90 memory spaces to save it into memory acc
ording to ro major or column major ordering. A common ay of representing non-z
ero elements of a sparse matrix is the 3-tuple forms. In this technique the abov
e matrix looks like: int arrSpmtx[12][3]={ 9 10 11 // 9X10 matrix having 11 nonzero elements. 0 9 15 1 6 -8 2 0 -3 2 7 40 3 4 10 4 1 14 4 8 -1 5 2 20 6 5 31 7
3 -9 8 7 -2 }; The first ro of the matrix arrSpmtx stores the order of the orig
inal matrix and number of nonzero elements. The next ros store the values of th
e nonzero elements and their positions in the original matrix. For the given exa
mple 12X3=36 memory spaces are required to store the hole matrix i.e. (90-36) =
54 memory spaces can be saved. Algorithm to create a 3-tuple of a given matrix
Algorithm 3.6 1. Algorithm fnSparse_Matrix_Using_3tuple(arrOriginal, iRo, iColu
mn, arrSpmtx) 2. // Purpose : This algorithm creates a 3-tuple of a given matrix
. 3. // Input : arrOriginal is the original matrix ith order iRo X iColumn and
arrSpmtx is its 3-tuple form. 4. // Output : None. 5. { 6. Index = 0; 7. iNon_Z
ero_Elements = fnCount_Non_Zero_Elements(arrOriginal, iRo, iColumn); 8. arrSpmt
x[Index][0] = iRo; 9. arrSpmtx[Index][1] = iColumn; //Set first ro 10. arrSpmt
x[Index][2] = iNon_Zero_Elements; 11. Index++; 12. for(i=0;i<iRo;i++) 13. for(j
=0;j<iColumn;j++) 14. if(arrOriginal[i][j] != 0) 15. { 16. arrSpmtx[Index][0] =
i; 17. arrSpmtx[Index][1] = j; //Set next ros 18. arrSpmtx[Index][2] = arrOrigi
nal[i][j]; 19. Index++; 20. }

21. }//End of algorithm Algorithm 3.7 1. Algorithm fnCount_Non_Zero_Elements(arr


Original, iRo, iColumn) 2. // Purpose : This algorithm counts number of non-zer
o elements in a matrix. 3. // Input : arrOriginal matrix ith order iRo X iColu
mn. 4. // Output : Returns number of non-zero elements. 5. { 6. iNon_Zero_Elemen
ts = 0; 7. for(i=0;i<iRo;i++) 8. for(j=0;j<iColumn;j++) 9. if(arrOriginal[i][j]
!= 0) 10. iNon_Zero_Elements++; 11. return iNon_Zero_Elements; 12. }// End of a
lgorithm To general types of n-square sparse matrices are triangular matrix and
tri-diagonal matrix. Triangular matrix: In a matrix here all entries on or bel
o (or on or above) the main diagonal are non-zero is called a loer (upper) tri
angular matrix. 15 -8 40 10 -3 14 31 20 -1 -9 Loer triangular matrix 31 -9 14 4
0 15 Upper triangular matrix 20 10 -1 -3 -8
Loer triangular matrix: Suppose e ant to place in memory the loer triangular
array a[][]. Clearly it ould be asteful to store those entries above the main
diagonal of a[][], since e kno they are all zero; hence e store only the oth
er entries of a[][] in an one dimensional array b[]. b[1] b[2] b[3] b[4] b[5] b[
6] b[7] b[8] b[9] b[10] 15 -8 40 10 -3 14 31 20 -1 -9 a[1][1] a[2][1] a[2][2] a[
3][1] a[3][2] a[3][3] a[4][1] a[4][2] a[4][3] a[4][4] Observe first that b[] il
l contain only1 + 2 + 3 + + n = n(n+1)/2 elements, hich is about half as many el
ements as a 2-dimensional n X n array. Since e ill require the value of a[j][k
] in our programs, e ill ant the formula that gives us the integer x in terms
of j and k hereb[x] = a[j][k] Observe that x represents the no of elements in
the list up to and including a[j][k]. No there are1 + 2 + 3 + .. + (j-1) = j(j-1
)/2 elements in the ros above a[j][k], and there are k elements in the ro j up
to and including a[j][k]. Accordingly, x = j(j-1)/2 + k yields the index that a
ccess the value a[j][k] from the linear array b[]. Algorithm 3.8 1. Algorithm fn
a_to_b(a,b,n)

2. // Purpose : This
to a one dimensional
triangular matrix a
tput : None. 5. { 6.
1)/2 + k; 11. b[x] =

algorithm stores the


array. 3. // Input :
is to be stored into
for(j=1;j<=n;j++) 7.
a[j][k]; 12. } 13. }

elements of a loer triangular matrix


The non-zero values of the n X n loer
the onedimensional array b[]. 4. // Ou
{ 8. for(k=1;k<=j;k++) 9. { 10. x=j(j14. }//End of algorithm

Algorithm 3.9 1. Algorithm fnb_to_a(a,b,n) 2. // Purpose : This algorithm restor


es the elements of a loer triangular matrix. 3. // Input : The elements of the
n X n loer triangular matrix a is to be restored from the onedimensional array
b[]. 4. // Output : None. 5. // Comments : Restore the nonzero elements stored in
to the one-dimensional array b[] to the n X n loer triangular matrix a[][] and
fills the other entries of the loer triangular matrix a[][] by zeros. 6. { 7. i
=1; 8. for(j=1;j<=n; j++) 9. { 10. for(k=1;k<=j; k++) 11. { 12. a[j][k] = b[i];
// stores the non-zero element 13. i++; 14. } 15. for(k=j+1;k<=n; k++) //stores
the zero values 16. a[j][k] = 0; 17. } 18. }//End of algorithm
3.10 POLYNOMIAL REPRESENTATION
A polynomial can be represented using array. Suppose e have an integer array of
10 elements: int arrPoly[10]; Using the above array, the folloing polynomial i
s to be stored. 2A7 + 10A5+8A2+ 15A + 21 Consider a general term of a polynomial
as CAE. The procedure is to store the coefficient C in the index E of the array
. Thus the array representation of the given polynomial looks like this: Index 0
Coefficient 2 1 1 1 5 2 3 4 5 8 0 0 1 0 6 7 8 9 0 2 0 0

As array is static in nature, so this process to store a polynomial is not an ef


ficient one. The efficient ay is to store a polynomial in a linked list, hich
is described in details in chapter 8.
3.11 MCQ Chapter 3
1. Structured data type made up of finite collection of ordered elements, all of
hich is of same data type is: (a) record (b) array (c) file (d) None of these
2. Elements of array are accessed by (a) accessing function in built-in data str
ucture (b) mathematical function (c) index (d) None of these. 3. Array is (a) Li
near data structure (b) non-linear data structure (c) Complex data structure (d)
None of these. 4. Ro-major order in to dimensional array refers to (a) all el
ements of a ro are stored in memory in sequence folloed by next ro in sequenc
e and so on. (b) all elements of a ro are stored in memory in sequence folloed
by next column in sequence and so on. (c) all elements of a column are stored i
n memory in sequence folloed by next column in sequence and so on. (d) None of
these 5. Suppose that a to - dimensional arraydeclared ac; "char a [5][6]," is
internally stored in contiguous memory locations starting from the locations "10
00" in a column-major manner. The address here a [i] U] ould be stored is (a)
1000+i+j*5 (b) 1000+i*4+j (c) 1000 + i + j * 6 (d) 1000 + i * 6 + j
6. A matrix. a, is called loer triangular if and only if for all j > i aij = O.
If such a matrix is mapped to Idimensional matrix A then it could be mapped to
the folloing index of A . (a) 1/2 * i (i + 1) + j (b) i + j (c) i (i + 1) + j (
d) None of the above 7. In a compact single dimensional array representation for
loer triangular matrices (i.e., an the elements above the diagonal are zero) o
f size n x n, nonzero elements (i.e., of the loer triangle) of each ro are sto
red one after another. starting from the first ro, the index cl: the (i,jih ele
ment of the loer triangular matrix in this representation is: (GATE-1994) (a) i
+ j (b) i + j - 1 (c) j + i (i - 1)/2 (d) i + j (j - 1)/2 8. Let A = (aij) be a
n n-roed square matrix and /12 be the matrix obtained by interchanging the firs
t and second ros of the n-roed Identity matrix. Then All2 is such that its fir
st:

(a) ro is the same as its second ro (b) ro is same as the second ro of A (c)
column is the same as the second column of A (d) ro is all zero
(GATE-1997)
9. Let A be a to dimensional array declared as follos: A: array [1..10] [1..15
] of integer; Assuming that each integer takes one memory location the array is
stored in ro-major order and the first element of the array is stored at locati
on. 100, hat is the address of the element A [l][J] ? (GATE-1998) (a) 15i + j +
84 (b) 15j + i + 84 (c) Wi + j + 89 (d) 10j + i + 89 10. The information about
an array that is used in a program ill be stored in (a) symbol table (b) activa
tion record (c) system table (d) dope vector 11. Which of the folloing expressi
ons accesses the (i,j)lh entry of a (m x n) matrix stored in column major form?
(a) n x (i-l) + j (b) m x(j -1) + i (c) m x (n-j) + j (d) n x (m-i) + j 12. Spar
se matrices have (a) many zero entries (c) higher dimension (b) many non-zero en
tries (d) none of the above
Solutions:
1. b 2. c 3. a 4. a 5. a 6. d 7. c 8. c 9. a 10. a 11. a 12. a
3.12 Exercise Chapter 3
1. Define an array. Ho can an array be declared? 2. What is row major and coumn m
ajor ordering of an array? Expain with a suitabe exampe. 3. Write an agorithm
to find out the maximum and the 2nd maximum number from an array of integers. 4
. Wtite a C function to find out whether an eement aij in an array A[I,J} such
that aij is the greatest vaue in ith row and smaest vaue in jth coumn. What
is the time compexity of your function? 5. Write a C program to find out wheth
er a matrix is symmetric or not. 6. Consider two singe dimention arrays of size
20 and 30 respectivey. Write an agorithm tofind out the eements which are co
mmon to both the arrays. 7. An integer array is decared as A[I,J,K]. The starti
ng address of this array is 1000. Considering integer size is of 4 bytes, find o
ut the ocation of A[i,j,k] in coumn major fasion. 8. An array A contains 25 po
sitive integers. Write an agorithm which wi find out a pairs of eements wh
ose sum is 30. 9. An array A contains 25 positive integers. Write an agorithm w
hich wi find out the number of odd and even numbers in that array. 10. Write a
C program which wi input an integer array of various sizes and compute the av
erage vaue of the eements of that array.

Chapter - 4 STRUCTURE AND POINTER


4.1 DEFINITION OF STRUCTURE
We have seen in chapter 3 that an array can be used to store the homogeneous dat
a i.e. the data of same data types (e.g. int, foat, char etc.). But using a str
ucture we can create a user defined data type consisting of ogicay reated da
ta items of different data types. The genera format of a structure definition i
s as foows: struct structure_name { ---------------------structure eements; --------------------};
4.2
BASIC OF POINTER
Consider the foowing statement: int iData = 10; When compier compies the abo
ve statement, it aocates a memory space from the heap (avaiabe memories) to
store the variabe iData ike the foowing: Name of the variabe: Vaue of the
variabe: Address of the variabe: iData 10 2020
Now we can access the vaue 10 by two ways: 1. By name and 2. By address. To sto
re the address of iData into another variabe, we need a pointer variabe and th
e decaration is: int *iptr1; //Signifies that vaue at address iptr1 is some in
teger vaue. char *cptr1; //Signifies that vaue at address cptr1 is some charac
ter vaue. For pointer operations, two operators are avaiabe 1) * (vaue at) 2
) &(address of). Suppose we want to store the address of iData into iptr1. The d
ecaration is: iptr1 = &iData;

Name of the variabe: Vaue of the variabe:


iptr1 2020
Address of the variabe: 4010 Now we can print the vaue 10 in two different way
s: printf(%d,iData); printf(%d,*iptr1);
4.3
STRUCTURE AND POINTER
In the previous section we have seen a pointer pointing to an int or a pointer p
ointing to a char. Simiary we can have a pointer pointing to a struct. Conside
r the foowing program code: struct date { int dd; int mm; int yy; }; main() {
struct date d1={06,04,2008}; //Decare d1 as structure variabe. struct date *d2
; //Decare d2 as a pointer to a structure. d2 = &d1; printf(%d/%d/%d,d1.dd,d1.mm,
d1.yy); printf(%d/%d/%d,d2->dd,d2->mm,d2->yy); } Name of the variabe: Vaue of th
e variabe: Address of the variabe: 4050 d1.dd 06 4052 d1.mm 04 d1.yy 2008 4054
d2 4050 8020
4.4
PASSING STRUCTURE TO FUNCTIONS
struct date { int dd; int mm; int yy; }; main() { struct date d1; //Decare d1 a
s structure variabe. fnGetDate(&d1); //Pass the structure by its address. fnSho
wDate(&d1); //Pass the structure by its address. } void fnGetDate( struct date *
d2) { *d2->dd = 06; *d2->mm = 04;

*d2->yy = 2008; } void fnShowDate( struct date *d2) { printf(%d/%d/%d,d2->dd,d2->m


m,d2->yy); }
4.5
SELF REFERENTIAL STRUCTURE
Consider the foowing structure decaration: struct node { int iData; struct no
de *ptrNext; }; Notice that here the structure eement ptrNext contains the addr
ess of a node simiar to itsef. Such type of structure is caed sef referenti
a structure.
4.6
DYNAMIC MEMORY ALLOCATION
The dynamic or run time memory aocation heps us to make efficient use of by a
ocating the required amount of memory whenever is needed. C provides the foo
wing dynamic aocation and de-aocation functions: (I) maoc() (II) caoc()
(III) reaoc() (IV) free() (I) maoc(): The genera syntax of maoc() functio
n is: (data_type *) maoc(size of one bock * number of bocks) Suppose we want
to aocate the memory space for previousy defined structure node in run time
using maoc() function. Then the statement is: struct node *ptrNode = (struct n
ode*)maoc(sizeof(struct node)); (II) caoc():The genera syntax of caoc() f
unction is: (data_type *) caoc(number of bocks , size of one bock) Suppose w
e want to aocate the memory space for the structure node using caoc() functi
on. Then the statement is: struct node *ptrNode = (struct node*)caoc(sizeof(st
ruct node)); (III) reaoc(): In some situation, the previousy aocated memory
is insufficient to run the correct appication. It is aso possibe that the am
ount of memory aocated is arge enough than the required memory. In both the c
ases it is necessary to reaocate the memory spaces and this can be done using
reaoc() function. The genera syntax of reaoc() function is: (data_type *) r
eaoc(ptr, new size) ptr is a pointer hoding the starting address of the aoc
ated memory bock. Suppose now we want to aocate 2 bock of node in the pointe
r variabe ptrNode. Then the statement is: ptrNode = (struct node*)reaoc(ptrNo
de, 2* sizeof(struct node)); (IV) free(): Now to de-aocate the memory spaces w
e can use the function free() and the decaration is: free(name of pointer varia
be);
4.7
MCQ Chapter 4
1. Dynamic memory aocation use

a) Caoc b) Maoc c) Free d) a of these 2. Sef referentia structure refers


a) own instance b) own address c) own variabes d) none of these 3. Defaut a
ocation of variabes in maoc() is equa to a) zero b) garbage c) any ve vaue d
) any +ve vaue 4. Defaut aocation of variabes in caoc() is equa to a) ze
ro b) garbage c) any ve vaue d) any +ve vaue 5. A pointer contains a) address o
f other variabes b) address of other pointers c) both a) and b) d) none of thes
e 6. when compied a structura code changes to a) Executabe code b) Non execut
abe code c) Assignment code d) None of these 7. A record structure can be repre
sented as a) Hierarchica structure b) Canonica structure c) Linear structure d
) A of these 8. Dynamic memory aocation is used to a) For program efficiency
b) For space management c) For time management d) A of these 9. Advantage of
using structure is a) To use ogicay reated data items but of different datat
ypes. b) To represent the records in a hierarchica manner c) To create an user
defined data type d) None of these 10. In C, size of a structure variabe depend
on a) The variabe of the maximum size used in the structure b) The numbers of
variabes used in the structure c) Both a) and b) d) None of these
Soutions:
1. d 2. a 3. b 4. a 5. c 6. c 7. d 8. b 9. a 10. b

4.8 Exercises Chapter 4


1. What is a Structure? What is a Pointer? 2. How can a structure be passed by a
pointer? 3. What is dynamic memory aocation? what is its advantages? 4. What
is sef refferntia structure? Discuss with an exampe. 5. How can a structure b
e passed to a function? 6. The foowing is a ist of entries, with eve number
s, in a fie of empoyee record: 1. Empoyee(200) 2. Name 3. Last 4. First 5. Mi
dde 6. Address 7. Street 8. Area 9. City 10. State 11. Country 12. Pin Code 13.
Age 14. Saary 15. Dependents a) Draw the corresponding hierarchica structure.
b) Which of the items are eementary items? Describe and write down a record in
C to impement this structura representation of data.

Chapter 5 STRINGS
5.1 Definition:
Let be an alphabet, a non-empty finite set. Elements of are called symbols or ch
aracters. A string (or word) over is any finite sequence of characters from . For
example, if = {0, 1}, then 0101 is a string over . The length of a string is the
number of characters in the string (the length of the sequence) and can be any
nonnegative integer. The empty string is the unique string over of length 0, and
is denoted or . Th st of a strings ovr of ngth n is dnotd n. For xamp
, if = {0, 1}, thn 2 = {00, 01, 10, 11}. Not that 0 = {} for any aphabt . Th s
t of a strings ovr of any ngth is th Kn cosur of and is dnotd as *.
In trms of n,
For xamp, if = {0, 1}, * = {, 0, 1, 00, 01, 10, 11, 000, 001, 010, 011, }. Atho
ugh * itsf is countaby infinit, a mnts of * hav finit ngth. A st of
strings ovr (i.. any subst of *) is cad a forma anguag ovr . For xamp
, if = {0, 1}, th st of strings with an vn numbr of zros ({, 1, 00, 11, 00
1, 010, 100, 111, 0000, 0011, 0101, 0110, 1001, 1010, 1100, 1111, }) is a forma
anguag ovr .
5.2 Concatnation and substrings
Concatnation is an important binary opration on *. For any two strings s and t
in *, thir concatnation is dfind as th squnc of charactrs in s foowd
by th squnc of charactrs in t, and is dnotd st. For xamp, if = {a, b, ,
z}, s = data, and t = structur, thn st =datastructur and ts = structurdata.
tring concatnation is an associativ, but non-commutativ opration. Th mpt
y string srvs as th idntity mnt; for any string s, s = s = s. Thrfor, t
h st * and th concatnation opration form a monoid, th

fr monoid gnratd by . In addition, th ngth function dfins a monoid homo
morphism from * to th non-ngativ intgrs. A string s is said to b a substrin
g or factor of t if thr xist (possiby mpty) strings u and v such that t = u
sv. Th ration "is a substring of" dfins a partia ordr on *, th ast m
nt of which is th mpty string.
5.3 tring oprations
A numbr of additiona oprations on strings commony occur in Data tructur. T
hy ar xpaind bow:
5.3.1 Aphabt of a string
Th aphabt of a string is a ist of a of th ttrs that occur in a particu
ar string. If s is a string, its aphabt is dnotd by Aph(s)
5.3.2 tring substitution
Lt L b a anguag, and t b its aphabt. A string substitution or simpy a
substitution is a mapping f that maps ttrs in to anguags (possiby in a dif
frnt aphabt). Thus, for xamp, givn a ttr a , on has f(a) = La whr i
s som anguag whos aphabt is . This mapping may b xtndd to strings as f()
= for th mpty string , and f(sa) = f(s)f(a) for nonmpty string . tring subs
titution may b xtndd to th ntir anguag as
An xamp of string substitution occurs in rguar anguags, which ar cosd
undr string substitution. That is, if th ttrs of a rguar anguag ar sub
stitutd by othr rguar anguags, th rsut is sti a rguar anguag.
5.3.3 tring homomorphism
A string homomorphism is a string substitution such that ach ttr is rpacd
by a sing string. That is, f(a) = s, whr s is a string, for ach ttr a.
tring homomorphisms ar homomorphisms, prsrving th binary opration of strin
g concatnation. Givn a anguag L, th st f(L) is cad th homomorphic imag
 of L. Th invrs homomorphic imag of a string s is dfind as
f-1(s) = { w | f(w) = s}
whi th invrs homomorphic imag of a anguag L is dfind as
f-1(L) = { s | f(s) L}
Not that, in gnra, f(f-1(L)) L, whi on dos hav

f(f-1(L))
L and L
f-1(f(L))
for any anguag L. imp sing-ttr substitution ciphrs ar xamps of st
ring homomorphisms.
5.3.4 tring projction
If s is a string, and is an aphabt, th string projction of s is th string t
hat rsuts by rmoving a ttrs which ar not in . It is writtn as . It is f
ormay dfind by rmova of ttrs from th right hand sid:
(s) = = (t) = (t)
if s = , th mty string if s = ta and a
if s = ta and a
Hr dnots th mpty string. Th projction of a string is ssntiay th sam
 as a projction in rationa agbra. tring projction may b promotd to th
 projction of a anguag. Givn a forma anguag L, its projction is givn b
y
(L) = { (s) | s L} 5.3.5 tring Right quotint
Th right quotint of a ttr a from a string s is th truncation of th ttr
a in th string s, from th right hand sid. It is dnotd as s / a. If th str
ing dos not hav a on th right hand sid, th rsut is th mpty string. Thus
:
(sa) / b
=s =
if a = b if a b
Th quotint of th mpty string may b takn: / a = imiary, givn a subst 
M of a monoid M, on may dfin th quotint subst as

 / a = { s M | sa }
Lft quotints may b dfind simiary, with oprations taking pac on th f
t of a string.
5.3.6 tring yntactic ration
Th right quotint of a subst  ration of . It is givn by M of a monoid M d
fins an quivanc ration, cad th right syntactic
~s = { (s, t) M x M |  / s =  / t }

Th ration is cary of finit indx (has a finit numbr of quivanc cas
ss) if and ony if th famiy right quotints is finit; that is, if { / m | m
M } is finit. In this cas,  is a rcognizab anguag, that is, a anguag
that can b rcognizd by a finit stat automaton. This is discussd in gratr
dtai in th artic on syntactic monoids.
5.3.7 tring Right cancation
Th right cancation of a ttr a from a string s is th rmova of th first
occurrnc of th ttr a in th string s, starting from th right hand sid.
It is dnotd as s a and is rcursivy dfind as
(sa) b
=s
if a=b
= ( s b )a if a b
Th mpty string is aways cancab: a = Cary, right cancation and proj
ction commut:
(L) a = (L) ( s a ) 5.3.8 String Prfixs
Th rfixs of a string is th st of all rfixs to a string, with rsct to
a givn languag:
Prf L(s) = { t | s = tu for u L }
Th prfix cosur of a anguag is
A anguag is cad prfix cosd if Prf (s) = L. Cary, th prfix cosur
oprator is idmpotnt:
Prf (Prf (L)) = Prf (L)
Th prfix ration is a binary ration s t such that if and ony if s Prf L(t
).
Prfix grammars gnrat anguags that ar prfix-cosd.
5.4 tring Topoogy
trings admit th foowing intrprtation as nods on a graph: Fixd ngth str
ings can b viwd as nods on a hyprcub; Variab ngth strings (of finit 
ngth) can b viwd as nods on th k-ary tr, whr k is th numbr of symbo
s in ; Infinit strings can b viwd as infinit paths on th k-ary tr.

Th natura topoogy on th st of fixd ngth strings or variab ngth strin
gs is th discrt topoogy, but th natura topoogy on th st of infinit str
ings is th imit topoogy, viwing th st of infinit strings as th invrs 
imit of th sts of finit strings. This is th construction usd for th p-adic
numbrs and som constructions of th Cantor st, and yids th sam topoogy.
5.5 tring datatyps
A string datatyp is a datatyp modd on th ida of a forma string. trings
ar such an important and usfu datatyp that thy ar impmntd in nary v
ry programming anguag. In som anguags thy ar avaiab as primitiv typ
s and in othrs as composit typs. Th syntax of most high-v programming a
nguags aows for a string, usuay quotd in som way, to rprsnt an instanc
 of a string datatyp; such a mta-string is cad a itra or string itra
.
5.6 tring ngth
Athough forma strings can hav an arbitrary (but finit) ngth, th ngth of
strings in ra anguags is oftn constraind to an artificia maximum. In gn
ra, thr ar two typs of string datatyps: fixd ngth strings which hav a
fixd maximum ngth and which us th sam amount of mmory whthr this maxim
um is rachd or not, and variab ngth strings whos ngth is not arbitrari
y fixd and which us varying amounts of mmory dpnding on thir actua siz.
Most strings in modrn programming anguags ar variab ngth strings. Dspit
 th nam, vn variab ngth strings ar imitd in ngth; athough, gnra
y, th imit dpnds ony on th amount of mmory avaiab.
5.7 tring Rprsntations
Rprsntations of strings dpnd haviy on th choic of charactr rprtoir
and th mthod of charactr ncoding. Odr string impmntations wr dsignd
to work with rprtoir and ncoding dfind by ACII, or mor rcnt xtnsion
s ik th IO 8859 sris. Modrn impmntations oftn us th xtnsiv rpr
toir dfind by Unicod aong with a varity of compx ncodings such as UTF-8
and UTF-16. Most string impmntations ar vry simiar to variab-ngth arr
ays with th ntris storing th charactr cods of corrsponding charactrs. Th
 principa diffrnc is that, with crtain ncodings, a sing ogica charact
r may tak up mor than on ntry in th array. This happns for xamp with U
TF-8, whr sing charactrs can tak anywhr from on to four byts. In ths
cass, th ogica ngth of th string diffrs from th ogica ngth of th
array. Th ngth of a string can b stord impicity by using a spcia trmin
ating charactr; oftn this is th nu charactr having vau zro, a convntio
n usd and prptuatd by th popuar C programming anguag[1]. Hnc, this rp
rsntation is commony rfrrd to as C string. Th ngth of a string can aso
b stord xpicity, for xamp by prfixing th string with th ngth as a
byt vau a convntion usd in Pasca; consqunty som pop ca it a P-str
ing. In trminatd strings, th trminating cod is not an aowab charactr i
n any string. Th trm bytstring usuay indicats to strings of byts rathr t
han bits or th widr concpt of charactrs, which may tak mor spac than a by
t that ar not trminatd in this way, and in byts may tak any vau.

Hr is an xamp of a nu-trminatd string stord in a 10-byt buffr, aong


with its ACII rprsntation: F R A N K NUL k 4 52 41 4E 4B 00 6  f w
6B 66 66 77
Th ngth of a string in th abov xamp is 5 charactrs, but it occupis 6 b
yts. Charactrs aftr th trminator do not form part of th rprsntation; th
y may b ithr part of anothr string or just garbag. (trings of this form a
r somtims cad ACIZ strings, aftr th origina assmby anguag dirctiv
 usd to dcar thm.)
Hr is th quivant (od sty) Pasca string stord in a 10-byt buffr, ao
ng with its ACII rprsntation: F R A N K k  f w

ngth
05
46 52 41 4E 4B 6B 66 66 77
Both charactr trmination and ngth cods imit strings: for xamp, C charac
tr arrays that contain Nu charactrs cannot b handd dircty by C string i
brary functions: strings using a ngth cod ar imitd to th maximum vau of
th ngth cod. Both of ths imitations can b ovrcom by cvr programmin
g, of cours, but such workarounds ar by dfinition not standard. Historicay,
rough quivants of th C trmination mthod appar in both hardwar and softw
ar. For xamp "data procssing" machins ik th IBM 1401 usd a spcia wor
d mark bit to dimit strings at th ft, whr th opration woud start at th
 right. This mant that whi th IBM 1401 had a svn-bit word in "raity", a
most no-on vr thought to us this as a fatur, and ovrrid th assignmnt
of th svnth bit to (for xamp) hand ACII cods. It is possib to crat
data structurs and functions that manipuat thm that do not hav th probm
s associatd with charactr trmination and can in princip ovrcom ngth cod
 bounds. It is aso possib to optimiz th string rprsntd using tchniqu
s from run ngth ncoding (rpacing rpatd charactrs by th charactr vau
and a ngth) and Hamming ncoding. Whi ths rprsntations ar common, oth
rs ar possib. Using rops maks crtain string oprations, such as insrtion
s, dtions, and concatnations mor fficint.
5.8 tring as Vctors

Whi charactr strings ar vry common uss of strings, a string in computr sc
inc may rfr gnricay to any vctor of homognousy typd data. A string o
f bits or byts, for xamp, may b usd to rprsnt data rtrivd from a com
munications mdium. This data may or may not b rprsntd by a string-spcific
datatyp, dpnding on th nds of th appication, th dsir of th programm
r, and th capabiitis of th programming anguag bing usd.
5.9 tring procssing agorithms
Thr ar many agorithms for procssing strings, ach with various trad-offs.
om catgoris of agorithms incud string sarching agorithms for finding a
givn substring or pattrn; string manipuation agorithms; sorting agorithms;
rguar xprssion agorithms; and parsing a string.
Advancd string agorithms oftn mpoy compx mchanisms and data structurs,
among thm suffix trs and finit stat machins.
5.9.1 tring sarching agorithms
tring sarching agorithms, somtims cad string matching agorithms, ar an
important cass of string agorithms that try to find a pac whr on or sv
ra strings (aso cad pattrns) ar found within a argr string or txt. Lt
b an aphabt (finit st). Formay, both th pattrn and sarchd txt ar c
oncatnations of mnts of . Th may b a usua human aphabt (for xamp, th
 ttrs A through Z in Engish). Othr appications may us binary aphabt ( =
{0,1}) or DNA aphabt ( = {A,C,G,T}) in bioinformatics. In practic how th str
ing is ncodd can affct th fasib string sarch agorithms. In particuar i
f a variab width ncoding is in us thn it is sow (tim proportiona to N) t
o find th Nth charactr. This wi significanty sow down many of th mor adv
ancd sarch agorithms. A possib soution is to sarch for th squnc of co
d units instad, but doing so may produc fas matchs unss th ncoding is
spcificay dsignd to avoid it. 5.9.1.1 Basic cassification Th various tri
ng agorithms can b cassifid by th numbr of pattrns ach uss. 5.9.1.2 in
g pattrn agorithms Lt m b th ngth of th pattrn and t n b th ngt
h of th sarchab txt. Agorithm Nativ string sarch agorithm Prprocssing
tim Matching tim1 0 (no prprocssing) (n m)

Rabin-Karp string sarch agorithm


(m)
avrag (n+m), worst (n m) (n) (n) (n/m), O(n) (n)
Finit stat automaton basd sarch Knuth-Morris-Pratt agorithm Boyr-Moor str
ing sarch agorithm Bitap agorithm (shift-or, shift-and, Baza-Yats-Gonnt)
(m ||) (m) (m + ||) (m + ||)
Th BoyrMoor string sarch agorithm has bn th standard bnchmark for th pr
actica string sarch itratur. 5.9.1.3 Agorithms using finit st of pattrn
s Aho-Corasick agorithm Commntz-Watr agorithm Rabin-Karp string sarch ago
rithm
5.9.1.4 Agorithms using infinit numbr of pattrns Naturay, th pattrns can
not b numratd in this cas. Thy ar rprsntd usuay by a rguar gramm
ar or rguar xprssion.
5.9.2 tring manipuation agorithms or tring Functions
tring functions ar usd to manipuat a string or chang or dit th contnts
of a string. Thy aso ar usd to qury information about a string. Thy ar us
uay usd within th contxt of a computr programming anguag. Th most basic
xamp of a string function is th ngth(string) function, which rturns th
ngth of a string (not counting any trminator charactrs or any of th string'
s intrna structura information) and dos not modify th string. For xamp,
ngth("ho word") rturns 11. Thr ar many string functions which xist in
othr anguags with simiar or xacty th sam syntax or paramtrs. For xam
p in many anguags th ngth function is usuay rprsntd as n(string).
Evn though string functions ar vry usfu to a computr programmr, a comput
r programmr using ths functions shoud b mindfu that a string function in
on anguag coud in anothr anguag bhav diffrnty or hav a simiar or c
ompty diffrnt function nam, paramtrs, syntax, and rsuts. Popuar tri
ng Functions usd in C and thir jobs ar givn bow: 1. char *strcpy( char *s1
, const char *s2)


copis th string s2 into th charactr array s1. Th bas addrss of s1 is rtu
rnd.
2. char *strncpy( char *s1, const char *s2, int n)

copis at most n charactrs of th string s2 into th charactr array s1. Th ba
s addrss of s1 is rturnd.
3. char *strcat( char *s1, const char *s2)

appnds th string s2 to th nd of charactr array s1. Th first charactr from
s2 ovrwrits th '\0' of s1. Th bas addrss of s1 is rturnd.
4. char *strncat( char *s1, const char *s2, int n)

appnds at most n charactrs of th string s2 to th nd of charactr array s1.
Th first charactr from s2 ovrwrits th '\0' of s1. Th bas addrss of s1 is
rturnd.
5. char *strchr( const char *s, int c)

rturns a pointr to th first instanc of c in s. Rturns a NULL pointr if c i


s not ncountrd in th string.
6. char *strrchr( const char *s, int c)

rturns a pointr to th ast instanc of c in s. Rturns a NULL pointr if c is


not ncountrd in th string.
7. int strcmp( const char *s1, const char *s2)

compars th string s1 to th string s2. Th function rturns 0 if thy ar th
sam, a numbr < 0 if s1 < s2, a numbr > 0 if s1 > s2.
8. int strncmp( const char *s1, const char *s2, siz_t n)

compars up to n charactrs of th string s1 to th string s2. Th function rtu
rns 0 if thy ar th sam, a numbr < 0 ifs1 < s2, a numbr > 0 if s1 > s2.
9. int strspn( char *s1, const char *s2)

rturns th ngth of th ongst substring of s1 that bgins at th start of s1
and consists ony of th charactrs found in s2.
10. int strcspn( char *s1, const char *s2)

rturns th ngth of th ongst substring of s1 that bgins at th start of s1
and contains non of th charactrs found in s2.

11. int strn( const char *s) dtrmins th ngth of th string s. Rturns th
 numbr of charactrs in th string bfor th '\0'.

12. char *strpbrk( const char *s1, const char *s2)

rturns a pointr to th first instanc in s1 of any charactr found in s2. Rtu
rns a NULL pointr if no charactrs from s2 ar ncountrd in s1.
13. char *strstr( const char *s1, const char *s2)

rturns a pointr to th first instanc of string s2 in s1. Rturns a NULL point
r if s2 is not ncountrd in s1.
14. char *strtok(char *s1, const char *s2)

rpatd cas to this function brak string s1 into "tokns"--that is th strin
g is brokn into substrings, ach trminating with a '\0', whr th '\0' rpac
s any charactrs containd in string s2. Th first ca uss th string to b t
oknizd as s1; subsqunt cas us NULL as th first argumnt. A pointr to th
 bginning of th currnt tokn is rturnd; NULL is rturnd if thr ar no m
or tokns.
5.9.3 tring orting agorithms
In computr scinc and mathmatics, a sorting agorithm is an agorithm that pu
ts mnts of a ist in a crtain ordr. Th most-usd ordrs ar numrica ord
r and xicographica ordr. Efficint sorting is important to optimizing th u
s of othr agorithms (such as sarch and mrg agorithms) that rquir sortd
ists to work corrcty; it is aso oftn usfu for canonicaizing data and fo
r producing human-radab output. Mor formay, th output must satisfy two co
nditions: Th output is in incrasing or dcrasing ordr (ach mnt is no sm
ar/gratr than th prvious mnt according to th dsird tota ordr); T
h output is a prmutation, or rordring, of th input.
Wknown orting Agorithms ar as foows: 1. 2. 3. 4. 5. 6. 7. Bubb ort In
srtion ort ction ort Mrg ort uick ort Hap ort Radix ort
This wknown sort agorithms ar discussd in dtais in chaptr 12.
5.9.4 Rguar Exprssion Agorithms
In computing, rguar xprssions provid a concis and fxib mans for idnt
ifying strings of txt of intrst, such as particuar charactrs, words, or pat
trns of charactrs. Rguar xprssions (abbrviatd as rgx or rgxp, with p
ura forms rgxs, rgxps, or rgxn) ar writtn in a forma anguag that
can b intrprtd by a rguar xprssion procssor, a program that ithr srv
s as a parsr gnrator or xamins txt and idntifis parts that match th pr
ovidd spcification.W wi not discuss this agorithms as this part is byond
th scop of this book.

5.9.5 Parsing a tring


In computr scinc and inguistics, parsing (mor formay: syntactic anaysis)
is th procss of anayzing a squnc of tokns to dtrmin grammatica struc
tur with rspct to a givn (mor or ss) forma grammar. A parsr is thus on
of th componnts in an intrprtr or compir, whr it capturs th impid
hirarchy of th input txt and transforms it into a form suitab for furthr p
rocssing (oftn som kind of pars tr, abstract syntax tr or othr hirarch
ica structur) and normay chcks for syntax rrors at th sam tim.
5.11 tring Impmntations
om anguags ik C impmnt strings as tmpats that can b usd with any p
rimitiv typ, but this is th xcption, not th ru. If an objct-orintd a
nguag rprsnts strings as objcts, thy ar cad mutab if th vau can c
hang at runtim and immutab if th vau is frozn aftr cration. For xamp
, Ruby has mutab strings, whi Python's strings ar immutab. Othr anguag
s, most notaby Proog and Erang, avoid impmnting a string datatyp, insta
d adopting th convntion of rprsnting strings as ists of charactr cods. A
gorithms of som popuar string functions: Agorithm mytrn(s1) // Purpos :
This agorithm dtrmins th ngth of th string. // Input : tring s1. // Out
put : Rturns th numbr of charactrs in th string s1 bfor th '\0'. { iLng
th = 0; whi(*s1!=\0) { iLnght++; s1++; } rturn iLngth; }// End of Algorithm.
Algorithm myStrcy(s1,s2) // Puros : This algorithm cois a string into a cha
ractr array. // Inut : s1 is th string and s2 is a charactr array. // Outut
: Non. { whil(*s1!=\0) { s2[iCountr] = *s1; iCountr++; s1++; } s2[iCountr] =
*s1; }// End of Algorithm Algorithm myStrcat(s1,s2) // Puros : This algorithm
ands th string to th nd of charactr array.

// Inut : s1 is th string and s2 is a charactr array. // Outut : Non. { iL


ngth = myStrln(s2); whil(*s1!=\0) { s2[iLngth] = *s1; iLngth++; s1++; } }// En
d of Algorithm Algorithm myStrcm(s1,s2) // Puros : This algorithm comars tw
o strings. // Inut : s1 and s2 ar th string. // Outut : Th algorithm rturn
s 0 if thy ar th sam, a numbr < 0 if s1 < s2, a numbr > 0 if s1 > s2. { St
ring1 = s1; String2 = s2; whil(*String1!=\0 && * String2!=\0) { if(*String1!=* Stri
ng2) brak; String1 ++; String2 ++; } if(*s1 == \0 && *s2==\0) rturn 0; ls rturn
(myStrln(s1) myStrln(s2)); }// End of Algorithm
MCQ Chatr 5
1. Th null charactr is rrsntd by (a) \n (b) \0 (c) NULL (d) \r 2.
l charactr nds a sac of (a) zro byts (b) on byt (c) thr byts
r byts 3. Whn w concatnat two string of siz m and n, th rsultant
will b of siz (a) m + n (b) lss than m + n (c) m * n (d) max(m, n) 4.
an instanc of a String of lngth l, in anothr string of lngth m, th
orrus Pratt algorithms tim is roortional to (at worst cas) (a) m
c) l (d) m * l

Th nul
(d) fou
string
To find
Kunth M
+ l (b) m (

5. Which string oration is not availabl in C? (a) Concatnation (b) Pattrn M


atching (c) Rvrsing th string (d) non of ths 6. String concatnation mans
(a) Combining two strings (b) Extracting to substring out of a string (c) Parti
tioning a string (d) Non of ths 7. Pattrn matching rfrs to (a) finding os
ition whr a string attrn P first aars in a givn string (b) Chcking wht
hr two strings ar idntical (c) Chcking whthr a attrn occurs in a givn
string (d) Non of ths 8. Macro xansion of C is an xaml of (a) String mat
ching and maniulation (b) Alication of hashing for a ractical rogram (c) St
ring oration which dos not rquir string matching (d) Non of ths 9. In C
strings ar stord in (a) Linkd list of charactr (b) Linkdlist of usignnd ch
aractr (c) Array of charactr (d) array of intgr 10. Problm of garbag coll
ction ariss with which mthod of string rrsntation? (a) Fixd lngth mthod
(b) Indx tabl mthod (c) Linkd list mthod (d) Non of ths 11. String Homo
morhism is on kind of (a) String Substitution (b) String Concatnation (c) Par
titioning a string (d) String matching 12. String Projction is on kind of (a)
String Substitution (b) String Concatnation (c) String rrsntation (d) Strin
g matching 13. String right cancllation is on kind of (a) String Substitution
(b) String Concatnation (c) String rrsntation

(d) String matching 14. Strln() function rturns


lu (c) charctr valu (d) Non of ths 15. Byt
bits (b) array of Byts (c) array of chatractrs
function rturns (a) Charactr valu (b) intgr
n of ths

(a) intgr valu


String is mad of
(d) non of ths
valu (c) ointr

(b) float va
(a) array of
16. Strcat()
valu (d) No

Solutions:
1. b 16. c 2. b 3. b 4. a 5. c 6. a 7. c 8. a 9. c 10. b 11. a 12. c 13. a 14. a
15.b
Exrcis Chatr 5
1. What is a string? How can it b imlmntd in C? 2. Giv som data structur
which is usd to imlmnt string. Which of ths is th bst and why? 3. Writ
an Algorithm to insrt a string x to a mastr string X. Us data structur of y
our choic suitably. 4. Writ an algorithm to concatnat btwn two strings st
r1 and str2. Us array to rrsnt sting. 5. It is rquird to find a string s
in a txt . writ an algorithm and a C rogram to imlmnt that. 6. Considr a
string X=abcd. List all substrings of X. writ a C function to comut all th s
ubstrings from a givn string. 7. Chck a string W=abccba if it is a alindrom st
ring. Writ a C rogram to find if a string is a alindrom or not. 8. Writ a C
rogram to collct th garbag valu from a string i. to collct th unusd o
rtion of a string. Us both array and linkd list rrsntations 9. What will b
 th string stord in th nxt figur? Char
link

1 2 3 4 5 6 7 8 9 10 11 12
Rad Lov W Data Structur To NULL
7 11 2 9 12 1 Start 10. Writ a C rogram to comut if a string is a articular
ty X x Y whr X is a arbitrary string of 0 and 1, Y is th rvrs of X and x
is any charactr valu. (Ex0110a0110, 110b011)
Chatr - 6 STACK
6.1 Dfinition
A stack is a linar data structur in which insrtion of nw data lmnt and d
ltion of xisting data lmnt is don from only on nd, calld to of th sta
ck. As all th insrtion and dltion orations ar don from on nd of th st
ack, th last insrtd itm will b dltd first. That is why stack is calld L
IFO (Last In First Out) list or FILO (First In Last Out) list. In our daily lif
, a common modl of such structur is a il of lats or a stack of coins.
6.2
Basic Orations
Th followings ar th basic orations associatd with a stack: 1) fnInitializ
(S): Initializ th stack S. 2) fnPush(S, iData): Insrt th lmnt iData on to
 of th stack S. 3) fnPo(S): Dlt th to most itm from th stack S and rt
urn th rmovd itm. 4) fnFull(S): This function chcks whthr th stack S is
full or not. To indicat S is full this function rturns TRUE and FALSE othrwis
. During PUSH oration Full(S) condition should b chckd if thr is any rs
triction on th maximum numbr of lmnts in th stack. Gnrally if w imlm
nt th stack using array thn stack full condition is chckd. But in cas of im
lmntation of stack using dynamic mmory allocation such ty of chcking is n
ot ndd at all as hr w can insrt any numbr of data in th stack. 5) fnEm
ty(S): This is also a Boolan function and rturns TRUE for mty stack and FALS
E for nonmty stack. During POP oration Emty(S) condition is chckd. fnPush
(S, 10) fnFull(S) rturns FALSE 15 10 fnPo(S) fnEmty(S) rturns 10 10 fnPush(S
, 15) fnFull(S) rturns FALSE fnPo(S) fnEmty(S) rturns 15 10 fnPush(S, 5) fnF
ull(S) rturns TRUE fnPo(S) fnEmty(S) rturns 15 10

FALSE
FALSE
TRUE
Figur 6.1: PUSH and POP orations on a Stack S
6.3
Imlmntation of stack using array
In this sction w will crat a stack of intgrs using array. For this uros
an intgr array arrSTACK of siz MAXSIZE may b usd and th array dclaration
is: int arrSTACK[MAXSIZE]; Hr to is global intgr variabl and th initial
valu of to is -1. From th array dclaration th maximum valu of to may b M
AXSIZE. So, to = MAXSIZE indicats stack is full and to = -1 indicats stack i
s mty. Algorithm for PUSH oration on th stack Algorithm fnPush( arrSTACK[],
iData) //Puros : This algorithm insrts an itm into th stack. //Inut : arr
STACK[] is th array in which th data itm iData is to b insrtd. //Outut :
Non { if(fnFull() == TRUE) // Chcking for stack full condition. stack is full;
ls { to = to + 1; // Incras th currnt lngth of th stack.. arrSTACK[to
] = iData; // insrt th itm iData. } }//End of Algorithm Algorithm for POP o
ration from th stack Algorithm fnPo(arrSTACK[]) //Puros : This algorithm d
lts th to lmnt from th stack. // Inut : Th array arrSTACK[] on which t
h stack is bing imlmntd. //Outut : Th to most itm iData that has bn
dltd. { if(fnEmty() == TRUE) //Chcking for stack mty condition. stack is
mty; ls { iData = arrSTACK[to] // itm dltd. to = to 1; // Shortn th
currnt lngth of th stack. rturn iData; // Rturn th valu of th itm that
has bn dltd. } }//End of Algorithm Rmmbr: During a POP oration, th i
tm is not dltd from th array, but currnt lngth of th stack is rducd by
dcrmnting to. Suos th valu of MAXSIZE is 2. Now considr th following
squnc of ush and o orations: Initially th valu of to is -1. fnPUSH(a
rrSTACK[],25) 1 fnPUSH(arrSTACK[],15) 1 15 to fnPOP(arrSTACK[]) 1 15

0
25
to
0
25
0
25
to
arrSTACK[0] = 25
arrSTACK[1] = 15
rturn 15
Now in this situation, on mor ush oration will ovrwrit th valu of arrST
ACK[1]. fnPUSH(arrSTACK[],20) 1 0 20 25 to
arrSTACK[1] = 20 Algorithm to dislay th lmnts of th stack Stack lmnts r
sid in th rang from 0 to to of th array. So it is rquird to dislay th
lmnts of th array from indx 0 to indx to. Algorithm fnDislay(arrSTACK[])
// Puros : This algorithm shows th lmnts of th stack. // Inut : arrSTAC
K[] is th nam of th stack. // Outut : Non. { if(fnEmty() == TRUE) // If st
ack is mty. Thr is nothing to dislay; ls for(iCountr=0;iCountr<=to;iCo
untr++) rint arrSTACK[iCountr]; }// End of Algorithm
Algorithm for chcking th stack full condition Th stack is full if th valu o
f to rachs MAXSIZE - 1 i.. th maximum siz of th stack. Algorithm fnFull()
// Puros : This algorithm chcks whthr th stack is full or not. // Inut :
Non. // Outut : This algorithm rturns TRUE if stack is full and rturns FALS
E if stack is not full. { if (to == MAXSIZE - 1) rturn TRUE; ls rturn FALSE
}// End of Algorithm
Algorithm for chcking th stack mty condition Th stack is mty if th valu
of to rachs -1. Algorithm fnEmty() // Puros : This algorithm chcks whth
r th stack is mty or not. // Inut : Non.

// Outut : This algorithm rturns TRUE if stack is mty and rturns FALSE if s
tack is not mty. { if (to == -1) rturn TRUE; ls rturn FALSE }// End of Al
gorithm
6.4
Imlmntation of stack using dynamic mmory allocation
If w imlmnt stack using array, thn insrtion of nw data lmnts may caus
an ovrflow and so th stack full condition is to b chckd during ach ush o
ration. But stack using dynamic mmory allocation dos not dmand to chck th
stack full condition in ach ush oration as hr w can insrt any numbr of
data lmnts dnding uon th availabl mmory. Figur 6.2 shows a stack usi
ng dynamic mmory allocation: NULL trTo Figur 6.2: Stack using dynamic mmory
allocation Each nod of th abov list has two filds: data fild and ointr f
ild. Data fild contains th data lmnt and th ointr fild contains th ad
drss of th nxt nod in th list. So from th conct of slf rfrntial stru
ctur th structur dfinition of such a nod is: struct Nod { int iData; struc
t Nod *trNxt; }; tydf struct Nod StackNod; Hr, to is a StackNod ty
ointr variabl and initially th valu of to is NULL indicating that th lis
t is mty. StackNod *to = NULL; Algorithm for Push Oration on th stack Alg
orithm fnPush(iData) // Puros : This algorithm insrts an itm on th to th
stack. // Inut : Th itm iData that is to b insrtd into th stack. // Outu
t : Non. { StackNod *trNwNod; // Assign a ointr to nw nod. trNwNod =
(StackNod*) malloc(sizof(StackNod)); //Crat th nw nod. trNwNod->iDat
a = iData; //Load th data fild of th nwly cratd nod. trNwNod->trNxt
= to; // Now nw nod will oint to th currnt to nod. to = trNwNod; //N
w nod is now th to nod of th list. }// End of Algorithm Algorithm for Po
Oration from th stack Algorithm fnPo()

// Puros : This algorithm dlts an itm from th to of th stack. // Inut
: Non. // Outut : Th itm iData that has bn dltd. { StackNod *trDlt
Nod; if(fnEmty() == TRUE) //Chck th stack mty condition. Stack is Emty; 
ls { iData = to->iData; // Th itm to b dltd. trDltNod = to; //St
th ointr to th nod to b dltd. to = to->trNxt; //St th nw valu o
f to. fr(trDltNod); //Fr th nod that has bn dltd. rturn(iData)
; //Rturn th data of th dltd nod. } }// End of Algorithm Algorithm to dis
lay th lmnts of th stack Algorithm fnDislay() // Puros : This algorithm
dislays th itms of th stack. // Inut : Non. // Outut : Non. { StackNod
*trDislayNod; if(fnEmty() == TRUE) //Chck stack mty condition. Thr is
nothing to dislay; ls { trDislayNod = to; //Initializ th ointr to to
nod. whil(trDislayNod!=NULL) //Until list is mty. { rint (trDislayNod
->iData); //Print th data. trDislayNod = trDislayNod -> trNxt; //Go to
nxt nod. } } }// End of Algorithm Algorithm for chcking th stack mty cond
ition Algorithm fnEmty() // Puros : This algorithm chcks whthr th stack i
s mty or not. // Inut : Non. // Outut : This algorithm rturns TRUE if stac
k is mty and rturns FALSE if stack is not mty. { if (to == NULL) rturn TR
UE; ls rturn FALSE }// End of Algorithm Examl: Suos w want to crat a
stack using dynamic mmory allocation. Th following statmnts show how th dif
frnt orations ar rformd on th stack. Initially th valu of to is NULL
.

Statmnt 1: fnPush(20) Statmnt 2: fnPush(25) Statmnt 3: fnPo() Statmnt 4


: fnPush(15) Statmnt 5: fnPo()
20 to 25 to 20 to 15 to 20 to
NULL 20 NULL
NULL
20
NULL
NULL
6.5
Arithmtic Exrssions
An xrssion is dfind as combination of som orands and orators. Basicall
y thr tys of notation for an xrssion ar availabl and th notations ar
as follows: 1) Infix Notation: In this notation orators ar writtn in btwn
th orands. Th xrssion to multily two numbrs X and Y is writtn in infi
x notation as: X*Y 2) Prfix Notation: In this notation orators ar writtn b
for th orands. Prfix notation is also calld olish notation as th olish
mathmatician Jan Lukasiwicz dvlod this notation. Th xrssion to multil
y two numbrs X and Y is writtn in rfix notation as: *XY 3) Postfix Notation:
In this notation orators ar writtn aftr th orands. This notation is als
o calld th rvrs olish notation. Th xrssion to multily two numbrs X a
nd Y is writtn in ostfix notation as: XY*
6.6
Convrting Infix xrssions to ostfix notation
For this convrsion, only th orators of th infix xrssion ar ushd onto
th stack according to th following rul: 1. If th riority of th stack to o
rator is gratr than or qual to th riority of th incoming orator thn t
h nw orator can not b ushd onto th stack. In othr words, th stack to
orator is to b od u until th riority of th stack to orator is lss
than th riority of th incoming orator. Th following tabl shows th ordr
of riority of som commonly usd orator: Orators Unary (-,+,!,log, sin tc
.) ,^ (Exonntiation Orator), $ *, / +,<,<=,>,>=,!= Priority 5 4 3 2 1
Tabl 6.1: Priority of som commonly usd orator Hr a stack Ortstk is usd
to ush th orators of th infix xrssion I and a string P is usd to stor
th quivalnt ostfix notation. Th orands of I ar dirctly addd to P.

Examl 1: Convrt th following infix xrssion to its corrsonding ostfix n


otation: I = A+B*C/(D+E) St 1: First inut charactr is A, which is an orand
. So add A to P. P: A
Ortstk St 2: Scond inut charactr + is an orator. Th orator stack is 
mty. So ush + onto th stack. P: A
+ Ortstk
to
St 3: Third inut charactr B is an orand. So add B to P. P: AB
+ Ortstk
to
St 4: Nxt inut symbol * is an orator and th stack to orator is +. As 
riority of + is lss than th riority of *, ush * onto th orator stack with
out any o oration. P: AB
* + Ortstk
to

St 5: Nxt inut symbol C is an orand. So add C to P. P: ABC


* + Ortstk to
St 6: Nxt inut symbol / is an orator and th stack to orator is *. Th
riority of * is qual to th riority of /. So o * from orator stack and ad
d * to P P: ABC*
+ Ortstk
to
Now th riority of th stack to orator (+) is lss than th riority of th
currnt symbol /. So, no mor o oration taks lac. Push / onto th orato
r stack.
/ + Ortstk
to
St 7: Nxt inut symbol is (. Push ( onto th stack. P: ABC* ( / + to

Ortstk St 8: Nxt inut charactr D is an orand. So add D to P. P: ABC*D (


/ + Ortstk to
St 9: Nxt inut symbol is + which is an orator and th stack to lmnt is
(. So thr is no nd to comar th rioritis of orator. Push + onto th s
tack. P: ABC*D + ( / + Ortstk St 10: Nxt inut symbol E is an orand. So ad
d E to P. P: ABC*DE + to ( / + Ortstk St 11: Now th last inut symbol is ).
So o all th orators from th orator stack until a lft arnthsis ( is
ncountrd. P: ABC*DE+ ( / + Ortstk to to

Now o ( from th stack, but dont add it to P.


/ + Ortstk
to
St 12: End of xrssion. So o orators from th orator stack until stack
is mty and add th symbols to P. Finally, P: ABC*DE+/+ Algorithm to convrt a
n infix xrssion to ostfix notation: Algorithm fnInfixToPostfix (I, P) // Pur
os : This algorithm finds th ostfix notation of an infix xrssion. // Inu
t : I is an arithmtic xrssion in infix notation. P is th quivalnt ostfix
notation. // Outut : Non. // Commnts : Ortstk is th orator stack. { whil
(not nd of I) { symbol = nxt inut charactr from I; if(symbol is an orand)
Add it to P; lsif(symbol is an orator) { whil(fnTo(Ortstk)>=symbol and !
Emty(Ortstk) and fnTo(Ortstk)!=() { n = o(Ortstk); add n to P; } ush(Orts
tk , symbol); } lsif(symbol is () ush(Ortstk , symbol); ls // right arnth
sis is ncountrd. { whil(Ortstk[to] != ( ) //Po from stack until lft arnt
hsis is ncountrd. { n = o(Ortstk); add n to P; } n = o(Ortstk); //only
o lft arnthsis (. Dont add it to P. } }// nd of whil whil(not stack mty
) {

n = o(Ortstk); add n to P; } }// End of algorithm Examl 2: Find ostfix not


ation for A$B*C-D+E/F*(G+H) Solution: Symbol Scann d A $ B * C D + E / F * ( G
+ H ) End Commnts A is an orand. Add A to P. Stack is mty. So ush $ onto s
tack. B is an orand. Add B to P. Priority($) > Priority(*). So o $ from stac
k and add it to P. Thn ush * onto th stack. C is an orand. Add C to P. Prio
rity(*) > Priority(-). So o * from stack and add it to P. Thn ush onto th s
tack. D is an orand. Add D to P. Priority(-) = Priority(+). So o from stack
and add it to P. Push + onto stack. E is an orand. Add E to P. Priority(+)<Pri
ority(/). So no o oration taks lac. Push / onto stack. F is an orand. A
dd F to P. Priority(/) = Priority(*). So o / and add / to P. Push * onto stack
. Push ( onto th stack. G is an orand and add G to P. Push + onto stack. H is
an orand. Add it to P. Po all th lmnts from th stack until ( is ncount
rd and xcut on mor o oration to dlt ( from th stack. Po all th
lmnts from th stack until stack is mty. Stack Contnts Emty $ $ * * + + +
/ +/ +* +*( +*( +*(+ +*(+ +* Emty Postfix Exrssion (P) A A AB AB$ AB$C AB$C*
AB$C*D AB$C*DAB$C*D-E AB$C*D-E AB$C*D-EF AB$C*D-EF/ AB$C*D-EF/ AB$C*D-EF/G AB$C*
D-EF/G AB$C*D-EF/GH AB$C*D-EF/GH+ AB$C*D-EF/GH+*+
Examl 3: Find ostfix notation for A+B*logC/D Solution: Symbol Commnts Scann
d A + B * log A is an orand. Add A to P. Push + onto stack. B is an orand. A
dd it to P. Priority(+)<Priority(*). So no o oration. Push * onto th stack.
Priority(*)<Priority(log). So no o oration. Push log onto th stack.
Stack Contnts Emty + + +* + * log
Postfix Exrssion (P) A A AB AB AB

C /
D End
C is an orand. Add C to P. Priority(log)>Priority(/). Po log and add it to P.
Again, Priority(*)=Priority(/). Po * and add * to P. Now Priority(+) < Priorit
y(/). So no mor o oration. Push / onto th stack. D is an orand. Add D to
P. Po all th lmnts from stack until it is mty.
+ * log +/
ABC ABClog*
+/ Emty
ABClog*D ABClog*D/+
6.7
Convrting Infix xrssion to rfix notation
Rul for o oration from th orator stack: 1. If th riority of th stack
to orator is gratr than th riority of th incoming orator thn th nw
orator can not b ushd onto th stack. In othr words th stack to orator
is to b od u until th riority of th stack to orator is lss than or
qual to th riority of th incoming orator. Examl 1: Convrt th followin
g infix xrssion to its corrsonding rfix notation: I = A+B*C/(D+E) Solutio
n: First tak th rvrs of I. I = rvrs(I) = (E+D)/C*B+A St 1: First inut
charactr is (. Push ( onto orator stack. P:
( Ortstk
to
St 2: Scond inut charactr E is an orand. So add E to P. P: E
( Ortstk
to
St 3: Third inut charactr + is an orator. Push + onto stack. P: E
+

to ( Ortstk St 4: Nxt inut symbol D is an orand. So add D to P. P: ED


+ ( Ortstk
to
St 5: Nxt inut symbol is ). So o all th orators from th stack until a
lft arnthsis is ncountrd and add thm to P. P: ED+
( Ortstk Now o ( from th stack, but dont add it to P.
to
P: ED+
Ortstk St 6: Nxt inut symbol / is an orator and th stack is now mty. P
ush / onto th stack. P: ED+

/ Ortstk
to
St 7: Nxt inut symbol C is an orand. Add C to P. P: ED+C
/ Ortstk
to
St 8: Nxt inut charactr * is an orator. Priority(/) = Priority(*). So us
h * onto stack without any o oration. P: ED+C
* /
to
Ortstk St 9: Nxt inut symbol is B which is an orand. Add B to P. P: ED+CB
* / Ortstk
to
St 10: Nxt inut symbol + is an orator. Priority(*) > Priority(+). So o *
and add it to P. Now stack to orator is /. Again Priority(/) > Priority(+).
So o / and add it to P. Now Stack is mty. So ush + onto th stack without a
ny comarison. P: ED+CB*/

+ Ortstk
to
St 11: Now th last inut symbol A is an orand. Add A to P. P: ED+CB*/A
+ Ortstk
to
St 12: End of xrssion. So o orators from th orator stack until stack
is mty and add th symbols to P. P: ED+CB*/A+ Finally P = rvrs(P) = +A/*BC+D
E Algorithm to convrt infix xrssion to rfix notation: Algorithm fnInfixToP
rfix(I,P) // Puros : This algorithm finds th rfix notation of an infix x
rssion. // Inut : I is an arithmtic xrssion in infix notation. P is th q
uivalnt rfix notation. // Outut : Non. // Commnts : P = rvrs(P) and I = r
vrs(I). Ortstk is th orator stack. { whil(not nd of I) { Symbol = Nxt i
nut charactr of I; if(Symbol is an orand) Add it to P; lsif(Symbol is an o
rator) { whil(Ortstk[to] > Symbol and !Emty(Ortstk) and Ortstk[to]!=() { n
= o(Ortstk); add n to P; } ush(Ortstk , Symbol); } lsif(Symbol is () ush(O
rtstk , Symbol); ls // right arnthsis is ncountrd { whil(Ortstk[to] !
= ( ) //Po from stack until lft arnthsis is ncountrd

{ n = o(Ortstk); add n to P; } o(Ortstk); //only o (. Dont add it to P } } //


nd of whil whil(Emty(Ortstk)==FALSE) // Until Stack is mty { n = o(Or
tstk); add n to P; } P = rvrs(P); }// End of Algorithm Examl 2: Find rfix n
otation for A/B$C+ (D*E-log F) Solution: I = A/B$C+ (D*E-log F) I = Rvrs of I
= (log F E*D)+C$B/A Symbol Commnts Scann d ( Push ( onto th stack. log Push t
h unary orator log onto th stack. F F is an orand. Add F to P. Priority(log
) > Priority(-). So o log and add log to P. Push onto stack. E E is an orand.
Add E to P. * Priority(-) < Priority(*). So no o. Push * onto th stack. D D i
s an orand. Add D to P. ) Po * , - from stack and add thm to P. Thn o ( , b
ut dont add it to P. + Now stack is mty. Push + onto th stack. C C is an oran
d. Add C to P. $ Priority(+)<Priority($). So no o oration. Push $ onto stack.
B Add orand B to P. / Priority($)>Priority(/). So o $ from stack and add it
to P. Nxt, Priority(+) < Priority($). Hnc no mor o. Push / onto th stack.
A Add orand A to P. End Po all th lmnts from th stack until stack is mt
y. Finally, P = rvrs of P = +/A$BC-*DElogF
Stack Contnts ( ( log ( log (((-* (-* Emty + + +$ +$ +/ +/ Emty
Prfix Exrssion (P)
F Flog FlogE FlogE FlogED FlogED*FlogED*FlogED*-C FlogED*-C FlogED*-CB FlogED*-C
B$ FlogED*-CB$A Flog ED*-CB$A/+
6.8
Evaluating Postfix Exrssion
To valuat a ostfix xrssion an orand stack (Orndstk) is usd rathr than
an orator stack i.. hr th orands of th ostfix xrssions ar ushd
onto th stack. Examl 1: Evaluat th following ostfix xrssion: 234*+8 St
1: First inut lmnt is 2 which is an orand. So ush 2 onto th orand sta
ck.

2
to
Orndstk St 2: Nxt inut lmnt is 3 which is also an orand. So ush 3 ont
o th orand stack.
3 2
to
Orndstk St 3: Third inut lmnt 4 is again an orand. So ush 4 onto th o
rand stack.
4 3 2 Orndstk
to
St 4: Nxt inut symbol is * which is an orator. Now o two lmnts from t
h stack and calculat th rsult asrsult = Elmnt rturnd from th scond o
 oration * Elmnt rturnd from th first o oration =3*4 = 12. Now ush
th rsult 12 onto th orand stack.
12 2 Orndstk
to
St 5: Nxt + is also an orator. So rsult = 2 + 12 = 14. Push rsult onto th
 stack.

14 Orndstk
to
St 6: Nxt inut symbol is orand 8. Push 8 onto th orand stack.
8 14
to
Orndstk St 7: Nxt inut symbol is orator -. So comut th rsult as 14 -8
= 6 and ush 6 into th stack.
6 Orndstk
to
St 8: End of xrssion. So finally o th only lmnt from th stack and th
us 6 is th final rsult. Algorithm to valuat a ostfix xrssion: Algorithm
fnPostfixEvaluation (P,I) // Puros : This algorithm valuats a ostfix xrs
sion. // Inut : P is an arithmtic xrssion in ostfix notation. I is finally
calculatd rsult. // Outut : This algorithm rturns th rsult aftr valuati
ng th ostfix xrssion. // Commnts : Orndstk is th orand stack. { whil(
not nd of Q) { Symbol = Nxt inut charactr of P; if(Symbol == Orand) ush(O
rndstk, Symbol); ls { Orand2 = o(Orndstk); Orand1 = o(Orndstk);

Valu = rsult of alying Symbol to Orand1 and Orand2; ush(Orndstk, Valu


); } } I = o(Orndstk); rturn(I); }// End of Algorithm
6.9
Evaluating Prfix Exrssion
Hr also an orand stack is usd rathr than an orator stack. For this valu
ation, rvrs of th givn rfix xrssion is takn and scannd until th nd
of P to find th rsult. Examl 1: Evaluat th following rfix xrssion: P
=-+2*348 P = rvrs(P) = 8 4 3 * 2 + St 1: First inut lmnt is 8 which is a
n orand. So ush 8 onto th orand stack.
8 Orndstk
to
St 2: Nxt inut lmnt is 4 which is also an orand. So ush 4 onto th o
rand stack.
4 8
to
Orndstk St 3: Third inut lmnt is 3 which is an orand. So ush 3 onto th
 orand stack.
3 4
to

8 Orndstk St 4: Nxt inut symbol is * which is an orator. Now o two lm
nts from th stack and calculat th rsult asrsult = Elmnt rturnd from th
 first o oration * Elmnt rturnd from th scond o oration =3*4 = 12
. Now ush th rsult 12 onto th orand stack.
12 8
to
Orndstk St 5: Nxt inut symbol 2 is an orand. Push 2 onto th stack.
2 12 8 Orndstk St 6: Nxt inut symbol is orator +. So rsult = 2 + 12 = 14
. Push 14 onto th orand stack. to
14 8 Orndstk
to
St 7: Nxt inut symbol - is an orator. So comut th rsult as 14 -8 = 6 a
nd ush 6 onto th stack.

6 Orndstk
to
St 8: End of xrssion. So finally o th only lmnt from th stack and th
us 6 is th final rsult. Algorithm to valuat a rfix xrssion Algorithm fn
PrfixEvaluation (P, I) // Puros : This algorithm valuats a rfix xrssio
n. // Inut : P is an arithmtic xrssion in rfix notation. I is finally cal
culatd rsult. // Outut : This algorithm rturns th rsult aftr valuating t
h rfix xrssion. // Commnts : P = rvrs (P). Orndstk is orand stack. {
whil(not nd of P) { Symbol = Nxt inut charactr of P; if(Symbol == Orand) 
ush(Orndstk, Symbol); ls { Orand1 = o(Orndstk); Orand2 = o(Orndstk)
; Valu = Rsult of alying Symbol to Orand1 and Orand2; ush(Orndstk, Val
u); } } I = o(Orndstk); rturn(I); }// End of Algorithm
6.10 Alication of Stack
Th alications of stack ar as follows: 1. Rvrsing a string. 2. Chcking th
balancd arnthsis. 3. Convrsion from infix to ostfix and rfix xrssion
. 4. Evaluation of ostfix and rfix xrssion. 5. Simulating rcursion.
6.11 Rvrsing a string
Considr th string strNam[] = DATA. Now using stack, rvrs of th string strNa
m can b obtaind by xcuting th following squnc of statmnts. Aftr all
th ush orations, o th data until stack is mty. A to fnPush(arrSTACK[],
D) 3 strNam[0] = fnPo(arrSTACK[]) = A fnPush(arrSTACK[], A) strNam[1] = fnPo
(arrSTACK[]) = T T fnPush(arrSTACK[], T) 2 strNam[2] = fnPo(arrSTACK[]) = A f
nPush(arrSTACK[], A) strNam[3] = fnPo(arrSTACK[]) = D A 1 Now th string strNa
m contains rvrs of th original information. D 0

Algorithm to rvrs a string using stack Algorithm fnRvrs(strNam) // Puros


 : This algorithm rvrs a givn string. // Inut : strNam is th rquird st
ring. // Outut : Non. // Commnts : arrSTACK is a charactr array to imlmnt
th stack. { iCountr = 0; whil(strNam[iCountr]!=\0) //Until nd of string. {
fnPush(arrSTACK[], strNam[iCountr]); //Push th charactr into th stack. iCou
ntr = iCountr + 1; } iCountr = 0; whil(fnEmty() != TRUE) //Until th stack
is not mty. { strNam[iCountr] = fnPo(arrSTACK[]); //Po th charactr and s
tor into array strNam[]. iCountr = iCountr + 1; } }//End of Algorithm
6.12 Chcking balancd arnthsis
Suos a string arrExrssion[] = ((()())). Now w can chck asily by stack wht
hr th arnthsis is balancd or not. If lft arnthsis (() is ncountrd th
n ush it onto th stack. Whn a right arnthsis ()) is ncountrd thn o on
lft arnthsis from th stack. At th nd, if th stack is mty thn conclud
 that th arnthsis is balancd. Algorithm to chck balancd arnthsis Algo
rithm fnChck_balancd_arnthsis(arrExrssion) // Puros : This algorithm ch
cks balancd arnthsis. // Inut : arrExrssion is th rquird xrssion.
// Outut : This algorithm rturns TRUE if arnthsis is balancd and rturns F
ALSE othrwis. // Commnts : arrSTACK is a charactr array to imlmnt th sta
ck. { iCountr = 0; whil(strExrssion[iCountr]!=\0) //Until nd of string. { if
(strExrssion[iCountr] == () fnPush(arrSTACK[], strExrssion[iCountr]); //Push
( onto th stack. if(strExrssion[iCountr] == )) fnPo(arrStack[]); //Po ( from th
 stack. iCountr = iCountr + 1; } rturn(fnEmty()); //If stack is mty rtur
n TRUE othrwis rturn FALSE. }// End of Algorithm
6.13 Multil Stacks
W can imlmnt two stacks in th sam array whr on stack grows from lft to
right and othr from right to lft. Th valu of th to (to1) for th first s
tack is initializd from -1 and for th scond stack th to (to2) is

initializd from th MAXSIZE of th array. So to1 is incrmntd by 1 during th


 ush oration onto th first stack and in cas of ush oration onto th sc
ond stack, th valu of to2 is to b dcrmntd by 1. Stack 1 Stack 2
0
1
2
3
4
5
6
7
8
9
10
11
12
to1 Figur 6.3: Two stack using sam array
to2
For th two-stack of th figur 6.3 th initial valu of to1 is -1 and for to2
th initial valu is 13. Th stack full condition for two-stack is to2 = to1
+ 1. Stack mty condition for th first stack is to1 = -1 and for th scond s
tack th condition is to2 = MAXSIZE. Algorithm of insrtion into two-stack Algo
rithm fnPushTwoStack(iStackNo, idata) // Puros : This algorithm insrts an it
m into th two-stack. // Inut : iStackNo dnots th stack numbr. iData is th
data itm to b insrtd onto th ithr stack. // Outut : Non. // Commnts :
to1 (to of th first stack) is initializd from -1 and to2 (to of th scon
d stack) is initializd from MAXSIZE. { if (to2 == to1 + 1) Stack is full; ls
 { if (iStackNo == 1) { to1 = to1 + 1; arrStack[to1] = iData; } lsif (iSta
ckNo == 2) { to2 = to2 -1; arrStack[to2] = iData; } ls Invalid Stack numbr
; } }//End of Algorithm Algorithm of dltion from th two-stack Algorithm fnPo
TwoStack(iStackNo) // Puros : This algorithm dlts an itm from two-stack. /
/ Inut : iStackNo is th stack numbr from which th itm is to b dltd. //
Outut : Th itm iData which has bn dltd.

{ if (iStackNo == 1) { if(to1 == -1) First stack is mty; ls { iData = arrSt


ack[to1]; to1 = to1 - 1; rturn iData; } } lsif (iStackNo == 2) { if (to2
== MAXSIZE) Scond stack is mty; ls { iData = arrStack[to2]; to2 = to2 +
1; rturn iData; } } ls Invalid stack numbr; }// End of Algorithm
/****Imlmntation of stack using C****/ /****Fil nam : stack.c****/
#includ<stdio.h> #includ<conio.h> #dfin MAXSIZE 50 //Prototy Dclaration v
oid fnPush( int[], int ); int fnPo(int[]); void fnDislay(int[]); int fnFull();
int fnEmty(); int to=-1; void fnPush( int arrSTACK[], int iData) //Puros :
This function insrts an itm into th stack. //Inut : arrSTACK[] is th array
in which th data itm iData is to b insrtd. //Outut : Non { if(fnFull() ==
1) // Chcking for stack full condition. rintf("stack is full"); ls {

to = to + 1; arrSTACK[to] = iData; } }//End of function


// Incras th currnt lngth of th stack.. // insrt th itm iData.
int fnPo(int arrSTACK[]) //Puros : This function dlts th to lmnt from
th stack. // Inut : Th array arrSTACK[] on which th stack is bing imlmn
td. //Outut : Th to most itm iData that has bn dltd. { int iData; if(f
nEmty() == 1) //Chcking for stack mty condition. { //rintf("stack is mty"
); rturn -1; } ls { iData = arrSTACK[to]; // itm dltd. to = to - 1; //
Shortn th currnt lngth of th stack. rturn iData; // Rturn th valu of t
h itm that has bn dltd. } }//End of function void fnDislay(int arrSTACK[
]) // Puros : This function shows th lmnts of th stack. // Inut : arrSTA
CK[] is th nam of th stack. // Outut : Non. { int iCountr; if(fnEmty() ==
1) // If stack is mty. rintf("Thr is nothing to dislay"); ls for(iCount
r=0;iCountr<=to;iCountr++) rintf("%d\n",arrSTACK[iCountr]); }// End of fun
ction int fnFull() // Puros : This function chcks whthr th stack is full o
r not. // Inut : Non. // Outut : This function rturns TRUE if stack is full
and rturns FALSE if stack is not full. { if (to == MAXSIZE - 1) rturn 1; ls
rturn 0; }// End of function int fnEmty() // Puros : This function chcks w
hthr th stack is mty or not. // Inut: Non. // Outut : This function rtu
rns TRUE if stack is mty and rturns FALSE if stack is not mty. { if (to ==
-1) rturn 1;

ls rturn 0; }// End of function void main() { int arrSTACK[50],iChoic,iData;


clrscr(); do { rintf("1. Push\n"); rintf("2. Po\n"); rintf("3. Dislay\n");
rintf("4. Exit\n"); rintf("Entr your choic\n"); scanf("%d",&iChoic); switc
h(iChoic) { cas 1: rintf("Entr th lmnt"); scanf("%d",&iData); fnPush(arr
STACK,iData); brak; cas 2: iData = fnPo(arrSTACK); if(iData == -1) rintf("St
ack is mty\n"); ls rintf("Itm dltd = %d\n",iData); brak; cas 3: rint
f("\n******Stack Contnt******\n"); fnDislay(arrSTACK); rintf("\n*************
************\n"); brak; cas 4: xit(1); } }whil(1); gtch(); }
/****C cod to imlmnt a stack using dynamic mmory allocation****/ /*Fil Nam
 : DMASTACK.C */
#includ<stdio.h> #includ<conio.h> #dfin MAXSIZE 50; struct Nod { int iData;
struct Nod *trNxt; }; tydf struct Nod StackNod;

StackNod *to = NULL; //Prototy Dclaration void fnPush(int); int fnPo(); vo


id fnDislay(); int fnEmty(); void fnPush(int iData) // Puros : This function
insrts an itm on th to th stack. // Inut : Th itm iData that is to b i
nsrtd into th stack. // Outut : Non. { StackNod *trNwNod; // Assign a 
ointr to nw nod. trNwNod = (StackNod*) malloc(sizof(StackNod)); //Crat
 th nw nod. trNwNod->iData = iData; //Load th data fild of th nwly cr
atd nod. trNwNod->trNxt = to; // Now nw nod will oint to th currnt
to nod. to = trNwNod; //Nw nod is now th to nod of th list. }// End
of function int fnPo() // Puros : This function dlts an itm from th to
of th stack. // Inut: Non. // Outut : Th itm iData that has bn dltd
or -1 for an mty stack. { int iData; StackNod *trDltNod; if(fnEmty() ==
1) //Chck th stack mty condition. //Stack is Emty; rturn -1; ls { iData
= to->iData; // Th itm to b dltd. trDltNod = to; //St th ointr
to th nod to b dltd. to = to->trNxt; //St th nw valu of to. fr
(trDltNod); //Fr th nod that has bn dltd. rturn(iData); //Rturn
th data of th dltd nod. } }// End of Function void fnDislay() // Puros
: This function dislays th itms of th stack. // Inut: Non. // Outut : Non
. { StackNod *trDislayNod; if(fnEmty() == 1) rintf("Thr is nothing to d
islay\n"); ls { trDislayNod = to; whil(trDislayNod!=NULL)
//Chck stack mty condition.
//Initializ th ointr to to nod. //Until list is mty.

{ rintf("%d\n",trDislayNod->iData); trDislayNod = trDislayNod -> trN


xt; } } }// End of Function int fnEmty() // Puros : This function chcks wht
hr th stack is mty or not. // Inut : Non. // Outut : This function rturn
s TRUE if stack is mty and rturns FALSE if stack is not mty. { if (to == N
ULL) rturn 1; ls rturn 0; }// End of Function void main() { int iChoic,iDat
a; clrscr(); do { rintf("1. Push\n"); rintf("2. Po\n"); rintf("3. Dislay\n"
); rintf("4. Exit\n"); rintf("Entr your choic\n"); scanf("%d",&iChoic); swi
tch(iChoic) { cas 1: rintf("Entr th lmnt"); scanf("%d",&iData); fnPush(i
Data); brak; cas 2: iData = fnPo(); if(iData == -1) rintf("Stack is mty\n"
); ls rintf("Itm dltd = %d\n",iData); brak; cas 3: rintf("\n******Stac
k Contnt******\n"); fnDislay(); rintf("\n*************************\n"); brak
; cas 4: xit(1); } //Print th data. //Go to nxt nod.

}whil(1); }
/****Rvrs a string using stack****/ /* Fil Nam: REVERSE.C */
#includ<stdio.h> #includ<conio.h> #dfin MAXSIZE 50 void fnPush(char[],char);
char fnPo(char[]); int to=-1; void fnRvrs(char strNam[]) // Puros : Thi
s function rvrs a givn string. // Inut: strNam is th rquird string. //
Outut : Non. // Commnts : arrSTACK is a charactr array to imlmnt th stac
k. { int iCountr = 0; int arrSTACK[50]; whil(strNam[iCountr]!=\0) //Until
nd of string. { fnPush(arrSTACK, strNam[iCountr]); //Push th charactr into
th stack. iCountr = iCountr + 1; } iCountr = 0; whil(fnEmty() != 1) //Unti
l th stack is not mty. { strNam[iCountr] = fnPo(arrSTACK); //Po th chara
ctr and stor into array strNam[]. iCountr = iCountr + 1; } }//End of Functi
on void fnPush( char arrSTACK[], char cData) //Puros : This function insrts a
n itm into th stack. //Inut : arrSTACK[] is th array in which th data itm
iData is to b insrtd. //Outut : Non { if(fnFull() == 1) // Chcking for sta
ck full condition. rintf("stack is full"); ls { to = to + 1; // Incras th
 currnt lngth of th stack.. arrSTACK[to] = cData; // insrt th itm iData.
} }//End of function char fnPo(char arrSTACK[]) //Puros : This function dl
ts th to lmnt from th stack. // Inut: Th array arrSTACK[] on which th
stack is bing imlmntd. //Outut : Th to most itm iData that has bn dl
td.

{ char cData; if(fnEmty() == 1) //Chcking for stack mty condition. { //rint


f("stack is mty"); rturn -1; } ls { cData = arrSTACK[to]; // itm dltd.
to = to - 1; // Shortn th currnt lngth of th stack. rturn cData; // Rt
urn th valu of th itm that has bn dltd. } }//End of function int fnFull
() // Puros : This function chcks whthr th stack is full or not. // Inut:
Non. // Outut : This function rturns TRUE if stack is full and rturns FALSE
if stack is not full. { if (to == MAXSIZE - 1) rturn 1; ls rturn 0; }// En
d of function int fnEmty() // Puros : This function chcks whthr th stack
is mty or not. // Inut: Non. // Outut : This function rturns TRUE if stack
is mty and rturns FALSE if stack is not mty. { if (to == -1) rturn 1; l
s rturn 0; }// End of function void main(void) { char strMyString[20]; clrscr(
); rintf("Entr your string"); gts(strMyString); fnRvrs(strMyString); rint
f("%s",strMyString); gtch(); }
/****C cod to find th ostfix and rfix notation of an infix xrssion ****/
/* Fil Nam: CONVERSION.C */
#includ<stdio.h> #includ<conio.h>

#includ<string.h> #dfin MAXSIZE 50 void fnPush(char[],char); char fnPo(char[


]); char fnto(char[]); void fnRsiz(char *); int to=-1;//Ortstk[50]; void fn
InfixToPostfix (char I[20], char P[20]) // Puros : This function finds th os
tfix notation of an infix xrssion. // Inut: I is an arithmtic xrssion in
infix notation. P is th quivalnt ostfix notation. // Outut : Non. // Comm
nts : Ortstk is th orator stack. { int iIndxI=0,iIndxP=0; char Ortstk[50
]; char symbol,n; whil(I[iIndxI]!=\0) { symbol = I[iIndxI]; //Gt nxt char
actr of I if(symbol == + || symbol == - || symbol == * || symbol == /)
{ whil(fnPriority(fnto(Ortstk))>=fnPriority(symbol) && !fnEmty() && fnto(O
rtstk)!=() { n = fnPo(Ortstk); P[iIndxP] = n; iIndxP++; } fnPush(Ortstk ,
symbol); } ls if(symbol == () fnPush(Ortstk , symbol); ls if(symbol == 
)) // right arnthsis is ncountrd. { whil(fnto(Ortstk) != ( ) //Po f
rom stack until lft arnthsis is ncountrd. { n = fnPo(Ortstk); P[iIndxP
] = n; iIndxP++; } n = fnPo(Ortstk); //only o lft arnthsis (. Dont add it
to P. } ls { P[iIndxP] = symbol; iIndxP++; } iIndxI++; }// nd of whil whi
l(!fnEmty())

{ n = fnPo(Ortstk); P[iIndxP] = n; iIndxP++; } P[iIndxP]=\0; }// End of F


unction void fnInfixToPrfix (char I[20], char P[20]) // Puros : This function
finds th ostfix notation of an infix xrssion. // Inut: I is an arithmtic
xrssion in infix notation. P is th quivalnt ostfix notation. // Outut :
Non. // Commnts : Ortstk is th orator stack. { int iIndxI=0,iIndxP=0; c
har Ortstk[50]; char symbol,n,*tm; I = strrv(I); fnRsiz(I); whil(I[iIndx
I]!=\0) { symbol = I[iIndxI]; //Gt nxt charactr of I if(symbol == + || s
ymbol == - || symbol == * || symbol == /) { whil(fnPriority(fnto(Ortstk
))>fnPriority(symbol) && !fnEmty() && fnto(Ortstk)! =() { n = fnPo(Ortstk
); P[iIndxP] = n; iIndxP++; } fnPush(Ortstk , symbol); } ls if(symbol == (
) fnPush(Ortstk , symbol); ls if(symbol == )) // right arnthsis is nco
untrd. { whil(fnto(Ortstk) != ( ) //Po from stack until lft arnthsis
is ncountrd. { n = fnPo(Ortstk); P[iIndxP] = n; iIndxP++; } n = fnPo(O
rtstk); //only o lft arnthsis (. Dont add it to P. } ls { P[iIndxP] = symb
ol; iIndxP++; } iIndxI++; }// nd of whil

whil(!fnEmty()) { n = fnPo(Ortstk); P[iIndxP] = n; iIndxP++; } P[iIndxP]=


\0; P = strrv(P); fnRsiz(I); I = strrv(I); }// End of Function void fnRsi
z(char *tm) { whil(*tm!=\0) { if(*tm==() *tm = ); ls if(*tm=
=)) *tm=(; tm++; } } int fnPriority(char orator1) { switch(orator1)
{ cas +: cas -: rturn 1; brak; cas *: cas /: rturn 2; brak; } }
char fnto(char Ortstk[]) { rturn Ortstk[to]; } void fnPush( char arrSTACK[]
, char cData) //Puros : This function insrts an itm into th stack. //Inut
: arrSTACK[] is th array in which th data itm iData is to b insrtd. //Out
ut : Non { if(fnFull() == 1) // Chcking for stack full condition. rintf("stac
k is full"); ls

{ to = to + 1; arrSTACK[to] = cData; } }//End of function char fnPo(char arr


STACK[]) //Puros : This function dlts th to lmnt from th stack. // In
ut : Th array arrSTACK[] on which th stack is bing imlmntd. //Outut : T
h to most itm iData that has bn dltd. { char cData; if(fnEmty() == 1) /
/Chcking for stack mty condition. { //rintf("stack is mty"); rturn -1; }
ls { cData = arrSTACK[to]; // itm dltd. to = to - 1; // Shortn th cur
rnt lngth of th stack. rturn cData; // Rturn th valu of th itm that has
bn dltd. } }//End of function int fnFull() // Puros : This function chc
ks whthr th stack is full or not. // Inut : Non. // Outut : This function
rturns TRUE if stack is full and rturns FALSE if stack is not full. { if (to
== MAXSIZE - 1) rturn 1; ls rturn 0; }// End of function int fnEmty() // Pu
ros : This function chcks whthr th stack is mty or not. // Inut : Non.
// Outut : This function rturns TRUE if stack is mty and rturns FALSE if s
tack is not mty. { if (to == -1) rturn 1; ls rturn 0; }// End of function
void main(void) { char I[20],P[20]; int iChoic; clrscr(); // Incras th curr
nt lngth of th stack.. // insrt th itm iData.

do { rintf("1. Infix to Postfix\n"); rintf("2. Infix to Prfix\n"); rintf("3.


Exit\n"); rintf("Entr your choic\n"); scanf("%d",&iChoic); switch(iChoic)
{ cas 1: rintf("Entr th infix xrssion\n"); gts(I); fnInfixToPostfix (I,P
); rintf("\nEquivalnt ostfix xrssion is:%s\n",P); brak; cas 2: rintf("E
ntr th infix xrssion\n"); gts(I); fnInfixToPrfix (I,P); rintf("Equivaln
t ostfix xrssion is:%s\n",P); brak; cas 3: xit(1); dfault: rintf("Wrong
Choic\n"); } }whil(1); }
6.14 MCQ Chatr 6 1. Stack can b imlmntd by (a) Array (b) Linkd List
(c) Both (a) and (b)
(d) non of ths
2. Considr th following four statmnts. (i) A stack is an ordrd collction
of itms into which nw itms may b insrtd and from which itms may b dlt
d at th on nd calld to of th stack. (ii) A stack is an ordrd collction
of itms into which nw itms may b insrtd into an arbitrary location. (iii)
Dynamic imlmntation stacks using Java languag ar ractically imossibl. (i
v) On of th stack alications is usd in comlir dsign. Which on of th fo
llowing is corrct in rlation to th stacks? (a) (i) and (iv) only (b) (i), (ii
) and (iii) only (c) (i) only (d) (iv) only () (i), (ii) and (iv) only 3. Consi
dr th following infix xrssion:

(( A+B) * C (D-E)) ^ (F + G) Which of th following is a / ar corrct quivaln


t xrssion(s) for th abov? (a) ^ - * + A B C D E F G+ (b) ^ - * + A B C D E
F+ G (c) ^ - * + A B C D E + F G (d) - ^ * + A B C D E + F G 4. Which of th fol
lowing statmnts is corrct in connction with stacks? (a) Rturn and rmov th
 most rcntly insrtd itm from th stack, if stack is not mty. (b) Insrt
a nw itm to th to of th stack, if stack is full. (c) Elmnts can b dlt
d from both nds. (d) Rturn and rmov th last rcntly insrtd itm from th
 stack, if stack is not mty. 5. Which of th following is a / ar ossibl o
ration(s) in connction with stacks? (a) Rvrs th ordr of lmnts on stack
S using two additional stacks. (b) Rvrs th ordr of lmnts on stack S usi
ng additional variabls. (c) Rvrs th ordr of lmnts on stack S using on
stack and som additional quus. (d) Sort th lmnts of stacks using on addi
tional stack. Qustions No. 6 and No. 7 ar basd on th following ostfix xr
ssion S and th initial valus of th variabls. S=AB-C+DEF-+^ Assum that A=3,
B=2, C=1, D=1, E=2, F=3 6. If th abov S is valuatd using a stack, what is/ar
 th intrmdiat valu(s) on th to of th stack? (a) 3 (b) 0 (c) 2 (d) -1 7.
What would b th final outut of th stack? (a) 1 (b) 2 (c) 0 (d) -1 8. Evalua
t th following rfix xrssion + * 2 + / 1 4 2 5 1 (a) 13 (b) 14 (c) 15 (d)
27 9. Evaluat th following rfix xrssion - * 6 3 4 1 (a) 25 (b) 15 (c) 23
(d) 12 10. Evaluat th following rfix xrssions + + 2 6 + - 1 3 2 4 (a) 25
(b) 15 (c) 23 (d) 12

11. Convrt th following infix xrssion to ostfix notation (A + 2) * (B + 4)


- 1 (a) A 2 + B 4 + * 1 (b) 1 * + 4 B + 2 A (c) A 2 B 4 + + X l (d) A 2 B 4 1 +
+ * -. 12. Convrt th following infix xrssion to ost fix notation Z (((X +
I) * 2) - 5)/Y (a) Z X I + * 2 5 / Y (b) Z X I + 2 * 5 Y I (c) Z X I + 2 * 5 Y
/ (d) Z X I + 2 5 * - Y /-. 13. A data structur in which an lmnt is addd an
d rmovd only from on nd. is known (a) quu (b) stack (c) in-built data stru
ctur (d) Non of ths 14. Gt a nod, stor nw lmnt and insrt th nw nod
at th to" rfrs to insrt oration in non mty (a) stack (c) array (b) qu
u (d) Non of ths. 15. A data structur in which lmnts ar addd or rmov
d only at a fixd nd is known as (a) quu (b) array (c) stack (d) Linkd List.
16. On can convrt an infix xrssion to a ostfix xrssion using a (a) sta
ck (b) quu (c) dquu (d) non of ths 17. Th intgrs 1, 2, 3, 4 ar ush
d into th stack in that ordr. Thy may b od out of th stack in any valid
ordr. Th intgrs which ar od out roduc a rmutation of th numbrs 1
,2,3,4. Which of th following rmutation can nvr b roducd in such a way?
(0) 1,2,3,4. (b) 4,3,2, 1. (c) 4, 2, 3. 1. (d) 3, 2,4, 1. 18. Which of th follo
wing tys of xrssions do not rquir rcdnc ruls for valuation? (a) Fu
lly arnthsizd infix xrssion (b) Postfix xrssion (c) Partially arnth
sizd infix xrssion (d) Mor than on of th abov 19. Considr th following
statmnts. Which of th following is TRUE. (a) An xrssion in rfix form is
th rvrs of th sam xrssion in ostfix form. (b) An xrssion in rfix
form is th rvrs of th sam xrssion in ostfix form if th orators ar

+, * and /. (c) Non of th abov. (d) Both (a) & (b). 20. Considr th followin
g rcursiv "C" function to comut th l1-th trm in th Fibonacci squnc whi
ch is dnotd by F (11). int fib (int n) if n(==O) rturn 0; ls if (n == 1) r
turn 1; ls rturn (Fib (n-1) + fib (n-2)); } Numbr of additions rformd by
fib (n) is : (a) F(n + 1) (b) F(n + 1) - 1 (c) 2n (d) Non of th abov 21. Th
rfix xrssion for th following infix xrssion a*(b+c)/-f is : (a) /*a+bc
--f (b) -/*abcf () -/* a + bc (d) non of th abov 22. Th following squn
c of orations ar rformd on a stack PUSH(10), PUSH(20), POP, PUSH(10), PUS
H(20), POP, POP. POP, PUSH(20), POP Th squnc of valus od out is : (GATE
-1991) (a) 20, 10, 20, 10, 20 (b) 20, 20, 10, 10, 20 (c) 10, 20, 20, 10, 20 (d)
20, 20, 10, 20, 10 23. ikn O(n), whr O(n) stands for ordr n is : (mor than 1 c
hoic may b corrct). (a) O(n2) (b)O(n3) (c)O(3n2) (d) a of ths 24. Which o
f th foowing prmutation can b obtaind in th output (in th sam ordr) us
ing a stack assuming that th input is th squnc 1,2,3,4,5 in that ordr? (GA
TE-1994) (a) 3, 4, 5, 1, 2 (b) 3, 4, 5, 2, 1 () 1, 5, 2. 3, 4 (d) 5, 4, 3, 1, 2
25. Th postfix xprssion for th infix xprssion A + B * (C + D)/ F + D * E
is: (a) AB+CD+*F/D+E* () A*B+CD/F*DE++ (b) AB+ CD+ * F/D+E* (d) A + * BCD/F* DE
++ (GATE-1995)
26. Which of th foowing is ssntia for convrting an infix xprssion to th
 postfix form fficinty. (GATE-1997) (a) An oprator stack (b) An oprand sta
ck () An oprand stack and oprator stack (d) a pars tr

27. If th squnc of oprations - push (1), push (2), pop, push (1) , push (2)
, pop, pop, pop, push (2), pop, ar prformd on a stack, th squnc of poppd
out vaus ar (a) 2, 2, 1, 1, 2 (b) 2, 2, 1, 2, 2 (c) 2, 1, 2, 2, 1 (d) 2, 1,
2, 2, 2 28. In vauating th arithmtic xprssion 2 * 3 - (4 + 5), using stack
s to vauat its quivant post-fix form, which of th foowing is stack outp
ut? (a) -3 (b) 7 (c) 3 (d) 0 29. tack A has th ntris a, b, c (with a on top)
. tack B is mpty. An ntry poppd out of stack A can b printd immdiaty or
pushd to stack B. An ntry poppd out of stack B can ony b printd. In this
arrangmnt, which of th foowing prmutations of a, b, c is not possib? (a)
b a c (b) b c a (c) cab (d) a b c 30. In th prvious probm, if th stack A h
as 4 ntris, thn th numbr of possib prmuta tions wi b (a) 24 (b) 12 c)
21 (d) 14 31. tacks cannot b usd to (a) vauat an arithmtic xprssion in
postfix form (b) impmnt rcursion (c) convrt a givn arithmtic xprssion
in infix form to its quivant postfix form. (d) aocat rsourcs (ik CPU)
by th oprating systm 32. Th postfix xprssion for th infix xprssion A +
B * (C + D) / F + D * E is: (a) AB + CD + * F / D + E * (b) ABCD + *F / + DE* +
(c) A*B + CD / F*DE ++ (d) A + *BCD / F*DE ++ 33. Th infix prioritis of + , *,
^, / coud b (a) 5, 1,2, 7 (b) 7,5,2, 1 (c) 1, 2, 5, 7 (d) 5,2,2,4
34. Th xprssion 1 * 2 ^ 3 * 4 ^ 5 * 6 wi b vauatd to (a) 3230 (b) 16230
. (c) 49152 (d) 173458 35. tack is usfu for impmnting (a) radix sort (b)
bradth first sarch (c) rcursion (d) dpth first sarch 36. An itm that is r
ad as input can b ithr pushd to a stack and atr poppd and printd, or pri
ntd dircty. Which of th foowing wi not dfinity b th output if th i
nput is th squnc of itms - 1, 2 , 3 , 4 , 5? (a) 3, 4, 5, 1, 2 (b) 3, 4, 5,
2, 1 (c) 1, 5, 2, 3, 4 (d) 5, 4, 3, 1, 2 37. Which of th foowing is ssntia
 for convrting an infix xprssion to th' postfix form fficinty? (a) An op
rator stack (b) An oprand stack (c) An oprator stack and an oprand stack (d)
A pars tr 38. Which of th foowing can b dscrib as a rcord?

(a) (c)

tack List^.Info
(b) (d)
List^ tack^.Info.
39. Which data structur woud you mosty iky s in a nonrcursiv impmnt
ation of a rcursiv agorithm? (a) Link ist (b) uu (c) tack (d) Trs. 40.
Prordr is sam as (a) dpth-first ordr (c) topoogica ordr (b) bradth-fir
st ordr (d) inar ordr
41. Which of th foowing can b dscrib as a pointr? (a) tack (b) List^ (c)
List^.Info (d) tack^.Info 42. Which of th foowing can b dscrib as a arra
y? (a) tack (b) List^ (c) List^.Info (d) tack^.Info 43. Which of th foowing
can b dscrib as a intgr? (a) tack (b) List^ (c) List^.Info (d) tack^.Inf
o

outions:
1. c 2. a 3. c 4. a 16. a 17. c 18. d 19. d 31. d 32. b 33. d 34. c 6.15 Exrcis
 Chaptr 6 1. 2. 5. a 6. c 20. b 21. b 35. c,d 36. d 7. a 22. b 37. a 8. b 23.
d 38. b 9. b 24. b 39. c 10. d 25. b 40. a 11. a 26. a 41. a 12. c 27. a 42. c 1
3. b 28. a 43. d 14. a 29. c 15. c 30. b
What is a stack? tat on ra if xamp for stack and show how it can b ca
d as stack. Cacuat th vau of th foowing postfix xprssion: a) 5 7 8
+ * 4 6 9 / + * b) 2 4 7 - / 5 3 5 * + / Convrt th foowing infix notation t
o postfix xprssion ((X + Y) (W + Z) * K / L ) * M Convrt th foowing postfi
x notation to infix xprssion abcdf+*Writ a C program to impmnt a stack usi
ng (i) Array, (ii) Linkd List
3. 4. 5.
6. What is Dynamic Mmory aocation ratd to stack? writ a C function using
Dynamic Mmory aocation by which you can impmnt a tack. 7. How can you rp
rsnt a poynomia xprssion using stack? Giv on xamp and show how you ca
n comput th rsut of th xprssion by stack. 8. How can you chck a string f
or paindromnss by a stack? Giv on xamp and show how you can comput that
a string is paindrom or not by stack.

9. How can you rvrs a string using stack? Giv on xamp and show how you c
an rvrs a givn string by stack. 10. What is a mutip stack? tat on app
ication of mutip stack and show how mutip stack is impmntd thr.
Chaptr - 7 UEUE
7.1 Dfinition
A quu is a inar data structur in which dtion can tak pac ony at on
nd, cad th front, and insrtions can tak pac ony at th othr nd ca
d th rar. Rar Rar Rar Front 10 INERT(10) Front 20 10 INERT(20) Front 30 2
0 10 INERT(30) DELETE() DELETE() Front Rar 30 20 Front 30 Rar
Figur 7.1: Insrtion and dtion oprations in a quu Thus hr th first ins
rtd itm is dtd first. o quu is cad a FIFO (First In First Out) ist
.
7.2
Impmntation of quu using array

In this sction w wi crat a quu of intgrs using array. For this purpos
an intgr array arr uu of siz MAXIZE is usd and th array dcaration is:
int arr uu[MAXIZE]; Hr front and rar ar two intgr variabs and th in
itia vau of both is 0. From th abov array dcaration th maximum vau of
rar may b MAXIZE. o, rar = MAXIZE indicats quu is fu and front = rar
indicats quu is mpty. Agorithm 7.1 Agorithm for insrtion into quu 1. A
gorithm fn Insrtion (arr uu[], iData) 2. // Purpos : This agorithm insrts
an itm in a inar quu. 3. // Input : arr uu is th array to impmnt th
quu. iData is th itm to b insrtd into th quu. 4. // Output : Non. 5.
// Commnts : rar and front both ar initiaizd from 0. 6. { 7. if(fn Fu()
== TRUE) // Chck for quu fu condition. 8. uu is fu; 9. s 10. { 11.
arr uu[rar] = iData; //Insrt th itm iData onto quu. 12. rar = rar+1; /
/Extnd th ngth of quu. 13. } 14. }// End of Agorithm Agorithm 7.2 Agori
thm for dtion from th inar quu 1. Agorithm fn Dtion (arr uu[]) 2.
// Purpos : This agorithm dts an itm from th inar quu. 3. // Input :
arr uu is th array to impmnt th quu. 4. // Output : Th itm iData tha
t has bn dtd. 5. // Commnts : rar and front both ar initiaizd from 0.
6. { 7. if(fn Empty() == TRUE) // Chck for quu mpty condition. 8. uu is
mpty; 9. s 10. { 11. iData = arr uu[front]; // itm dtd. 12. front = f
ront+1; // hortn th ngth of quu. 13. rturn iData; //Rturn th data. 14.
} 15. }// End of Agorithm Agorithm 7.3 Agorithm to dispay mnts of quu
uu mnts ar in th rang from front to rar of th array arr uu[]. o
mnts of th array arr uu[] from th indx front to indx rar is to b dis
payd. 1. Agorithm fn Dispay (arr uu[]) 2. // Purpos : This agorithm disp
ays th mnts of a inar quu. 3. // Input : arr uu is th array to imp
mnt th quu. 4. //Output : Non. 5. {

6. if (fn Empty() == TRUE) // Chck for quu mpty condition. 7. Nothing to dis
pay; 8. s 9. { 10. for(iCountr = front;iCountr<rar;iCountr++) 11. print
arr uu[iCountr]; 12. } 13. }// End of Agorithm Agorithm 7.4 Agorithm for c
hcking th quu fu condition Th quu is fu if th vau of rar rachs
MAXIZE i.. th maximum siz of th quu. 1. Agorithm fn Fu() 2. // Purpos
: This agorithm chcks whthr th quu is fu or not. 3. // Input : Non. 4
. // Output : This agorithm rturns TRUE if quu is fu and rturns FALE if
quu is not fu. 5. { 6. if (rar == MAXIZE) 7. rturn TRUE; 8. s 9. rtur
n FALE; 10. }// End of Agorithm Agorithm 7.5 Agorithm for chcking th quu
mpty condition Th quu is mpty if th vau of front rachs rar. 1. Agor
ithm fn Empty() 2. // Purpos : This agorithm chcks whthr th quu is mpty
or not. 3. // Input : Non. 4. // Output : This agorithm rturns TRUE if quu
is mpty and rturns FALE if quu is not mpty. 5. { 6. if (front == rar) 7.
rturn TRUE; 8. s 9. rturn FALE; 10. }// End of Agorithm Th foowing x
amp shows how th abov agorithms work: Examp 7.1: Lt MAXIZE=2. Initiay
: front = rar = 0 2 1 0 front=rar fn Insrtion(arr uu[],10) 2 1 0 1 0 rar f
ront

fn Insrtion(arr uu[],20) 2 rar 1 20 0 1 front 0 fn Insrtion(arr uu[],30)


2 rar 1 20 0 1 front 0 As rar = MAXIZE, quu is fu. o, no furthr insrti
on wi tak pac. fn Dtion(arr uu[]) 2 rar 1 2 front 0 0 10 itm dtd
= 10
fn Dtion(arr uu[]) 2 front=rar 1 20 0 10 itm dtd = 20 fn Dtion(arr
uu[]) 2 front=rar 1 20 0 10 As front = rar, quu is mpty. o, no furthr
dtion wi tak pac.
7.3
Impmntation of uu using dynamic mmory aocation
If w impmnt quu using array, thn insrtion of nw data mnts may caus
an ovrfow and so th quu fu condition is to b chckd during ach insrt
ion opration. But quu using dynamic mmory aocation dos not dmand to chc
k th quu fu condition at a in ach push opration as hr w can insrt a
ny numbr of data mnts dpnding upon th avaiab mmory. Figur 6.2 shows
a quu using dynamic mmory aocation: NULL front Figur 7.2: uu using dyn
amic mmory aocation rar

Hr nw data itm is insrtd at th nd of th ist and xisting data itm is
dtd from th bginning of th ist. Each nod of th abov ist has two fi
ds: data fid and pointr fid. Data fid contains th data mnt and th p
ointr fid contains th addrss of th nxt nod in th ist. o from th conc
pt of sf rfrntia structur th structur dfinition of such a nod is: st
ruct Nod { int iData; struct Nod *ptrNxt; }; typdf struct Nod uuNod; W
 can impmnt th inar quu using ony on pointr pointing to th first no
d in th ist. But for simpicity w ar using two pointr variabs front and
rar. Hr, front and rar both ar uuNod typ goba pointr variab and t
hir initia vau is NULL. uuNod *front,*rar; front = NULL; rar = NULL; T
h NULL vau of front (or rar) indicats mpty quu. Agorithm for insrtion
opration Agorithm 7.6 1. Agorithm fn Insrtion(iData) 2. // Purpos : This a
gorithm insrts an mnt into inar quu using dynamic mmory aocation. 3.
// Input : Vau of th itm iData that is to b dtd. 4. // Output : Non.
5. // Commnts : Initia vau of both rar and front is NULL. 6. { 7. uuNod
*ptrNwNod; //Assign a pointr to nw nod. 8. ptrNwNod = ( uuNod*) mao
c(sizof( uuNod)); //Crat th nw nod. 9. ptrNwNod->iData = iData; //Loa
d th data fid of th nwy cratd nod. 10. ptrNwNod->ptrNxt = NULL; // N
ow nw nod is th ast nod in th ist. 11. if(fn Empty() == TRUE) // If ist
is mpty. 12. front = rar = ptrNwNod; //t both th vau of front and rar.
13. s 14. { 15. rar->ptrNxt = ptrNwNod; //Now currnt rar points to th
nw nod. 16. rar = ptrNwNod; //t th rar to nw nod.. 17. } 18. }// End
of Agorithm Agorithm for dtion Opration Agorithm 7.7 1. Agorithm fn D
t() 2. // Purpos : This agorithm dts an itm from a inar quu. 3. //
Input : Non 4. // Output : Th data itm iData that has bn dtd. 5. // Com
mnts : Initia vau of both rar and front is NULL. 6. { 7. uuNod *ptrD
tNod; 8. if(fn Empty() == TRUE) //Chck th quu mpty condition. 9. uu is
Empty; 10. s

11. { 12. iData = front->iData; 13. ptrDtNod = front; 14. front = front->pt
rNxt; 15. fr(ptrDtNod); 16. rturn(iData); 17. } 18. }// End of Agorith
m
//Th data itm to b dtd. //t th pointr to th nod to b dtd. //
t th nw vau of top. //D-aocat mmory for th nod that has bn dtd.
//Rturn th data of th dtd nod.
Agorithm to dispay th mnts of inar quu using dynamic mmory aocatio
n In this impmntation, front points to th first nod in th ist. o to disp
ay a th mnts of th quu w hav to travrs th ist starting from th
front nod ti a NULL vau (i.. nd of ist) is ncountrd. Th foowing a
gorithm dscribs th procdur. Agorithm 7.8 1. Agorithm fn Dispay() 2. //
Purpos : This agorithm dispays th mnts of a inar quu using dynamic m
mory aocation. 3. // Input : Non. 4. // Output : Non. 5. { 6. uuNod *pt
rDispayNod; 7. if(fn Empty() == TRUE) // If quu is mpty. 8. Thr is nothin
g to dispay; 9. s 10. { 11. ptrDispayNod = front; //Initiaiz th pointr
to front nod. 12. whi(ptrDispayNod != NULL) //Unti ist is mpty. 13. { 1
4. print (ptrDispayNod->iData); //Print th data. 15. ptrDispayNod = ptrDisp
ayNod -> ptrNxt; //Go to nxt nod. 16. } 17. } 18. }// End of Agorithm Ago
rithm for chcking th quu mpty condition Agorithm 7.9 1. Agorithm fn Empty
() 2. // Purpos : This agorithm chcks whthr th quu is mpty or not. 3. /
/ Input : Non. 4. // Output : This agorithm rturns TRUE if quu is mpty and
rturns FALE if quu is not mpty. 5. { 6. if (front == NULL || rar == NULL)
7. rturn TRUE; 8. s 9. rturn FALE; 10. }// End of Agorithm Th foowing
xamp shows how th abov agorithms work: Examp 7.2: Initiay: front = r
ar = NULL fn Insrtion(10)

ptrNwNod = ( uuNod*) maoc(sizof( uuNod))


ptrNwNod ptrNwNod->iData = 10; 10 ptrNwNod ptrNwNod->ptrNxt = NULL 10 N
ULL
ptrNwNod if(rar = NULL or front = NULL) front = rar = ptrNwNod 10 NULL //
this is tru for our cas
front = rar fn Dt() 10 iData = front->iData = 10 ptrDtNod = front 10 N
ULL NULL front
ptrDtNod = front front = front -> ptrNxt = NULL fr(ptrDtNod) rturn
10
7.4
Limitation of inar quu
5 rar 4 50 3 4 front 0 2 1 0

Considr th snapshot abov in a inar quu. Th quu can contain maximum 5 
mnts. Currnty th quu has ony 2 mnts. But no mor mnts can b in
srtd into th quu as th vau of rar is 5 i.. 3 spacs is bing simpy wa
std. This imitation can b sovd using circuar quu.
7.5
Circuar uu
In a circuar quu whn rar (or front) rachs MAXIZE - 1 thn rar (or front
) wi b 0 i.. th incrmnt of rar (or front) is rar = (rar + 1) % MAX, an
d aso front = (front + 1) % MAX 4 50 3 4 front 0 2 1 0 rar Now w can insrt a
nw mnt in th array indx 0. 4 3 .
.
2 1 0
n-1
Figur 7.3: Circuar quu of n mnts Hr aso th initia vau of both fro
nt and rar is 0. o, quu mpty condition for a circuar ist is front = rar.
Now suppos MAXIZE = 3 and xcut th foowing squnc of statmnts: fnC I
nsrt(arrC uu[],10) arrC uu[0] = 10 rar = (rar + 1)%3 =1 2
1 0
fnC Insrt(arrC uu[],20) arrC uu[1] = 20 rar = (rar + 1)%3 = 2
rar 10 front
2 1 0 20 10
rar
front

fnC Insrt(arrC uu[],30) arrC uu[2] = 30 rar = (rar + 1)%3 = 0


2 1 0
30 20 10 front rar
Now th quu is fu. Unfortunaty hr aso front = rar. o it is difficut
to diffrntiat btwn th quu fu and quu mpty condition. But notic on
 thing, if front rachs rar during th dtion opration thn obviousy it i
ndicats that th quu is mpty and if rar b qua to front during th insrt
ion opration into quu thn this mans quu is fu. To impmnt this ogic
two Booan variabs boo fu (to indicat quu is fu) and boo mpty (to i
ndicat quu is mpty) ar takn. Initiay boo fu is st to FALE and boo
mpty is st to TRUE. Agorithm for insrtion into circuar quu Agorithm 7.10
1. Agorithm fnC Insrt(arrC uu[], iData) 2. // Purpos : This agorithm ins
rts an itm into circuar quu. 3. //Input : arrC uu is th array to impmn
t th circuar quu and iData is th itm to b insrtd. 4. //Output : Non. 5
. // Commnts : Booan variab boo fu = TRUE indicats that quu is fu.
6. { 7. if(boo fu == TRUE) //If quu is fu. 8. uu is fu; 9. s 10.
{ 11. arrC uu[rar] = iData; //Insrt th data. 12. rar = (rar + 1) % MAXIZ
E; //Incrmnt rar. 13. boo mpty = FALE; //As an insrtion taks pac, so n
ow quu is not mpty. 14. if (rar == front) 15. boo fu = TRUE; //if rar b
qua to front thn quu is fu. 16. } 17. }// End of Agorithm Agorithm for
dtion into circuar quu Agorithm 7.11 1. Agorithm fnC Dt(arrC uu[]
) 2. // Purpos : This agorithm dts an itm from circuar quu. 3. //Input
: arrC uu is th array to impmnt th circuar quu. 4. //Output : This a
gorithm rturns th itm iData that has bn dtd. 5. // Commnts : Booan v
ariab boo mpty = TRUE indicats that quu is mpty. 6. { 7. if(boo mpty =
= TRUE) //If quu is mpty. 8. uu is mpty; 9. s 10. { 11. iData = arrC u
u[front] //itm dtd. 12. front = (front + 1) % MAXIZE; //Incrmnt rar.

13. boo fu = FALE; 14. if (front == rar) 15. boo mpty = TRUE; 16. } 17. }
//End of Agorithm
//t boo fu to fas as now quu is not fu. //if front b qua to rar t
hn quu is mpty.
7.6
Dqu(Doub Endd uu)
Dqu: It is a inar ist whr itms can b insrtd or dtd at ithr nd
but not from th midd. That is, hr w can insrt or dt mnts from bot
h th rar and front nd. Hnc it is aso cad a doub ndd quu. Dtion
Insrtion 10 20 5 30 20 40 Insrtion Dtion front rar Thr ar two typs of
dqu du to th rstrictions of prforming insrtion and dtion ony at on
nd. Thy ar: 1) Input rstrictd dqu: Hr insrtion can b don at on nd
of th ist but aows dtion from both th rar and front nd. 2) Output rst
rictd dqu: Hr dtion can b don at on nd of th ist but aows insrt
ion from both th rar and front nd. inc both insrtion and dtion ar prf
ormd from ithr nd, it is ncssary to dsign four agorithms to prform th
foowing four oprations: 1) Insrtion of nw mnt into th rar nd of th
quu: This opration is simiar to norma insrtion into a inar quu discuss
d in th sction 7.2. 2) Insrtion of nw mnt into th front nd of th qu
u: This opration is a tricky on. Hr th nw mnt is insrtd at th fron
t nd of th quu. As hr a nw data itm is bing insrtd so quu fu cond
ition is to b chckd. Th gnra ogic to impmnt this opration is first d
crmnt th vau of front and thn insrt th data itm at th currnt positio
n of th front. o if th vau of front is 0, thn no furthr insrtion can tak
 pac as aftr dcrmnting nw vau of front wi b -1 which is not fasib
 (bcaus array indx -1 dos not xist). Hnc in this cas quu fu conditi
on is front = 0. 3) Dtion of xisting data itm from th rar nd of th quu
: Hr first stor th data vau of th indx rar from th array and thn dc
rmnt th vau of rar. Th quu mpty condition is simiar to inar quu d
iscussd in th sction 7.2. 4) Dtion of xisting data itm from th front n
d of th quu: This is simiar to th dtion opration from th inar quu
discussd in th sction 7.2. Agorithm for insrtion into th rar nd of th q
uu Agorithm 7.12 1. Agorithm fnD Insrt_At_Rar(arrDqu[], iData) 2. // Pur
pos : This agorithm insrts an mnt at th rar of a quu. 3. // Input : a
rrDqu[] is th array to impmnt th quu and iData is th data itm to b i
nsrtd. 4. // Output : Non. 5. // Commnts : Vau of both front and rar ar
initiaizd from 0. 6. { 7. if (fn Fu() == TRUE) 8. uu is fu; 9. s 10.
{

11. arrDqu[rar] = iData; 12. rar = rar + 1; 13. } 14. }//End of Agorithm A
gorithm for insrtion into th front nd of th quu Agorithm 7.13 1. Agorit
hm fnD Insrt_At_Front(arrDqu[], iData) 2. // Purpos : This agorithm insrts
an mnt at th front of a quu. 3. // Input : arrDqu[] is th array to im
pmnt th quu and iData is th data itm to b insrtd. 4. // Output : Non
. 5. // Commnts : Vau of both front and rar ar initiaizd from 0. 6. { 7.
if (front == 0 ) 8. uu is fu; 9. s 10. { 11. front = front - 1; 12. arrD
qu[front] = iData; 13. } 14. }//End of Agorithm Agorithm for dtion from t
h rar nd of th quu Agorithm 7.14 1. Agorithm fnD Dt_From_Rar(arrDq
u[]) 2. // Purpos : This agorithm dts an mnt from th rar nd of a q
uu. 3. // Input : arrDqu[] is th array to impmnt th quu. 4. // Output
: Th data itm iData that has bn dtd. 5. // Commnts : Vau of both fro
nt and rar ar initiaizd from 0. 6. { 7. if (fn Empty() == TRUE) 8. uu is
mpty; 9. s 10. { 11. rar = rar - 1; 12. iData = arrDqu[rar]; 13. rturn
iData; 14. } 15. }//End of Agorithm Agorithm for dtion from th front nd
of th quu Agorithm 7.15 1. Agorithm fnD Dt_From_Front(arrDqu[]) 2. //
Purpos : This agorithm dts an mnt from th front nd of a quu. 3. /
/ Input : arrDqu[] is th array to impmnt th quu. 4. // Output : Th dat
a itm iData that has bn dtd. 5. // Commnts : Vau of both front and ra
r ar initiaizd from 0. 6. {

7. if (fn Empty() == TRUE) 8. uu is mpty; 9. s 10. { 11. iData = arrDqu
[front]; 12. front = front + 1; 13. rturn iData; 14. } 15. }//End of Agorithm
7.7
Priority uu
A priority quu is a coction of mnts such that ach mnt has bn ass
ignd a priority such that th ordr in which mnts ar dtd and procssd
coms from th foowing rus: 1. An mnt of highr priority is procssd b
for any mnt of owr priority. 2. Two mnts with sam priority ar proc
ssd according to th ordr in which thy ar addd to th quu. To impmnt
th priority quu minimum two quus ar ndd on to stor th mnts and t
h othr to assign th corrsponding prioritis. Thr ar two typs of priority
quu: 1) Ascnding priority quu: Hr th mnts can b insrtd arbitrari
y but ony th mnt with th smast priority can b dtd. 2) Dscnding
priority quu: Hr th mnts can b insrtd arbitrariy but ony th m
nt with highst priority can b dtd. Hr w wi discuss th insrtion and
dtion agorithm for ascnding priority quu. From th proprtis of ascndi
ng priority quu w can insrt data in any whr of th array but th data with
smast priority can b dtd. For this purpos, during insrtion first find
th position of th nw data mnt in th array according to its priority and
stor th data in that position. Hnc th array bcoms a sortd on in ascnd
ing ordr according to th prioritis of th mnts and hnc th first data v
au of th array is th data itm with smast priority which is to b dtd
.
Agorithm for insrtion into ascnding priority quu Agorithm 7.16 1. Agorith
m fnAP Insrt(arr uu[], arrP uu[], iData, iPriority) 2. // Purpos : This a
gorithm insrts an mnt in an ascnding priority quu. 3. // Input : arr uu
[] is th array to stor th data vau and arrP uu[] is th array to stor t
h //corrsponding prioritis. iData and iPriority ar th data itm and its pri
ority rspctivy. 4. // Output : Non. 5. // Commnts : Vau of both front an
d rar ar initiaizd from 0. 6. { 7. if(rar == MAXIZE) 8. uu is fu; 9.
s 10. { 11. iPosition = fnFind_Position(arrP uu[], iPriority); 12. fnInsrt
ion_into_Array(arr uu[], rar, iPosition, iData); 13. fnInsrtion_into_Array(a
rrP uu[], rar, iPosition, iPriority); 14. rar = rar + 1; 15. } 16. }// End
of Agorithm

Agorithm for dtion from th ascnding priority quu Agorithm 7.17 1. Agor
ithm fnAP Dt(arr uu[], arrP uu[]) 2. // Purpos : This agorithm insrts
an mnt in an ascnding priority quu. 3. // Input : arr uu[] is th arra
y to stor th data vau and arrP uu[] is th array to stor th //corrspond
ing prioritis. 4. // Output : Th data itm iData that has bn dtd. 5. //
Commnts : Vau of both front and rar ar initiaizd from 0. 6. { 7. if(front
== rar) 8. uu is mpty; 9. s 10. { 11. iData = arr uu[front]; 12. iPri
ority = arrP uu[front]; 13. front = front + 1; 14. rturn iData; 15. } 16. }//
End of Agorithm
7.8
Impmntation of quu using stacks

tack is a Last In First Out ist. But quu foows th ru First In First Out
. Now a quu can b impmntd using two stacks. uppos two stacks tack1 and
tack2 ar avaiab. Now inst th itms in th first stack tack1. But for d
tion us tack2. First pop a th mnts from tack1 and push thm into ta
ck2. Now th top mnt of tack2 is th mnt that has bn insrtd first i
nto th tack1. o now pop th top mnt of tack2 and dispay it. Thn again
pop a th mnts of tack2 and push thm into tack1 and prform th simiar
kind of opration for mor insrtion and dtion oprations. Th foowing xa
mp dscribs this procss. uppos w hav two stacks tack1 and tack2 with s
am siz. Considr th foowing statmnts: PUH (tack1, 10) PUH (tack1, 20)
PUH (tack1, 30) PUH (tack1, 40) Aftr xcuting th abov statmnts, th c
ontnt of tack1 and tack2 is shown in figur7.4.
40 30 20 10
tack1 tack2 Figur 7.4 Now pop a th mnts from tack1 and insrt thm in
to tack2 (shown in figur7.5). PUH (tack2, POP (tack1)) // Pop 40 from tack
1 and Push 40 onto tack2 PUH (tack2, POP (tack1)) // Pop 30 from tack1 and
Push 30 onto tack2 PUH (tack2, POP (tack1)) // Pop 20 from tack1 and Push 2
0 onto tack2

PUH (tack2, POP (tack1))


// Pop 10 from tack1 and Push 10 onto tack2
10 20 30 40
tack2 Figur 7.5 Now pop from tack2 dts mnt 10 which is first insrtd
mnt. Thus w can impmnt a quu. Aftr dting th mnt from tack2,
again push a th mnts of tack2 onto tack1 (shown in figur 7.6). That i
s, xtrna Push opration is prformd on tack1 and Fina Pop opration is pr
formd from tack2. tack1
40 30 20
tack1 Figur 7.6 tack2
Agorithm 7.18 1. Agorithm fn _Using_tack_Insrt(arrtack1[], iData) 2. // Pur
pos : This agorithm insrts an itm in a quu impmntd using two stacks. 3
. // Input : arrtack1[] is th array to impmnt tack1 and iData is th data
itm to b insrtd. 4. // Output : Non 5. { 6. if (top1 == MAXIZE-1) 7. uu
is fu; 8. s 9. fnPush(arrtack1[], iData); 10. }//End of Agorithm Agorit
hm 7.19 1. Agorithm fn _Using_tack_Dt(arrtack1[], arrtack2[]) 2. // Purp
os : This agorithm insrts an itm in a quu impmntd using two stacks. 3.
// Input : arrtack1[] and arrtack2[] ar th arrays to impmnt tack1 and 
tack2 rspctivy. 4. // Output : Th data itm iData that has bn dtd.

5. { 6. if ( top1 == -1) 7. uu is mpty; 8. s 9. { 10. whi(top1 != -1) 1


1. fnPush(arrtack2[], fnPop(arrtack1[])); 12. iData = fnPop(arrtack2[]); 13.
whi(top2 != -1) 14. fnPush(arrtack1[], fnPop(arrtack2[])); 15. rturn iData;
16. } 17. }// End of Agorithm
7.9
Appication of uu
1) Job quu and procss quu ar impmntd using quu for procss schduin
g. 2) Printr srvr routin is impmntd using quu. 3) A typs of custom
r srvic softwar (ik Raiway tickt rsrvation) ar dsignd using quu fo
r propr srvic to customr. /* Program to impmnt a inar quu using array
*/ /* Array.c*/ #incud<stdio.h> #incud<conio.h> #dfin MAXIZE 50 #dfin
TRUE 1 #dfin FALE 0 int front=0,rar=0; //Prototyp Dcaration void fn Ins
rtion(int[], int); int fn Dtion(int[]); void fn Dispay (int []); int fn Fu
(); int fn Empty(); void fn Insrtion (int arr uu[], int iData) // Purpos : T
his function insrts an itm in a inar quu. // Input: arr uu is th array
to impmnt th quu. iData is th itm to b insrtd into th quu. // Outp
ut : Non. // Commnts : rar and front both ar initiaizd from 0. { if(fn Fu
() == TRUE) // Chck for quu fu condition. printf("\n uu is fu\n"); s
 { arr uu[rar] = iData; //Insrt th itm iData onto quu. rar = rar+1; /
/Extnd th ngth of quu. } }// End of Function

int fn Dtion (int arr uu[]) // Purpos : This function dts an itm from
th inar quu. // Input : arr uu is th array to impmnt th quu. // O
utput : Th itm iData that has bn dtd. // Commnts : rar and front both
ar initiaizd from 0. { int iData; if(fn Empty() == TRUE) // Chck for quu 
mpty condition. printf("\n uu is mpty\n"); s { iData = arr uu[front]; //
itm dtd. front = front+1; // hortn th ngth of quu. rturn iData; //
Rturn th data. } }// End of Function void fn Dispay (int arr uu[]) // Purpo
s : This function dispays th mnts of a inar quu. // Input: arr uu i
s th array to impmnt th quu. //Output : Non. { int iCountr; if (fn Empt
y() == TRUE) // Chck for quu mpty condition. printf("\nNothing to dispay\n"
); s { for(iCountr = rar-1;iCountr>=front;iCountr--) printf("%d\n",arr u
u[iCountr]); } }// End of function int fn Fu() // Purpos : This function ch
cks whthr th quu is fu or not. // Input: Non. // Output : This function
rturns TRUE if quu is fu and rturns FALE if quu is not fu. { if (ra
r == MAXIZE) rturn TRUE; s rturn FALE; }// End of function int fn Empty()
// Purpos : This function chcks whthr th quu is mpty or not. // Input:
Non. // Output : This function rturns TRUE if quu is mpty and rturns FALE
if quu is not mpty. { if (front == rar) rturn TRUE; s

rturn FALE; }// End of function void main() { int arr UEUE[50],iChoic,iData;
crscr(); do { printf("1. Insrtion\n"); printf("2. Dtion\n"); printf("3. Dis
pay\n"); printf("4. Exit\n"); printf("Entr your choic\n"); scanf("%d",&iChoic
); switch(iChoic) { cas 1: printf("Entr th mnt"); scanf("%d",&iData); f
n Insrtion(arr UEUE,iData); brak; cas 2: if(fn Empty()==TRUE) printf(" uu i
s mpty\n"); s printf("Itm dtd = %d\n",fn Dtion(arr UEUE)); brak; ca
s 3: printf("\n****** uu Contnt******\n"); fn Dispay(arr UEUE); printf("\n*
************************\n"); brak; cas 4: xit(1); dfaut: printf("\nWrong C
hoic\n"); } }whi(1); } /* Program to impmnt a inar quu using inkd i
st */ /* Linkd.c*/ #incud<stdio.h> #incud<conio.h> #incud<aoc.h> #dfi
n MAXIZE 50; #dfin TRUE 1 #dfin FALE 0 struct Nod { int iData; struct No
d *ptrNxt;

}; typdf struct Nod uuNod; uuNod *front=NULL,*rar=NULL; //front = NU


LL; //rar = NULL; void fn Insrtion(int iData) // Purpos : This function insr
ts an mnt into inar quu using dynamic mmory aocation. // Input: Vau
of th itm iData that is to b dtd. // Output : Non. // Commnts : Initia
 vau of both rar and front is NULL. { uuNod *ptrNwNod; //Assign a poin
tr to nw nod. ptrNwNod = ( uuNod*) maoc(sizof( uuNod)); //Crat t
h nw nod. ptrNwNod->iData = iData; //Load th data fid of th nwy crat
d nod. ptrNwNod->ptrNxt = NULL; // Now nw nod is th ast nod in th is
t. if(fn Empty() == TRUE) // If ist is mpty. front = rar = ptrNwNod; //t
both th vau of front and rar. s { rar->ptrNxt = ptrNwNod; //Now curr
nt rar points to th nw nod. rar = ptrNwNod; //t th rar to nw nod..
} }// End of Function int fn Dt() // Purpos : This function dts an itm
from a inar quu. // Input: Non // Output : Th data itm iData that has b
n dtd. // Commnts : Initia vau of both rar and front is NULL. { int iD
ata; uuNod *ptrDtNod; if(fn Empty() == TRUE) //Chck th quu mpty co
ndition. { printf("\n uu is Empty\n"); rturn 0; } s { iData = front->iData
; //Th data itm to b dtd. ptrDtNod = front; //t th pointr to th
nod to b dtd. front = front->ptrNxt; //t th nw vau of top. fr(pt
rDtNod); //Daocat mmory for th nod that has bn dtd. rturn(iDa
ta); //Rturn th data of th dtd nod. } }// End of Function void fn Dispa
y() // Purpos : This function dispays th mnts of a inar quu using dyn
amic mmory aocation. // Input: Non.

// Output : Non. { uuNod *ptrDispayNod; if(fn Empty() == TRUE) printf("\n


Nothing to dispay\n"); s { ptrDispayNod = front; whi(ptrDispayNod != N
ULL) { printf("%d\n",ptrDispayNod->iData); ptrDispayNod = ptrDispayNod ->
ptrNxt; } } }// End of Function
// If quu is mpty.
//Initiaiz th pointr to front nod. //Unti ist is mpty. //Print th data.
//Go to nxt nod.
int fn Empty() // Purpos : This function chcks whthr th quu is mpty or n
ot. // Input: Non. // Output : This function rturns TRUE if quu is mpty and
rturns FALE if quu is not mpty. { if (front == NULL || rar == NULL) rtur
n TRUE; s rturn FALE; }// End of Function void main() { int iChoic,iData;
crscr(); do { printf("1. Insrtion\n"); printf("2. Dtion\n"); printf("3. Dis
pay\n"); printf("4. Exit\n"); printf("Entr your choic\n"); scanf("%d",&iChoic
); switch(iChoic) { cas 1: printf("Entr th mnt"); scanf("%d",&iData); f
n Insrtion(iData); brak; cas 2: if(fn Empty()==TRUE) printf(" uu is mpty\n
"); s printf("Itm dtd = %d\n",fn Dt()); brak;

cas 3: printf("\n****** uu Contnt******\n"); fn Dispay(); printf("\n*******


******************\n"); brak; cas 4: xit(1); dfaut: printf("\nWrong Choic\
n"); } }whi(1); } /* Program to impmnt a Priority uu*/ /* Fi Nam: Pri
ority .c */ #incud<stdio.h> #incud<conio.h> #dfin MAXIZE 50 #dfin TRUE
1 #dfin FALE 0 int front=0,rar=0; //Prototyp Dcaration void fnAP Insrt(i
nt [], int [], int, int); int fnAP Dt(int[], int[]); int fnFind_Position(int
[], int); void fnInsrtion_into_Array(int[], int, int, int); void fn Dispay (in
t[],int[]); int fn Fu(); int fn Empty(); void fnAP Insrt(int arr uu[], int
arrP uu[], int iData, int iPriority) // Purpos : This function insrts an 
mnt in an ascnding priority quu. // Input: arr uu[] is th array to stor
th data vau and arrP uu[] is th array to stor th //corrsponding priorit
is. iData and iPriority ar th data itm and its priority rspctivy. // Out
put : Non. // Commnts : Vau of both front and rar ar initiaizd from 0. {
int iPosition; if(fn Fu()==TRUE) printf("\n uu is fu\n"); s { if(fn Em
pty()==TRUE) iPosition = front; s iPosition = fnFind_Position(arrP uu, iPri
ority); fnInsrtion_into_Array(arr uu, rar, iPosition, iData); fnInsrtion_in
to_Array(arrP uu, rar, iPosition, iPriority); rar = rar + 1; } }// End of F
unction

int fnFind_Position(int arrP uu[], int iPriority) // Purpos : This function f


inds th position of th mnt according to priority. // Input: arrP uu[] is
th array to stor th prioritis and iPriority is th priority of th nw m
nt. // Output : Rturns th position. // Commnts : Vau of both front and ra
r ar initiaizd from 0. { int iCountr; for(iCountr = front;iCountr<rar;iCo
untr++) if(arrP uu[iCountr]>iPriority) rturn iCountr; rturn iCountr; }//
End of Function void fnInsrtion_into_Array(int arrData[], int n, int k, int it
m) // Purpos : This function insrts an mnt into on dimnsiona array. //
Input: arrData[] is an on dimnsiona array with n numbr of mnts. Emnt
itm is to b insrtd into th kth position in th array. // Output : Non. {
int i; for(i=n-1;i>=k;i--) arrData [i+1]= arrData [i]; arrData[k]=itm; // Insr
t th itm. }// End of Function int fnAP Dt(int arr uu[], int arrP uu[])
// Purpos : This function insrts an mnt in an ascnding priority quu. /
/ Input: arr uu[] is th array to stor th data vau and arrP uu[] is th
array to stor th //corrsponding prioritis. // Output : Th data itm iData t
hat has bn dtd. // Commnts : Vau of both front and rar ar initiaizd
from 0. { int iData,iPriority; if(fn Empty()==TRUE) printf("\n uu is mpty\n"
); s { iData = arr uu[front]; iPriority = arrP uu[front]; front = front +
1; rturn iData; } }// End of Function void fn Dispay (int arr uu[],int arrP
uu[]) // Purpos : This function dispays th mnts of a inar quu. //
Input: arr uu is th array to impmnt th quu. //Output : Non. { int iCou
ntr; if (fn Empty() == TRUE) // Chck for quu mpty condition.

printf("\nNothing to dispay\n"); s { for(iCountr = rar-1;iCountr>=front;i


Countr--) printf("%d\t%d\n",arr uu[iCountr],arrP uu[iCountr]); } }// End
of function int fn Fu() // Purpos : This function chcks whthr th quu is
fu or not. // Input: Non. // Output : This function rturns TRUE if quu is
fu and rturns FALE if quu is not fu. { if (rar == MAXIZE) rturn TRUE
; s rturn FALE; }// End of function int fn Empty() // Purpos : This functi
on chcks whthr th quu is mpty or not. // Input: Non. // Output : This fu
nction rturns TRUE if quu is mpty and rturns FALE if quu is not mpty. {
if (front == rar) rturn TRUE; s rturn FALE; }// End of function void mai
n() { int arr UEUE[50],arrP uu[50],iChoic,iData,iPriority; crscr(); do { pri
ntf("****PRIORITY UEUE****\n"); printf("1. Insrtion\n"); printf("2. Dtion\n
"); printf("3. Dispay\n"); printf("4. Exit\n"); printf("Entr your choic\n");
scanf("%d",&iChoic); switch(iChoic) { cas 1: printf("Entr th mnt and it
s priority"); scanf("%d%d",&iData,&iPriority); fnAP Insrt(arr UEUE,arrP uu,iD
ata,iPriority); brak; cas 2: if(fn Empty()==TRUE)

printf(" uu is mpty\n"); s printf("Itm dtd = %d\n",fnAP Dt(arr UE


UE,arrP uu)); brak; cas 3: printf("\n****** uu Contnt******\n"); fn Disp
ay(arr UEUE,arrP uu); printf("\n*************************\n"); brak; cas 4:
xit(1); dfaut: printf("\nWrong Choic\n"); } }whi(1); } /* Program to imp
mnt a Dqu*/ /* Fi Nam: Dqu.c */ /* Program to impmnt a dqu */ /* DE
UE.c */ #incud<stdio.h> #incud<conio.h> #dfin MAXIZE 50 #dfin TRUE 1 #
dfin FALE 0 int front=0,rar=0; //Prototyp Dcaration void fnD Insrt_At_R
ar(int[], int); void fnD Insrt_At_Front(int[], int); int fnD Dt_From_Rar(i
nt[]); int fnD Dt_From_Front(int[]); void fn Dispay (int []); int fn Fu()
; int fn Empty(); void fnD Insrt_At_Rar(int arrDqu[], int iData) // Purpos
: This function insrts an mnt at th rar of a quu. // Input: arrDqu[]
is th array to impmnt th quu and iData is th data itm to b insrtd. /
/ Output : Non. // Commnts : Vau of both front and rar ar initiaizd from
0. { if (fn Fu() == TRUE) printf("\n uu is fu"); s { arrDqu[rar] =
iData; rar = rar + 1; } }//End of function void fnD Insrt_At_Front(int arrDq
u[], int iData)

// Purpos : This function insrts an mnt at th front of a quu. // Input:


arrDqu[] is th array to impmnt th quu and iData is th data itm to b
insrtd. // Output : Non. // Commnts : Vau of both front and rar ar init
iaizd from 0. { if (front == 0 ) printf("\n uu is fu\n"); s { front = f
ront - 1; arrDqu[front] = iData; } }//End of function int fnD Dt_From_Rar
(int arrDqu[]) // Purpos : This function dts an mnt from th rar nd
of a quu. // Input: arrDqu[] is th array to impmnt th quu. // Output
: Th data itm iData that has bn dtd. // Commnts : Vau of both front
and rar ar initiaizd from 0. { int iData; if (fn Empty() == TRUE) printf("\n
uu is mpty\n"); s { rar = rar - 1; iData = arrDqu[rar]; rturn iData
; } }//End of function int fnD Dt_From_Front(int arrDqu[]) // Purpos : Th
is function dts an mnt from th front nd of a quu. // Input: arrDqu
[] is th array to impmnt th quu. // Output : Th data itm iData that has
bn dtd. // Commnts : Vau of both front and rar ar initiaizd from 0
. { int iData; if (fn Empty() == TRUE) printf("\n uu is mpty\n"); s { iDat
a = arrDqu[front]; front = front + 1; rturn iData; } }//End of function void
fn Dispay (int arr uu[]) // Purpos : This function dispays th mnts of
a inar quu. // Input: arr uu is th array to impmnt th quu. //Output
: Non.

{ int iCountr; if (fn Empty() == TRUE) // Chck for quu mpty condition. prin
tf("\nNothing to dispay\n"); s { for(iCountr = rar-1;iCountr>=front;iCoun
tr--) printf("%d\n",arr uu[iCountr]); } }// End of function int fn Fu() //
Purpos : This function chcks whthr th quu is fu or not. // Input: Non
. // Output : This function rturns TRUE if quu is fu and rturns FALE if q
uu is not fu. { if (rar == MAXIZE) rturn TRUE; s rturn FALE; }// End
of function int fn Empty() // Purpos : This function chcks whthr th quu
is mpty or not. // Input: Non. // Output : This function rturns TRUE if quu
is mpty and rturns FALE if quu is not mpty. { if (front == rar) rturn T
RUE; s rturn FALE; }// End of function void main() { int arrD UEUE[50],iCho
ic,iData; crscr(); do { printf("1. Insrt At Front\n"); printf("2. Insrt At R
ar\n"); printf("3. Dt From Front\n"); printf("4. Dt From Rar\n"); prin
tf("5. Dispay\n"); printf("6. Exit\n"); printf("Entr your choic\n"); scanf("%
d",&iChoic); switch(iChoic) { cas 1: printf("Entr th mnt"); scanf("%d",
&iData);

fnD Insrt_At_Front(arrD UEUE,iData); brak; cas 2: printf("Entr th mnt")


; scanf("%d",&iData); fnD Insrt_At_Rar(arrD UEUE,iData); brak; cas 3: if(fn
Empty()==TRUE) printf(" uu is mpty\n"); s printf("Itm dtd = %d\n",fnD
Dt_From_Front(arrD UEUE)); brak; cas 4: if(fn Empty()==TRUE) printf(" uu
 is mpty\n"); s printf("Itm dtd = %d\n",fnD Dt_From_Rar(arrD UEUE
)); brak; cas 5: printf("\n****** uu Contnt******\n"); fn Dispay(arrD UEUE
); printf("\n*************************\n"); brak; cas 6: xit(1); dfaut: pri
ntf("\nWrong Choic\n"); } }whi(1); }
7.10 MC Chaptr - 7 ustions No. 1 and No. 2 ar basd on th foowing straig
ht quu which can b aocatd ight intgrs and fiv oprations. front = 3 r
ar= 5 uu = - , - , 2 , 4 ,5, - , - , (for notationa convninc usd to dno
t an mpty c) Th foowing oprations hav to b prformd. (i) 6 is addd
to th quu. (ii) Two mnts ar dtd from th quu. (iii) 7 and 8 ar ad
dd to th quu. (iv) Two mnts ar dtd from th quu. (v) 2 and 3 ar
addd to th quu. 1. What ar th fina front and rar vaus whn th abov o
prations ar prformd into a straight quu? (a) front = 7 rar=2 (b) front =
2 rar=7 (c) front = 7 rar=8 (d) front = 5 rar=8 2. What ar th fina front a
nd rar vaus whn th abov oprations ar prformd into a circuar quu?

(a) front = 7 rar=3 (b) front = 2 rar=7 (c) front = 2 rar=8 (d) front = 5 ra
r=8 3. Th initia configuration of a quu is a, b, c, d, and a is in th front
nd. To gt th configuration d, c, b, a, on nds a minimum of (a) 2 dtion
s and 3 additions (b) 3 dtions and 2 additions (c) 3 dtions and 3 addition
s (d) 3 dtions and 4 additions 4. uu can b usd to impmnt (a) radix so
rt (b) quick sort (c) rcursion (d) dpth first sarch
5. Th procss of accssing data stord in a tap is simiar to manipuating dat
a on a (a) stack (b) quu (c) ist (d) hap 6. Which of th foowing can b d
scrib as a pointr? (a) uu (b) uu.Rar (c) uu.Rar^ (d) uu.Front^.I
nfo. 7. Which of th foowing can b dscrib as a intgr? (a) uu (b) uu
.Rar (c) uu.Front (d) uu.Front^.Info. 8. Which of th foowing can b d
scrib as a rcord? (a) uu.Front^.Nxt (b) uu.Rar (c) uu.Front^.Nxt (
d) uu.Front^.Info. 9. In a quu (whr q.rar and q.ront ar pointrs to th
nds of a quu) (a) th numbr of th tota mnts is fixd. (b) If q.rar>q
.front thn quu is mpty (c) th numbr of mnts at any tim is (q.rar q.f
ront 1) (d) Non of ths 10. FRONT = REAR rfrs that a quu is (a) Fu (b) Emp
ty (c) Circuar (d) Non of ths 11. N mnts of a quu ar to b rvrsd u
sing anothr quu. Th numbr of ADD and REMOVE oprations rquird to do so is (a)
2*N (b) 4*N (c) N (d) th task cant b rformd 12. Quu (a) Can b cratd by
stting u an ordinary contigous array to hold th itms (b) can tak car of d
lt oration automatically (c) nd a ointr to add or dlt an itm (d) No
n of ths

Solutions:
1. c 2. a 3. a 4. d 5. b 6. b 7. d 8. a 9. d 10. b 11. d 12. a 7.11 Exrcis Cha
tr - 7 1. What is a quu? Giv on ractical xaml and show why w will cal
l it a quu. 2. Writ a C rogram to imlmnt a quu using (i) Array, (ii) Li
nkd List 3. What is Dynamic Mmory allocation rlatd to quu? writ a C funct
ion using Dynamic Mmory allocation by which you can imlmnt a Quu. 4. What
is a Circular quu? why w us circular quu instad of linar quu? 5. Giv
short not on: (i) Dquu (ii) Pririty Quu
6. How can you imlmnt a quu using stack? writ a C rogram to imlmnt tha
t. 7. Stat on alication of quu and imlmnt it using a C Program
Chatr - 8 LINKED LIST
8.1 Introduction
In th third chatr w hav discussd about array. An array is a static data st
ructur, i.. th total numbr of sacs to k data lmnts in an array whn
vr dfin in a sourc rogram rmains constant during xcution tim of th ro
gram. So, during xcution tim w cant chang th siz of an array. Hnc th s
acs dfind for an array may b wastd during run tim or mor sacs may b r
quird in xcution tim. Now if w allocat mmory sacs during xcution tim
dnding uon th nd of usr, thn it will b mor flxibl. From this asc
t th conct of linkd list is drivd. Linkd list is dynamic data structur.
8.2
Dfinition
A linkd list is a dynamic linar data structur which contains a collction of
data lmnts, calld nods, whr th linarity is maintaind by mans of oint
r.
8.3
Advantags

1) Numbr of nods in a linkd list can b incrasd or dcrasd during run tim
 of a rogram. That is, linkd list is dynamic in natur. 2) In this tchniqu
mmory can b allocatd or d-allocatd whnvr rquird. That is, mmory can b
 utilizd fficintly. 3) Insrtion and dltion orations ar asir and ffi
cint. 4) Many comlx alications (lik olynomial addition or multilication)
can b don mor fficintly.
8.4
Disadvantags
1) Random accss is not ossibl. 2) In ach nod xtra mmory sacs ar ndd
to stor th addrss of th othr nod.
8.5
Orations on Linkd List
Thr ar basic ty of orations associatd with a list data structur. 1. Count
ing total numbr of nods. 2. Insrtion of a nw nod in th list. 3. Dltion o
f an xisting nod from th list. 4. Sarching a scifid nod in th list. 5.
Dislay all nods of th list.
8.6
Tys of Linkd List
Thr ar two tys of linkd list dnding on th numbr of links: 1. Singly L
inkd list: In this list ach nod has only on addrss fild to contain th add
rss of th nxt nod in th list. Nod A Nod B Nod C Nod D 12 B 15 C 18 D 20
NULL
Figur 8.1: An xaml of a singly linkd list with four nods In figur 8.1 ac
h nod has two filds. First on is data fild to stor th information and th
scond fild is link fild which contains th addrss of th nxt nod in th li
st. So from th conct of slf rfrntial structur, th structur dfinition
for ach nod is: struct Nod { int iData; //Data valu of a nod. struct nod *
trNxt; //Pointr to th nxt nod. }; tydf struct Nod SLLNod; //Rnam th
 data ty of ach nod as SLLNod. 2. Doubly Linkd List: Hr ach nod conta
ins two ointr filds, on contains th addrss of th nxt nod and th othr
link ks th track of th rvious nod in th list. Figur 8.2 shows an xam
l of a doubly linkd list. So th structur dfinition of such a nod is: struc
t Nod { struct Nod * trLft; //Pointr to th rvious nod. int iData; //Dat
a valu or information. struct Nod * trRight; //Pointr to th nxt nod. }; t
ydf struct Nod DLLNod; //Rnam th data ty of ach nod as DLLNod.

Nod A NULL 10 B A
Nod B 20 D B 30
Nod D NULL
Figur 8.2: An xaml of a doubly linkd list with thr nods
8.7
Singly linkd list
8.7.1 Counting total numbr of nods
Algorithm 8.1 1. Algorithm fnSLL_Count_Total_Nods(trStart) 2. // Puros : Thi
s algorithm counts th total numbr of nods in a singly linkd list. 3. // Inu
t : trStart is th addrss of th first nod in th list. 4. // Outut : This a
lgorithm rturns total numbr of nods iCount in th list. 5. { 6. SLLNod *trT
m; //Crat a nw ointr trTm of SLLNod ty. 7. trTm = trStart; //In
itializ trTm. 8. iCount = 0; //Initializ countr. 9. whil(trTm != NULL)
//Rat sts 11 and 12 until trTm rachs NULL. 10. { 11. iCount = iCount
+ 1; //Incrmnt valu of iCount. 12. trTm = trTm->trNxt; //Advanc trT
m to nxt nod. 13. } 14. rturn(iCount); //Rturn total numbr of nods. 15.
}//End of Algorithm
How th algorithm 8.1 works: Considr th following list: 10 trStart St 1: (L
in 7) trTm = trStart 10 trTm trStart St 2: (Lin 9 to 13) trTm !=
NULL is tru. So iCount = 1 and trTm is advancd by on nod. 10 20 40 NULL 2
0 40 NULL 20 40 NULL

trStart
trTm
St 3: (Lin 9 to 13) Again trTm != NULL is tru. So iCount = 2 and trTm
is advancd by on nod. 10 trStart 20 40 NULL trTm
St 4: (Lin 9 to 13) Again trTm != NULL is tru. So iCount = 3 and trTm
is advancd by on nod. 10 trStart NULL St 5: Now trTm = NULL. So control
gos to outsid th whil loo in Lin 14 which rturns th valu of iCount (to
tal numbr of nods). 20 40 NULL trTm =
8.7.2 Find th addrss of th nod at scific osition
Algorithm 8.2 1. Algorithm fnSLL_Find_Position(trStart, iPosition) 2. // Puros
 : This algorithm finds th addrss of a scific nod. 3. // Inut : trStart
is addrss of th first nod and addrss of th nod at iPosition in th list is
rquird. 4. // Outut : This algorithm rturns th addrss of th nod and for
non xistnc osition it rturns 0. 5. { 6. SLLNod *trTm; //Crat a nw 
ointr trTm of SLLNod ty. 7. trTm = trStart; //Initializ trTm. 8.
if(iPosition<0 || iPosiotion > fnSLL_ Count_Total_Nods(trStart)) 9. rturn 0;
//If osition is ngativ or gratr than total nods thn rturn 0. 10. for(iCo
untr = 1; iCountr < iPosition; iCountr++) //Go to articular nod. 11. trTm
 = trTm->trNxt; 12. rturn trTm; //Rturn addrss. 13. }// End of Algor
ithm How th algorithm 8.2 works: Considr th following list: 10 20 40 NULL

trStart Suos w want to find th addrss of th third nod in th list. So i
Position = 3. St 1: (Lin 7) trTm = trStart 10 trTm trStart St 2: (L
in 8) Valu of iPosition is not ngativ or not gratr than th total nods. S
o go to Lin 10. 20 40 NULL

St 3: Th for loo of Lin 10 xcuts for 2 tims (1 to 2) and accordingly t
rTm is advancd by two nods in Lin 11. 10 trStart 20 40 NULL trTm
St 4: Now trTm is ointing to th third nod in th list. So rturn trTm
(Lin 12).
8.7.3 Insrting a nod
For th insrtion of a nod in a singly linkd list, w will us a ointr varia
bl, trStart to k th track of th first nod in th list. Initially trStar
t is st to NULL to indicat that th list is mty. Considr th singly linkd
list in figur 8.3. A nw nod trNwNod is to b insrtd aftr th nod trT
m1. Th data valu of th nw nod is 30. 10 20 trTm1 40 NULL

trNwNod Figur 8.3: Insrtion of a nw nod in a singly linkd list Algorithm
8.3 1. Algorithm fnSLL_Insrt (trTm1, iData) 2. //Puros : This algorithm i
nsrts a nw nod in a singl linkd list aftr a givn nod. 3. //Inut : Th n
w nod with data valu iData is to b insrtd aftr nod trTm1. 4. //Outut
: Non. 5. { 6. SLLNod *trNwNod; //Crat a nw ointr for th nw nod. 7
. trNwNod = (SLLNod*) malloc(sizof(SLLNod)); //Crat th nw nod. 8. tr
NwNod->iData = iData; // St th data valu into nw nod. 9. trNwNod->trN
xt = trTm1->trNxt; //Nw nod now oints to nxt nod of givn nod. 10. 
trTm1->trNxt = trNwNod; //Givn nod now oints to nw nod. 11. }// End
of algorithm. How th algorithm 8.3 works: Considr th list of figur 8.3. St
1: trNwNod = (SLLNod*) malloc(sizof(SLLNod)); 10 20 trTm1 40 NULL
trNwNod

St 2: trNwNod->iData = 30 10 20 trTm1 30 trNwNod St 3: trNwNod->


trNxt = trTm1->trNxt; 10 20 trTm1 30 trNwNod St 4: trTm1->trN
xt = trNwNod; 10 trTm1 20 40 NULL 40 NULL 40 NULL
30 trNwNod
8.7.3.1
Insrt at th bginning
Algorithm 8.4 1. Algorithm fnSLL_Insrt_At_Bginning (trStart, iData) 2. //Pur
os : Insrt a nw nod at th bginning of th list. 3. //Inut : trStart is t
h addrss of th first nod and iData is th data valu of nw nod. 4. //Outu
t : This algorithm rturns th addrss of th first nod (trStart). 5. { 6. SLL
Nod *trNwNod; 7. trNwNod = (SLLNod*) malloc(sizof(SLLNod)); //Crat t
h nw nod. 8. trNwNod->iData = iData; //Cois th data valu into nw nod
. 9. trNwNod->trNxt = trStart; //Nw nod now oints to currntly first no
d 10. trStart = trNwNod; //St nw nod as th first nod in th list. 11.
rturn trStart; //Rturn th udatd addrss of th first nod. 12. }// End of
Algorithm
How th algorithm 8.4 works. Considr th following list: trStart 20 Nod2 30 N
ULL

Nod 1 Nod 2 Figur 8.4: A singly linkd list of two nods Suos a nod with
th data valu 10 is to b insrtd at th bginning of th list in figur 8.4.
So th function call is: fnSLLInsrt_At_Bginning(trStart,10) St 1: Crat th
 nw nod. trNwNod = (SLLNod *) malloc(sizof(SLLNod));

trNwNod St 2: Cois th data valu into nw nod. trNwNod->iData = 10 1
0 trNwNod St 3: Link th nw nod to th first nod of th linkd list. tr
NwNod->trNxt = trStart 10 trNwNod 20 trStart 30 NULL
St 4: St nw nod as th first nod in th list. trStart = trNwNod 10 tr
Start=trNwNod 20 30 NULL
8.7.3.2
Insrt at th last of th list
Algorithm 8.5 1. Algorithm fnSLL_ Insrt_At_End (trStart, iData) 2. // Puros
: This algorithm insrts a nod at th nd of th list 3. // Inut : trStart is
th addrss of th first nod and iData is th data valu. 4. // Outut : Non.
5. { 6. SLLNod *trPosition; 7. iTotalNods = fnSLL_Count_Total_Nods(trStart
); //Count total numbr of nods. 8. if(iTotalNods != 0) //If list is not mty
. 9. { 10. trPosition = fnSLL_Find_Position(trStart, iTotalNods); //Gt th a
ddrss of th last nod. 11. fnSLL_Insrt(trPosition, iData); //Insrt nw nod
aftr th nod trPosition. 12. } 13. }//End of Algorithm How th algorithm 8.5
works:

Considr th singly linkd list of figur 8.4. Suos a nw nod with data valu
 40 is to b insrtd at th last of th list in figur 8.4. So th function ca
ll is: fnSLLInsrt_At_End(trStart, 40) St 1: (Lin 7) iTotalNods = 2; St 2
: (Lin 10) trPosition = Nod2 St 3: (Lin 11) fnSLL_Insrt(trPosition, 40)
20 Nod1 30 Nod2 40 NULL
Nod3
8.7.3.3
Insrt at th scific osition
Suos w want to insrt th nw nod at fifth osition in th list. That mans
th nw nod is to b insrtd aftr fourth nod. So first w hav to find th
addrss of th fourth nod aftr which w can insrt th nw nod. Again if th
list is mty or th osition of th nw nod is 1, thn th nw nod is to b i
nsrtd as first nod. Algorithm 8.6 dscribs th total rocdur. Algorithm 8.
6 1. Algorithm fnSLL_Insrt_At_Scific_Position (trStart, iData, iPosition) 2.
// Puros : This algorithm insrts a nw nod at a scific osition of th li
st. 3. // Inut : trStart = th addrss of th first nod. iData = th data val
u. iPosition = th osition whr th nw nod is to b insrtd. 4. // Outut
: This algorithm rturns th addrss of th first nod (trStart). 5. { 6. SLLNo
d *trNwNod, *trPosition; 7. trPosition = fnSLL_Find_Position(trStart, iPo
sition -1); //Gt th addrss of th nod at iPosition -1. 8. iTotal = fnSLL_Cou
nt_Total_Nods(trStart); //Count total numbr of nods. 9. if(iPosition <= iTot
al+1 && iPosition >= 0) //If osition is valid. 10. { 11. if(iPosition == 1 || 
trStart == NULL) //If osition is 1 or list is mty. 12. trStart = fnSLL_Insr
t_At_Bginning (trStart, iData); //Insrt nod at bginning. 13. ls 14. fnSLL
_Insrt(trPosition, iData); //Insrt nw nod aftr th nod trPosition. 15. }
16. ls 17. Not a valid osition; 18. rturn trStart; 19. }//End of Algorithm
8.7.4 Dlting a nod
Considr th following linkd list with thr nods P, Q and R. Suos w hav
to dlt nod Q which is aftr nod P. Now aftr dltion of nod Q, nod R wil
l b th nxt nod of P. Thrfor w hav to stor th addrss of nod R in th
addrss fild of nod P. Algorithm 8.7 dscribs th dltion rocss. trNodP
trNodQ

NULL Nod P Nod Q Nod R


Algorithm 8.7 1. Algorithm fnSLL_Dlt (trNodP, trNodQ) 2. //Puros : This
algorithm dlts an xisting nod from a singl linkd list. 3. //Inut : Nod
trNodQ is to b dltd which is aftr nod trNodP. 4. //Outut : Th data
valu of th nod that has bn dltd. 5. { 6. trNodP->trNxt = trNodQ->
trNxt; // Now nod P oints to th nod nxt to nod Q. 7. trNodQ->trNxt =
NULL //St addrss fild of nod Q to NULL. 8. iData = trNodQ->iData; //Stors
th data valu of th dltd nod. 9. fr(trNodQ); //Rturns th addrss of
nod Q to ha. 10. rturn(iData); //Rturn th data that has bn dltd. 11.
}// End of algorithm. How th algorithm 8.7 works: Considr th following list
with thr nods: Nod P Nod Q 10 Q 20 R trNodP trNodQ
Nod R 40 NULL
St 1: (Lin 6) trNodP->trNxt = trNodQ->trNxt Nod P 10 R 20 trNodP N
od Q R trNodQ Nod R 40 NULL
St 2: (Lin 7) trNodQ->trNxt = NULL Nod P 10 R 20 trNodP St 3: (Lin
8) iData = 20 St 4: (Lin 9) fr(trNodQ) Nod P 10 R trNodP St 5: (Lin
10) Rturn 20(data valu of dltd nod). Nod R 40 NULL Nod Q NULL trNodQ
Nod R 40 NULL

8.7.4.1
Dlt from th bginning
Algorithm 8.8 1. Algorithm fnSLL_Dlt_From_Bginning (trStart) 2. // Puros
: This algorithm dlts th first nod from th list. 3. // Inut : trStart is
th addrss of th first nod in th list. 4. //Outut : Rturns th addrss of
th udatd first nod in th list. 5. { 6. SLLNod *trDltdNod; 7. if(trS
tart == NULL) //If th list is mty. 8. { 9. Thr is nothing to dlt. 10. r
turn; 11. } 12. trDltdNod = trStart; //St th ointr to first nod. 13.
iData = trDltdNod->iData; //Stors th data valu of th dltd nod. 14.
trStart = trStart->trNxt; //Now th scond nod is th first nod of th lis
t. 15. fr(trDltdNod); //Rturn dltd nod to ha. 16. rturn(trStart)
; 17. }//End of Algorithm How th algorithm 8.8 works: Considr th following li
st with thr nods: Nod P Nod Q 10 trStart St 1: (Lin 12) trDltdNod
= trStart Nod P 10 Q 20 trDltdNod trStart St 2: (Lin 13) iData = 10 S
t 3: (Lin 14) trStart = trStart->trNxt Nod P 10 Q trDltdNod St 4:
(Lin 15) fr(trDltdNod) Nod Q 20 R trStart Nod R 40 NULL Nod Q 20 R
trStart Nod R 40 NULL Nod Q R Nod R 40 NULL Q 20 R
Nod R 40 NULL

St 5: (Lin 16) Rturn nw valu of trStart.


8.7.4.2
Dlt from th last
Algorithm 8.9 1. Algorithm fnSLL_Dlt_From_End (trStart) 2. // Puros : This
algorithm dlts th last nod from th list 3. // Inut : trStart is th add
rss of th first nod in th list. 4. // Outut : Non. 5. // Commnts: This al
gorithm works if numbr of nods in th list ar mor than on. If th list cont
ains only on nod, call th function to dlt nod from th bginning of th l
ist. 6. { 7. SLLNod *trNodP, *trNodQ; 8. if(trStart == NULL) //If list is
mty. 9. { 10. Thr is nothing to dlt. 11. rturn; 12. } 13. iTotal = fnSLL
_Count_Total_Nods(trStart); //Count total numbr of nods. 14. if(iTotal > 1)
//If list contains mor than on nods. 15. { 16. trNodP = fnSLL_Find_Position
(trStart, iTotal -1); //Gt th addrss of nod P. 17. trNodQ = fnSLL_Find_Po
sition(trStart, iTotal); //Gt th addrss of nod Q. 18. iData = fnSLL_Dlt(
trNodP, trNodQ); 19. } 20. }//End of Algorithm How th algorithm 8.9 works:
Considr th following list with thr nods: Nod A Nod P 10 trStart St 1:
(Lin 13) iTotal = 3 St 2: (Lin 16) trNodP = fnSLL_Find_Position(trStart,
2) Nod A Nod P 10 trStart P 20 Q trNodP Nod Q 40 NULL P 20 Q
Nod Q 40 NULL
St 3: (Lin 17) trNodQ = fnSLL_Find_Position(trStart, 3) Nod A 10 trStart
P 20 Nod P Q trNodP Nod Q 40 NULL trNodQ

St 4: (Lin 18) iData = fnSLL_Dlt(trNodP, trNodQ) = 40 Nod A 10 P trS


tart Nod P 20 NULL trNodP
8.7.4.3
Dlt from th scific osition
Algorithm 8.10 1. Algorithm fnSLL_Dlt_from_Scific_Position (trStart, iPosi
tion) 2. // Puros : This algorithm dlts th last nod from th list 3. // I
nut : trStart is th addrss of th first nod in th list. iPosition is th 
osition from whr th nod is to b dltd. 4. //Outut : Rturns th udatd
addrss of th first nod in th list. 5. { 6. SLLNod *trNodP, *trNodQ; 7.
iTotal = fnSLL_Count_Total_Nods(trStart); 8. if(iPosition <= iTotal && iPositi
on > 0) //If valid osition. 9. { 10. if(iPosition == 1) // If nod is in th fi
rst osition. 11. trStart = fnSLL_Dlt_From_Bginning (trStart); 12. ls 13
. { 14. trNodP = fnSLL_Find_Position(trStart, iPosition -1); //Gt th addrs
s of nod P. 15. trNodQ = fnSLL_Find_Position(trStart, iPosition); //Gt th
addrss of nod Q. 16. iData = fnSLL_Dlt(trNodP, trNodQ); //Dlt Q and
gt data valu of Q. 17. } 18. } 19. ls 20. Not a valid osition; 21. rturn 
trStart; 22. }//End of Algorithm
8.7.5 Dislay th nods
Algorithm 8.11 1. Algorithm fnSLL_Dislay_Nods(trStart) 2. // Puros : This a
lgorithm dislays all th nods in th list. 3. // Inut : trStart is th addr
ss of th first nod in th list. 4. //Outut : Non. 5. { 6. SLLNod *trTm;
7. trTm = trStart; 8. whil(trTm!=NULL) 9. { 10. rint(trTm->iData); 1
1. trTm = trTm->trNxt;

12. } 13. }//End of Algorithm


8.8
Rvrsing a singly linkd list
Algorithm 8.12 1. Algorithm fnSLL_Rvrs (trStart) 2. // Puros : This algori
thm rvrs all th nods in th list. 3. // Inut : trStart, th addrss of th
 first nod in th list. 4. //Outut : Th nw valu of trStart. 5. { 6. SLLNo
d *trTm1,*trTm2,*trTm3; 7. trTm3 = trStart; 8. trTm2 = NULL; 9.
whil( trTm3 != NULL) 10. { 11. trTm1 = trTm2; 12. trTm2 = trTm3
; 13. trTm3 = trTm3->trNxt; 14. trTm2->trNxt = trTm1; 15. } 16.
trStart = trTm2; 17. rturn trStart; 18. }// End of Algorithm How th algor
ithm 8.12 works: Suos a linkd list with thr nods is givn (figur 8.5). W
 hav to rvrs this list according to th algorithm. 10 20 Figur 8.5: A link
d list of thr nods St 1: Initially trTm3=trStart and trTm2 = NULL.
trTm2 = NULL 10 20 30 NULL 30 NULL

trTm3 = trStart St 2: Chck th condition: trTm3 NULL trTm1 = trTm
2; trTm2 = trTm3; trTm3 = trTm3->trNxt; trTm2->trNxt = trT
m1; trTm1 = NULL 10 NULL 20 30 NULL

trTm2 trStart St 3:


trTm3
Chck th condition: trTm3 NULL trTm1 = trTm2; trTm2 = trTm3; tr
Tm3 = trTm3->trNxt; trTm2->trNxt = trTm1; 10 NULL 20 trTm2 30
NULL

trTm1 trStart St 4:


trTm3
Chck th condition: trTm3 NULL trTm1 = trTm2; trTm2 = trTm3; tr
Tm3 = trTm3->trNxt; trTm2->trNxt = trTm1; trTm3 = NULL 10 NULL
20 trTm1 30 trTm2

trStart St 5:
Now st trStart to trTm2 as currntly trTm2 is th first nod. trStart =
trTm2;
10
NULL
20
30 trStart
8.9
Polynomial using singly linkd list
8.9.1 Rrsntation of olynomial
In rrsntation of a olynomial, thr ar som trms. Each trm has coffici
nt and xonnt. Now w can dfin a structur for ach nod and whnvr rquir
d w can crat such nw nod against ach trm. Thrfor th structur dfini
tion looks lik: struct Polynomial { int iCoff; int iEx;

struct Polynomial *trNxt; }; tydf Polynomial PolyNod; Examl: 4 3 2 5A +


7A + A + 6 Th linkd list rrsntation of th abov olynomial quation is: 5
4 7 3 1 2 6 0 NULL
8.9.2 Crat olynomial list
W know how to and a nod at th nd of a singly linkd list. Now to crat a
olynomial using linkd list, w nd to and th nw nod at th last of th
list. Algorithm 8.13 dscribs how to crat such a olynomial. Algorithm 8.13
1. Algorithm fnCrat_Polynomial(trPoly, iCoff, iEx) 2. // Puros : This alg
orithm crats a nod in a olynomial. 3. // Inut : trPoly is nam of th oly
nomial. iCoff and iEx ar th cofficint and xonnt of th nod rsctivl
y. 4. // Outut : Rturns th starting addrss (trPoly) of th olynomial. 5. {
6. PolyNod *trTm,*trNwNod ; 7. trTm = trPoly; 8. trNwNod = (PolyN
od*) malloc(sizof (PolyNod)) ; 9. if ( trPoly == NULL ) 10. trPoly = trNw
Nod; //St nw nod as first nod if list is mty. 11. ls 12. { 13. whil (
trTm -> trNxt != NULL ) // travrs th ntir linkd list. 14. trTm = 
trTm -> trNxt; 15. trTm -> trNxt = trNwNod; //St nw nod as th n
xt nod of trTm. 16. } 17. trNwNod -> iCoff = iCoff ; // St cofficint
in th nw nod. 18. trTm -> iEx = iEx ; // St xonnt in th nw nod.
19. trTm -> trNxt = NULL ; // St link fild of nw nod to NULL as this is
th last nod. 20. rturn trPoly; //Rturns th addrss of th starting nod.
21. }/ End of Algorithm
Addition of two olynomials
Algorithm 8.14 1. Algorithm fnPolyADD(trPolyA, trPolyB, trPolyC) 2. //Puros
: This algorithm adds two olynomials A and B and stors th rsult in C. 3. //
Inut : trPolyA ointr to th first nod of olynomial A. 4. // : trPolyB oi
ntr to th first nod of olynomial B. 5. // : trPolyC ointr to th first no
d of th rsultant olynomial C. 6. //Outut : Rturns th ointr(trPolyC) to
olynomial C. 7. {

8. PolyNod *trTmA, *trTmB; 9. trTmA = trPolyA; 10. trTmB = trPoly


B; 11. whil(trTmA != NULL && trTmB != NULL) 12. { 13. if(trTmA->iEx =
= trTmB->iEx) 14. { 15. iX = trTmA->iCoff + trTmB->iCoff; 16. if(iX
!= 0) 17. insrt iX and trTmA->iEx (or trTmB->iEx) into C; 18. trTmA
= trTmA->trNxt; 19. trTmB = trTmB->trNxt; 20. } 21. lsif(trTmA
->iEx < trTmB->iEx) 22. { 23. insrt trTmB->iCoff and trTmB->iEx in
to C; 24. trTmB = trTmB->trNxt; 25. } 26. ls 27. { 28. insrt trTmA
->iCoff and trTmA->iEx into C; 29. trTmA = trTmA->trNxt; 30. } 31.
} 32. whil(trTmA != NULL) 33. { 34. insrt trTmA->iCoff and trTmA->iE
x into C; 35. trTmA = trTmA->trNxt; 36. } 37. whil(trTmB != NULL) 3
8. { 39. insrt trTmB->iCoff and trTmB->iEx into C; 40. trTmB = trT
mB->trNxt; 41. } 42. rturn trPolyC; 43. } // End of Algorithm Examl How t
h algorithm 8.14 works. A = 3x7 + 4x4 + 5x3 B = -3x7 + 5x5 + 2x trTmA = trP
olyA
3
7
4
4
5
3
N

trTmB = trPolyB
-3
St 1:
7
5
5
2
1
N

trTmA->iEx = trTmB->iEx;

iX = trTmA->iCoff + trTmB->iCoff = 3 + (-3) = 0; As iX is 0, so no insr


tion into C. trTmA = trTmA->trNxt; trTmB = trTmB->trNxt; trPoly
A trTmA
3
7
4
4
trTmB
5
3
N N

trPolyB
-3
St 2:
7
5
5
2
1

trTmA->iEx < trTmB->iEx; insrt trTmB->iCoff and trTmB->iEx into


C; trTmB = trTmB->trNxt; trPolyA trTmA
3
7
4
4
5
3
N N

trPolyB
trTmB
-3
C
7

5
N
5
2
1
5
St 3:
5

trTmA->iEx > trTmB->iEx; insrt trTmA->iCoff and trTmA->iEx into


C; trTmA = trTmA->trNxt; trPolyA trTmA
3
7
4
4
5
3
N N

trPolyB
trTmB
-3
7
C
5 4
5
2
1
5
St 4:
5
4
N

trTmA->iEx > trTmB->iEx; insrt trTmA->iCoff and trTmA->iEx into


C; trTmA = trTmA->trNxt;

trPolyA
trTmA=NULL
3
7
trPolyB
4
4
5
3
NULL

trTmB
-3 5
St 5: C
7
5 4
5
2
1
NULL
5
4
5
3
NULL
As trTmB NULL insrt trTmB->iCoff and trTmB->iEx into C; trTmB = 
trTmB->trNxt; trPolyA trTmA=NULL
3
7
trPolyB
4
4
5

3
NULL trTmB=NULL
-3 5
C
7
5 4
5
2
1
NULL
5
4
5
3
2
8.9.4 Multilication of two olynomials
1
NULL
Algorithm 8.15 1. Algorithm fnPolyMUL (trPolyA, trPolyB, trPolyC) 2. //Puros
 : This algorithm multilis two olynomials A and B and stors th rsult in C
. 3. //Inut : trPolyA ointr to th first nod of olynomial A. 4. // : trPo
lyB ointr to th first nod of olynomial B. 5. // : trPolyC ointr to th f
irst nod of th rsultant olynomial C. 6. //Outut : Rturns th ointr to o
lynomial C trPolyC. 7. { 8. PolyNod *trTmA, *trTmB; 9. trTmA = trPol
yA; 10. trTmB = trPolyB; 11. if(trPolyA == NULL) //If olynomial A is mty
, thn st olynomial C as B. 12. rturn trPolyB; 13. if(trPolyB == NULL) //If
olynomial B is mty, thn st olynomial C as A. 14. rturn trPolyA; 15. whi
l ( trPolyA != NULL) // for ach trm of th first list A

16. { 17. whil (trPolyB != NULL) 18. // multily ach trm of th scond list
B with a trm of A. 19. { 20. coff1 = trTmA->iCoff * trTmB->iCoff; 21.
x1 = trTmA->iEx + trTmB->iEx; 22. insrt coff1 and x1 into C1; 23.
trTmB = trTmB->trNxt; 24. fnPolyADD (trPolyC, trPolyC1, trPolyC); 25.
} 26. trTmB = trPolyB; // rosition q to th starting of B. 27. trTmA =
trTmA->trNxt; // go to th nxt nod of A. 28. rturn trPolyC; 29. } 30.
}//End of Algorithm
8.10 Advantags and disadvantags of singly linkd list
Advantags: 1. Accssibility of a nod in th forward dirction is asir. 2. In
srtion and dltion of nods ar asir. Disadvantags 1. Accssing th rcdi
ng nod of a currnt nod is not ossibl as thr is no backward travrsal. 2.
Accssing a nod is tim consuming.
8.11 Circular linkd list
If a ointr trP to a nod in a linar list is givn, w cant rach any nods th
at rcd th nod to which trP is ointing. This is th main drawback of th
linar singly linkd list. W can ovrcom this disadvantag by introducing anot
hr kind of list namly circular linkd list. Hr th ointr fild of th last
nod contains th addrss of th first nod in th list instad of NULL. Hnc
starting from th any nod of th list, w can travrs th ntir list. Figur.. show
s a circular linkd list. So w can asily convrt a linar linkd list to circu
lar linkd list by rlacing th NULL ointr in th last nod of th list with
th addrss of its first nod as shown in algorithm 8.16.
Figur: Circular Linkd List Algorithm 8.16 1. Algorithm fnCrat_CLL (trStart)
2. // Puros : This algorithm crats a circular linkd list from a linar list
. 3. // Inut : trStatr is th addrss of th first nod in th list. 4. // Out
ut : Non. 5. { 6. SLLNod *trTm; 7. trTm = trStart;

8. whil(trTm->trNxt != NULL) 9. trTm = trTm ->trNxt; 10. trTm->


trNxt = trStart; 11. }// End of algorithm
//Rat st 9 until trTm rachs to last nod. //Advanc th valu of trT
m to nxt nod. //Sts th ointr of last nod to th first nod in th list.
8.12 Doubl linkd list
Although a circular linkd list has advantags ovr a linar list, it still has
svral drawbacks: (i) On cant travrs such a list backward. (ii) A nod cant b
dltd from a circular linkd list (as wll as linar linkd list), givn only
a ointr to that nod. In cass whr ths facilitis ar rquird th aro
riat data structur is a doubl linkd list. Th nod structur of such a list
has bn discussd in th sction 8.6. Lik singly linkd list, hr also w tak
 a variabl trStart which contains th addrss of th first nod in th list.
Initially valu of trStart is NULL to indicat that th list is mty. DLLNod
*trStart = NULL; 8.12.1 Counting total numbr of nods Algorithm 8.17 1. Algori
thm fnDLL_Count_Total_Nods(trStart) 2. // Puros : This algorithm counts th
total numbr of nods in a doubl linkd list. 3. // Inut : trStart is th add
rss of th first nod in th list. 4. // Outut : This algorithm rturns total
numbr of nods iCount in th list. 5. { 6. DLLNod *trTm; //Crat a nw oi
ntr trTm of DLLNod ty. 7. trTm = trStart; //Initializ ointr. 8. iC
ount = 0; //Initializ countr. 9. whil(trTm != NULL) //Rat sts 11 and
12 until trTm rachs NULL. 10. { 11. iCount = iCount + 1; //Incrmnt valu
of iCount. 12. trTm = trTm->trRight; //Advanc trTm to nxt nod. 13.
} 14. rturn(iCount); //Rturn total numbr of nods. 15. }//End of Algorithm 8.
12.2 Find th addrss of th nod at scific osition Algorithm 8.18 1. Algorit
hm fnDLL_Find_Position(trStart, iPosition) 2. // Puros : This algorithm finds
th addrss of a scific nod. 3. // Inut : trStart is addrss of th first
nod and addrss of th nod at iPosition in th list is rquird. 4. // Outut
: This algorithm rturns th addrss of th dsird nod. 5. { 6. DLLNod *trT
m; 7. trTm = trStart; 8. for(iCountr = 1; iCountr < iPosition && trTm!
=NULL; iCountr++) 9. trTm = trTm->trRight; 10. rturn trTm;

11. }// End of Algorithm 8.12.3 Insrting a nod into a doubl linkd list Consi
dr th doubl linkd list in figur 8.2. Suos a nw nod C is to b insrtd
aftr nod B. Th data valu of th nw nod is 25. Algorithm 8.19 1. Algorithm
fnDLL_Insrt (trNodB, iData) 2. //Puros : This algorithm insrts a nw nod
C aftr nod B in a doubl linkd list. 3. //Inut : trNodB is th addrss of
nod B. iData is data valu of nod C. 4. //Outut : Non. 5. { 6. DLLNod *tr
NodC; //trNodC is th addrss of nod C. 7. trNodC = (DLLNod*) malloc(siz
of(DLLNod)); //Crat nod C. 8. trNodC->iData = iData; // St th data valu
into nw nod C. 9. trNodC->trLft = trNodB; //St B as th lft nod of C
. 10. trNodC->trRight = trNodB->trRight; //St D as th right nod of C. 1
1. trNodB->trRight->trLft = trNodC; //St C as th right nod of D. 12. 
trNodB->trRight = trNodC; //St C as th lft nod of B. 13. }// End of algo
rithm. How th algorithm 8.19 works. Considr th list of figur 8.2. Nod C is
to b insrtd aftr nod B. St 1: trNodC = (DLLNod*) malloc(sizof(DLLNod
));

trNodC St 2: trNodC ->iData = 25 25 trNodC St 3: trNodC->trLft = 


trNodB; Nod A NULL 10 B A Nod B 20 D Nod C B 25 trNodC St 4: trNodC->
trRight = trNodB->trRight; Nod A NULL 10 B A Nod B 20 D B 30 Nod D NULL B
30 Nod D NULL

trNodB Nod C B 25 trNodC St 5: trNodB->trRight->trLft = trNodC; No


d A NULL 10 B A Nod B 20 trNodB Nod C B 25 trNodC St 6: trNodB->trRi
ght = trNodC; Nod A NULL 10 B A Nod B 20 trNodB Nod C B 25 trNodC D C C
30 Nod D NULL D D C 30 Nod D NULL D
8.12.3.1
Insrt at th bginning
Algorithm 8.20 1. Algorithm fnDLL_Insrt_At_Bginning (trStart, iData) 2. //Pur
os : Insrt a nw nod P at th bginning of th list. 3. //Inut : trStart i
s th addrss of th first nod and iData is th data valu of nw nod P. 4. //
Outut : This algorithm rturns th addrss of th first nod (trStart). 5. { 6
. DLLNod *trNodP; //trNodP is th addrss of nod P. 7. trNodP = (DLLNod
*) malloc(sizof(DLLNod)); //Crat th nw nod. 8. trNodP->iData = iData; /
/Cois th data valu into nw nod. 9. trNodP->trLft = NULL; //St NULL to
lft link of P. 10. trNodP->trRight = trStart; //St currntly first nod a
s th lft nod of P. 11. trStart->trLft = trNodP; //St P as th lft nod
of currntly first nod. 12. trStart = trNodP; //Now P is th first nod in
th list. 13. rturn trStart; //Rturn th udatd addrss of th first nod. 1
4. }// End of Algorithm

How th algorithm 8.20 works. Considr th list of figur 8.2. Nod P is to b i
nsrtd at th bginning in th list. Suos data valu of P is 25. St 1: tr
NodP = (DLLNod*) malloc(sizof(DLLNod));

trNodP St 2: trNodP ->iData = 25 25 trNodP St 3: trNodP->trLft = N


ULL; NULL 25
trNodP St 4: trNodP->trRight = trStart; Nod A NULL 10 Nod P NULL 25 A
B A Nod B 20 D B 30 Nod D NULL
trNodP St 5: trStart->trLft = trNodP; Nod A 10 Nod P NULL 25 A Nod B
A 20 Nod D 30 NULL
P
B
D
B

trNodP
8.12.3.2
Insrt at th last of th list
Algorithm 8.21 1. Algorithm fnDLL_ Insrt_At_End (trStart, iData) 2. // Puros
: This algorithm insrts a nod P at th nd of th list.

3. // Inut : trStart is th addrss of th first nod and iData is th data va
lu of P. 4. // Outut : Non. 5. { 6. DLLNod *trPosition; 7. iTotalNods = fn
DLL_Count_Total_Nods(trStart); //Count total numbr of nods. 8. if(iTotalNod
s != 0) //If list is not mty. 9. { 10. trPosition = fnDLL_Find_Position(trSt
art, iTotalNods); //Gt th addrss of th last nod. 11. fnDLL_Insrt(trPosit
ion, iData); //Insrt nw nod aftr th nod trPosition. 12. } 13. }//End of A
lgorithm How th algorithm 8.21 works. Considr th singly linkd list of figur
8.2. Suos a nw nod with data valu 40 is to b insrtd aftr nod D. St
1: iTotalNods = 3; St 2: trPosition = Nod D St 3: fnDLL_Insrt(trPositi
on, 40) Nod A 10 Nod B A 20 Nod D 30 P Nod P D 25 NULL
P
B
D
B
8.12.3.3 Insrt at th scific osition
Algorithm 8.22 1. Algorithm fnDLL_Insrt_At_Scific_Position (trStart, iData,
iPosition) 2. // Puros : This algorithm insrts a nw nod at a scific osit
ion of th list. 3. // Inut : trStart is addrss of th first nod. iData is d
ata valu of nw nod. iPosition is th osition whr th nw nod is to b ins
rtd. 4. // Outut : This algorithm rturns th addrss of th first nod (trS
tart). 5. { 6. DLLNod *trNwNod, *trPosition; 7. trPosition = fnDLL_Find_Po
sition(trStart, iPosition -1); //Gt th addrss of th nod at osition -1. 8.
iTotal = fnDLL_Count_Total_Nods(trStart); //Count total numbr of nods. 9. i
f(iPosition <= iTotal+1 && iPosition >= 0) //If osition is valid. 10. { 11. if(
iPosition == 1 || trStart == NULL) //If osition is 1 or list is mty.

12.

trStart = fnDLL_Insrt_At_Bginning (trStart, iData); bginning. ls fnDLL_In


srt(trPosition, iData);
//Insrt nod at
13.
14.
//Insrt nw nod aftr th nod trPosition.
15. } 16. ls 17. Not a valid osition; 18. rturn trStart; 19. }//End of Algo
rithm
8.12.4
Dlting a nod form a doubl linkd list
Considr th doubl linkd list shown in figur 8.2. Suos nod B is to b dl
td. So now nod A oints to nod D and nod D oints to nod A and nod B no m
or oints to any nod i.. th links of B ar NULL. (1) Nod A NULL 10 trNodA
D A Nod B 20 D A Nod D 30 NULL

trNodB (2)
trNodD
For link 1: trNodD->trLft = trNodA. Now addrss of nod D, trNodD, is st
ord in th right link fild of nod B i.. trNodB->trRight = trNodD and al
so trNodB->trLft = trNodA. Now w can rwrit th statmnt for link 1 as
trNodB->trRight->trLft = trNodB->trlft For link 2: Similarly w can writ
 for link 2trNodB->trLft->trRight = trNodB->trRight Now st th link fi
lds of B to NULL. trNodB->trLft = trNodB->trRight = NULL (1) Nod A NULL
10 trNodA Algorithm 8.23 dscribs th dltion rocss. Algorithm 8.23 1. Al
gorithm fnDLL_Dlt(trNodB) 2. //Puros : This algorithm dlts an xisting
nod B from a doubl linkd list. D NULL Nod B 20 NULL A Nod D 30 NULL

trNodB (2)
trNodD

3. //Inut : trNodB is th addrss of nod B. 4. //Outut : Th data valu of


th dltd nod. 5. { 6. iData = trNodB->iData; //Stors th data valu of th
 dltd nod. 7. trNodB->trRight->trLft = trNodB->trlft; 8. trNodB>trLft->trRight = trNodB->trRight; 9. trNodB->trLft = trNodB->trRig
ht = NULL; 10. fr(trNodB); //Rturns th addrss of nod Q to ha. 11. rtu
rn(iData); 12. }// End of algorithm
8.12.4.1
Dlt from th bginning
Algorithm 8.24 1. Algorithm fnDLL_Dlt_From_Bginning(trStart) 2. // Puros
: This algorithm dlts th first nod from th list. 3. // Inut : trStart is
th addrss of th first nod in th list. 4. //Outut : Rturns th addrss of
th udatd first nod in th list. 5. { 6. DLLNod *trDltdNod; 7. if(trS
tart == NULL) //If th list is mty. 8. { 9. Thr is nothing to dlt. 10. r
turn; 11. } 12. trDltdNod = trStart; //St th ointr to first nod. 13.
iData = trStart->iData; //Stors th data valu of th dltd nod. 14. trSta
rt = trStart->trRight; //Now th scond nod is th first nod of th list. 15
. trStart->trLft = NULL; 16. trDltdNod->trRight = NULL; 17. fr(trDl
tdNod); //Rturn dltd nod to ha. 18. rturn(trStart); 19. }//End of Al
gorithm
8.12.4.2
Dlt from th last
Algorithm 8.25 1. Algorithm fnDLL_Dlt_From_End (trStart) 2. // Puros : Thi
s algorithm dlts th last nod from th list 3. // Inut : trStart is th ad
drss of th first nod in th list. 4. // Outut : Th data valu of th last n
od. 5. // Commnts: This algorithm works if numbr of nods in th list ar mor
 than on. If th list contains only on nod, call th function to dlt nod
from th bginning of th list. 6. { 7. DLLNod *trLastNod; 8. if(trStart ==
NULL) //If list is mty. 9. { 10. Thr is nothing to dlt.

11. 12. 13. 14. 15.


rturn; } iTotal = fnDLL_Count_Total_Nods(trStart); //Count total numbr of no
ds. if(iTotal > 1) //If list contains mor than on nods. { 16. trLastNod =
fnDLL_Find_Position(trStart, iTotal); //Gt th addrss of nod Q. 17. trLastN
od->trLft->trRight = NULL; //St NULL to right link fild of scond last nod
. 18. trLastNod->trLft = NULL; //St NULL to th lft link fild of last no
d. 19. iData = trLastNod->iData; 20. fr(trLastNod); 21. } 22. rturn iDat
a; 23. }//End of Algorithm
8.12.4.3
Dlt from th scific osition
Algorithm 8.26 1. Algorithm fnDLL_Dlt_from_Scific_Position (trStart, iPosi
tion) 2. // Puros : This algorithm dlts th last nod of th list. 3. // In
ut : trStart is th addrss of th first nod in th list. iPosition is th o
sition from whr th nod is to b dltd. 4. //Outut : Rturns th udatd a
ddrss of first nod in th list. 5. { 6. DLLNod *trPosition; 7. iTotal = fnDL
L_Count_Total_Nods(trStart); 8. if(iPosition <= iTotal && iPosition > 0) //If
valid osition. 9. { 10. if(iPosition == 1) //If nod is in th first osition.
11. trStart = fnDLL_Dlt_From_Bginning(trStart); 12. lsif(iPosition == iT
otal) //If th nod is th last nod. 13. iData = fnDLL_Dlt_From_End(trStart
); 14. ls 15. { 16. trPosition = fnDLL_Find_Position(trStart, iPosition); //
Gt th addrss of th nod. 17. iData = fnDLL_Dlt(trPosition); 18. } 19. }
20. ls 21. Not a valid osition; 22. rturn trStart; 23. }//End of Algorithm
8.12.5
Dislay th nods
Algorithm 8.27 1. Algorithm fnDLL_Dislay_Nods(trStart) 2. // Puros : This a
lgorithm dislays all th nods in th list.

3. // Inut : trStart is th addrss of th first nod in th list. 4. //Outut
: Non. 5. { 6. DLLNod *trTm; 7. trTm = trStart; //Initializ ointr.
8. whil(trTm!=NULL) //Rat sts 10 and 11 until trTm is NULL. 9. { 10.
rint(trTm->iData); //Print th data. 11. trTm = trTm->trRight; //Adv
anc trTm to nxt nod. 12. } 13. }//End of Algorithm
8.12.6 Advantags and disadvantags of doubl linkd list
Advantags: 1. Both way travrsal ar ossibl hr. 2. A nod can b dltd fr
om a doubl linkd list, givn only a ointr to that nod. Disadvantags 1. Hr
 insrtion is slightly mor comlx. /* C cod to imlmnt th orations on a
singly linkd list and rvrs th list*/ /* Fil nam : SLL.c */ #includ <std
io.h> #includ <conio.h> #includ <alloc.h> struct Nod { int iData; struct nod
*trNxt; }; tydf struct Nod SLLNod;
//Data valu of a nod. //Pointr to th nxt nod. //Rnam th data ty of a
ch nod as SLLNod.
//Prototy Dclaration int fnSLL_Count_Total_Nods(SLLNod *); SLLNod* fnSLL_F
ind_Position(SLLNod *, int ); void fnSLL_Insrt (SLLNod *, int ); SLLNod *fnS
LL_Insrt_At_Bginning (SLLNod *, int ); void fnSLL_Insrt_At_End (SLLNod *, i
nt ); SLLNod *fnSLL_Insrt_At_Scific_Position (SLLNod *, int , int); int fnS
LL_Dlt (SLLNod *, SLLNod *); SLLNod *fnSLL_Dlt_From_Bginning (SLLNod
*); void fnSLL_Dlt_From_End (SLLNod *); SLLNod *fnSLL_Dlt_from_Scific_
Position (SLLNod *, int); SLLNod *fnSLL_Rvrs (SLLNod *); void fnSLL_Disla
y_Nods(SLLNod *); int fnSLL_Count_Total_Nods(SLLNod *trStart) // Puros :
This Function counts th total numbr of nods in a singly linkd list. // Inut
: trStart is th addrss of th first nod in th list.

// Outut : This function rturns total numbr of nods iCount in th list. { in
t iCount; SLLNod *trTm; //Crat a nw ointr trTm of SLLNod ty. trT
m = trStart; //Initializ trTm. iCount = 0; //Initializ countr. whil(t
rTm != NULL) //Rat sts 11 and 12 until trTm rachs NULL. { iCount = i
Count + 1; //Incrmnt valu of iCount. trTm = trTm->trNxt; //Advanc t
rTm to nxt nod. } rturn(iCount); //Rturn total numbr of nods. }//End of
Function SLLNod* fnSLL_Find_Position(SLLNod *trStart, int iPosition) // Puro
s : This Functionfinds th addrss of a scific nod. // Inut : trStart is a
ddrss of th first nod and addrss of th nod at iPosition in th list is rq
uird. // Outut : This Function rturns th addrss of th nod and for non xi
stnc osition it rturns 0. { int iCountr; SLLNod *trTm; //Crat a nw 
ointr trTm of SLLNod ty. trTm = trStart; //Initializ trTm. if(iPo
sition<0 || iPosition > fnSLL_Count_Total_Nods(trStart)) rturn 0; //If ositi
on is ngativ or gratr than total nods thn rturn 0. for(iCountr = 1; iCou
ntr < iPosition; iCountr++) //Go to articular nod. trTm = trTm->trNx
t; rturn trTm; //Rturn addrss. }// End of Function void fnSLL_Insrt (SLLN
od *trTm1, int iData) //Puros : This function insrts a nw nod in a sing
l linkd list aftr a givn nod. //Inut : Th nw nod with data valu iData
is to b insrtd aftr nod trTm1. //Outut : Non. { SLLNod *trNwNod; /
/Crat a nw ointr for th nw nod. trNwNod = (SLLNod*) malloc(sizof(SL
LNod)); //Crat th nw nod. trNwNod->iData = iData; // St th data valu
into nw nod. trNwNod->trNxt = trTm1->trNxt; //Nw nod now oints t
o nxt nod of givn nod. trTm1->trNxt = trNwNod; //Givn nod now oin
ts to nw nod. }// End of function SLLNod *fnSLL_Insrt_At_Bginning (SLLNod
*trStart, int iData) //Puros : Insrt a nw nod at th bginning of th list
. //Inut : trStart is th addrss of th first nod and iData is th data valu
 of nw nod. //Outut : This function rturns th addrss of th first nod (
trStart). { SLLNod *trNwNod; trNwNod = (SLLNod*) malloc(sizof(SLLNod))
; //Crat th nw nod. trNwNod->iData = iData; //Cois th data valu into
nw nod. trNwNod->trNxt = trStart; //Nw nod now oints to currntly fi
rst nod trStart = trNwNod; //St nw nod as th first nod in th list. r
turn trStart; //Rturn th udatd addrss of th first nod.

}// End of function void fnSLL_Insrt_At_End (SLLNod *trStart, int iData) // P


uros : This function insrts a nod at th nd of th list // Inut : trStart
is th addrss of th first nod and iData is th data valu. // Outut : Non.
{ int iTotalNods; SLLNod *trPosition; iTotalNods = fnSLL_Count_Total_Nods(
trStart); //Count total numbr of nods. if(iTotalNods != 0) //If list is not
mty. { trPosition = fnSLL_Find_Position(trStart, iTotalNods); //Gt th add
rss of th last nod. fnSLL_Insrt(trPosition, iData); //Insrt nw nod aftr
th nod trPosition. } }//End of function SLLNod *fnSLL_Insrt_At_Scific_Po
sition (SLLNod *trStart, int iData, int iPosition) // Puros : This function
insrts a nw nod at a scific osition of th list. // Inut : trStart = th
addrss of th first nod. iData = th data valu. iPosition = th osition wh
r th nw nod is to b insrtd. // Outut : This function rturns th addrss
of th first nod (trStart). { int iTotal; SLLNod *trNwNod, *trPosition;
trPosition = fnSLL_Find_Position(trStart, iPosition -1); //Gt th addrss of
th nod at iPosition -1. iTotal = fnSLL_Count_Total_Nods(trStart); //Count to
tal numbr of nods. if(iPosition <= iTotal+1 && iPosition >= 0) //If osition i
s valid. { if(iPosition == 1 || trStart == NULL) //If osition is 1 or list is
mty. trStart = fnSLL_Insrt_At_Bginning (trStart, iData); //Insrt nod at
bginning. ls fnSLL_Insrt(trPosition, iData); //Insrt nw nod aftr th no
d trPosition. } ls rintf("Not a valid osition\n"); rturn trStart; }//End
of function int fnSLL_Dlt (SLLNod *trNodP, SLLNod *trNodQ) //Puros :
This function dlts an xisting nod from a singl linkd list. //Inut : Nod
 trNodQ is to b dltd which is aftr nod trNodP. //Outut : Th data va
lu of th nod that has bn dltd. { int iData; trNodP->trNxt = trNodQ
->trNxt; // Now nod P oints to th nod nxt to nod Q. trNodQ->trNxt =
NULL; //St addrss fild of nod Q to NULL. iData = trNodQ->iData; //Stors t
h data valu of th dltd nod. fr(trNodQ); //Rturns th addrss of nod
Q to ha. rturn(iData); //Rturn th data that has bn dltd. }// End of f
unction.

SLLNod *fnSLL_Dlt_From_Bginning (SLLNod *trStart) // Puros : This funct


ion dlts th first nod from th list. // Inut : trStart is th addrss of
th first nod in th list. //Outut : Rturns th addrss of th udatd first
nod in th list. { int iData; SLLNod *trDltdNod; if(trStart == NULL) //I
f th list is mty. { rintf("Thr is nothing to dlt\n"); rturn trStart;
} trDltdNod = trStart; //St th ointr to first nod. trDltdNod->t
rNxt = NULL; iData = trDltdNod->iData; //Stors th data valu of th dl
td nod. trStart = trStart->trNxt; //Now th scond nod is th first nod
of th list. fr(trDltdNod); //Rturn dltd nod to ha. rturn(trStar
t); }//End of function void fnSLL_Dlt_From_End (SLLNod *trStart) // Puros
: This function dlts th last nod from th list // Inut : trStart is th
addrss of th first nod in th list. // Outut : Non. // Commnts: This funct
ion works if numbr of nods in th list ar mor than on. If th list contains
only on nod, call th function to dlt nod from th bginning of th list.
{ int iTotal,iData; SLLNod *trNodP, *trNodQ; if(trStart == NULL) //If lis
t is mty. { rintf("Thr is nothing to dlt\n"); rturn; } iTotal = fnSLL_C
ount_Total_Nods(trStart); //Count total numbr of nods. if(iTotal > 1) //If l
ist contains mor than on nods. { trNodP = fnSLL_Find_Position(trStart, iTo
tal -1); //Gt th addrss of nod P. trNodQ = fnSLL_Find_Position(trStart, i
Total); //Gt th addrss of nod Q. iData = fnSLL_Dlt(trNodP, trNodQ); }
}//End of function SLLNod *fnSLL_Dlt_from_Scific_Position (SLLNod *trSt
art, int iPosition) // Puros : This function dlts th last nod from th li
st // Inut : trStart is th addrss of th first nod in th list. iPosition i
s th osition from whr th nod is to b dltd. //Outut : Rturns th uda
td addrss of th first nod in th list. { SLLNod *trNodP, *trNodQ; int i
Total,iData; iTotal = fnSLL_Count_Total_Nods(trStart);

if(iPosition <= iTotal && iPosition > 0) //If valid osition. { if(iPosition ==
1) // If nod is in th first osition. trStart = fnSLL_Dlt_From_Bginning (
trStart); ls { trNodP = fnSLL_Find_Position(trStart, iPosition -1); //Gt
th addrss of nod P. trNodQ = fnSLL_Find_Position(trStart, iPosition); //G
t th addrss of nod Q. iData = fnSLL_Dlt(trNodP, trNodQ); //Dlt Q an
d gt data valu of Q. } } ls rintf("Not a valid osition\n"); rturn trStar
t; }//End of function SLLNod *fnSLL_Rvrs (SLLNod *trStart) // Puros : Th
is function rvrs all th nods in th list. // Inut : trStart, th addrss
of th first nod in th list. // Outut : Th nw valu of trStart. { SLLNod
*trTm1,*trTm2,*trTm3; trTm3 = trStart; trTm2 = NULL; whil( trT
m3 != NULL) { trTm1 = trTm2; trTm2 = trTm3; trTm3 = trTm3->
trNxt; trTm2->trNxt = trTm1; } trStart = trTm2; rturn trStart; }/
/ End of Function void fnSLL_Dislay_Nods(SLLNod *trStart) // Puros : This
function dislays all th nods in th list. // Inut : trStart is th addrss
of th first nod in th list. // Outut : Non. { SLLNod *trTm; trTm = 
trStart; whil(trTm!=NULL) { rintf("%d\n",trTm->iData); trTm = trTm
->trNxt; } }//End of function void main(void) { SLLNod *trStart=NULL;

int choic,iData,iPosition; clrscr(); do { rintf("1. Insrt lmnt at bgining


\n"); rintf("2. Insrt lmnt at nd ositon\n"); rintf("3. Insrt at th s
cific osition\n"); rintf("4. Dislay\n"); rintf("5. Dlt from th bgining
\n"); rintf("6. Dlt from th last\n"); rintf("7. Dlt th lmnt from th
 scific osition\n"); rintf("8. Rvrs th list\n"); rintf("9. Exit\n"); 
rintf("Entr your choic\n"); scanf("%d",&choic); switch(choic) { cas 1: rin
tf("Entr th itm\n"); scanf("%d",&iData); trStart = fnSLL_Insrt_At_Bginning
(trStart, iData); brak; cas 2: if(trStart!=NULL) { rintf("Entr th itm\n
"); scanf("%d",&iData); fnSLL_Insrt_At_End(trStart, iData); } ls rintf("For
insrtion into mty list choos otion 1\n"); brak; cas 3: rintf("Entr th
scific osition and th itm\n " ); scanf("%d%d", &iPosition, &iData); trSta
rt = fnSLL_Insrt_At_Scific_Position (trStart,iData,iPosition); brak; cas 4
: rintf("\nTh Elmnts in th list ar\n"); fnSLL_Dislay_Nods(trStart); ri
ntf("\n*****************************\n"); brak; cas 5: trStart = fnSLL_Dlt
_From_Bginning (trStart); brak; cas 6: if(fnSLL_Count_Total_Nods(trStart)=
=1)

{ rintf("Thr is only on nod in th list. Choos ithr otion 5 or otion 7
\n"); brak; } fnSLL_Dlt_From_End(trStart); brak; cas 7: rintf("\nEntr t
h osition of th lmnt to b dltd\n"); scanf("%d",&iPosition); trStart =
fnSLL_Dlt_from_Scific_Position (trStart,iPosition); brak; cas 8: trSta
rt = fnSLL_Rvrs(trStart); brak; cas 9: xit(); dfault: rintf("\nWrong ch
oic\n"); } }whil(1); } /* C cod to imlmnt th orations on a Doubl link
d list */ /* Fil nam : DLL.c */ #includ<stdio.h> #includ<conio.h> struct Nod
 { struct Nod * trLft; int iData; struct Nod * trRight; }; tydf struct
Nod DLLNod;
//Pointr to th rvious nod. //Data valu or information. //Pointr to th n
xt nod. //Rnam th data ty of ach nod as DLLNod.
//Prototy Dclaration int fnDLL_Count_Total_Nods(DLLNod *); DLLNod* fnDLL_F
ind_Position(DLLNod *, int ); void fnDLL_Insrt (DLLNod *, int ); DLLNod *fnD
LL_Insrt_At_Bginning (DLLNod *, int ); void fnDLL_Insrt_At_End (DLLNod *, i
nt ); DLLNod *fnDLL_Insrt_At_Scific_Position (DLLNod *, int , int); int fnD
LL_Dlt (DLLNod *); DLLNod *fnDLL_Dlt_From_Bginning (DLLNod *); int fnD
LL_Dlt_From_End (DLLNod *); DLLNod *fnDLL_Dlt_from_Scific_Position (DL
LNod *, int); void fnDLL_Dislay_Nods(DLLNod *); int fnDLL_Count_Total_Nods(
DLLNod *trStart) // Puros : This function counts th total numbr of nods i
n a doubl linkd list.

// Inut : trStart is th addrss of th first nod in th list. // Outut : Th
is function rturns total numbr of nods iCount in th list. { int iCount=0; DL
LNod *trTm; //Crat a nw ointr trTm of DLLNod ty. trTm = trSta
rt; //Initializ ointr. iCount = 0; //Initializ countr. whil(trTm != NUL
L) //Rat sts 11 and 12 until trTm rachs NULL. { iCount = iCount + 1; /
/Incrmnt valu of iCount. trTm = trTm->trRight; //Advanc trTm to n
xt nod. } rturn(iCount); //Rturn total numbr of nods. }//End of Function DL
LNod *fnDLL_Find_Position(DLLNod *trStart, int iPosition) // Puros : This f
unction finds th addrss of a scific nod. // Inut : trStart is addrss of
th first nod and addrss of th nod at iPosition in th list is rquird. //
Outut : This function rturns th addrss of th dsird nod. { int iCountr;
DLLNod *trTm; trTm = trStart; for(iCountr = 1; iCountr < iPosition &&
trTm!=NULL; iCountr++) trTm = trTm->trRight; rturn trTm; }// End
of Function void fnDLL_Insrt (DLLNod *trNodB, int iData) //Puros : This fu
nction insrts a nw nod C aftr nod B in a doubl linkd list. //Inut : trN
odB is th addrss of nod B. iData is data valu of nod C. //Outut : Non. {
DLLNod *trNodC; //trNodC is th addrss of nod C. trNodC = (DLLNod*) m
alloc(sizof(DLLNod)); //Crat nod C. trNodC->iData = iData; // St th dat
a valu into nw nod C. trNodC->trLft = trNodB; //St B as th lft nod
of C. trNodC->trRight = trNodB->trRight; //St D as th right nod of C. 
trNodB->trRight->trLft = trNodC; //St C as th right nod of D. trNodB>trRight = trNodC; //St C as th lft nod of B. }// End of function. DLLNod
 *fnDLL_Insrt_At_Bginning (DLLNod *trStart, int iData) //Puros : Insrt a
nw nod P at th bginning of th list. //Inut : trStart is th addrss of t
h first nod and iData is th data valu of nw nod P. //Outut : This functio
n rturns th addrss of th first nod (trStart). { DLLNod *trNodP; //trNo
dP is th addrss of nod P. trNodP = (DLLNod*) malloc(sizof(DLLNod)); //C
rat th nw nod. trNodP->iData = iData; //Cois th data valu into nw no
d. trNodP->trLft = NULL; //St NULL to lft link of P. trNodP->trRight =
trStart; //St currntly first nod as th lft nod of P.

trStart->trLft = trNodP; trStart = trNodP; rturn trStart; }// End of F


unction
//St P as th lft nod of currntly first nod. //Now P is th first nod in t
h list. //Rturn th udatd addrss of th first nod.
void fnDLL_Insrt_At_End(DLLNod *trStart, int iData) // Puros : This functio
n insrts a nod P at th nd of th list. // Inut : trStart is th addrss of
th first nod and iData is th data valu of P. // Outut : Non. { int iTotal
Nods; DLLNod *trPosition; iTotalNods = fnDLL_Count_Total_Nods(trStart); //
Count total numbr of nods. if(iTotalNods != 0) //If list is not mty. { trP
osition = fnDLL_Find_Position(trStart, iTotalNods); //Gt th addrss of th l
ast nod. fnDLL_Insrt(trPosition, iData); //Insrt nw nod aftr th nod tr
Position. } }//End of Function DLLNod *fnDLL_Insrt_At_Scific_Position (DLLNo
d *trStart, int iData, int iPosition) // Puros : This function insrts a nw
nod at a scific osition of th list. // Inut : trStart is addrss of th
first nod. iData is data valu of nw nod. iPosition is th osition whr th
nw nod is to b insrtd. // Outut : This function rturns th addrss of th
 first nod (trStart). { int iTotal; DLLNod *trNwNod, *trPosition; trPos
ition = fnDLL_Find_Position(trStart, iPosition -1); //Gt th addrss of th no
d at osition -1. iTotal = fnDLL_Count_Total_Nods(trStart); //Count total num
br of nods. if(iPosition <= iTotal+1 && iPosition >= 0) //If osition is valid
. { if(iPosition == 1 || trStart == NULL) //If osition is 1 or list is mty.
trStart = fnDLL_Insrt_At_Bginning (trStart, iData); //Insrt nod at bginni
ng. ls fnDLL_Insrt(trPosition, iData); //Insrt nw nod aftr th nod trP
osition. } ls rintf("\nNot a valid osition"); rturn trStart; }//End of Fun
ction int fnDLL_Dlt(DLLNod *trNodB) //Puros : This function dlts an 
xisting nod B from a doubl linkd list. //Inut : trNodB is th addrss of n
od B. //Outut : Th data valu of th dltd nod. { int iData; iData = trNo
dB->iData; //Stors th data valu of th dltd nod. trNodB->trRight->tr
Lft = trNodB->trLft; trNodB->trLft->trRight = trNodB->trRight; trN
odB->trLft = trNodB->trRight = NULL;

fr(trNodB); rturn(iData); }// End of function


//Rturns th addrss of nod Q to ha.
DLLNod *fnDLL_Dlt_From_Bginning(DLLNod *trStart) // Puros : This functi
on dlts th first nod from th list. // Inut : trStart is th addrss of t
h first nod in th list. //Outut : Rturns th addrss of th udatd first n
od in th list. { int iData; DLLNod *trDltdNod; if(trStart == NULL) //If
th list is mty. { rintf("\nThr is nothing to dlt"); rturn; } trDlt
dNod = trStart; //St th ointr to first nod. iData = trStart->iData; //S
tors th data valu of th dltd nod. trStart = trStart->trRight; //Now t
h scond nod is th first nod of th list. trStart->trLft = NULL; trDlt
dNod->trRight = NULL; fr(trDltdNod); //Rturn dltd nod to ha. r
turn(trStart); }//End of Function int fnDLL_Dlt_From_End (DLLNod *trStart)
// Puros : This function dlts th last nod from th list // Inut : trSt
art is th addrss of th first nod in th list. // Outut : Th data valu of
th last nod. // Commnts: This function works if numbr of nods in th list a
r mor than on. If th list contains only on nod, call th function to dlt
 nod from th bginning of th list. { int iTotal,iData; DLLNod *trLastNod;
if(trStart == NULL) //If list is mty. { rintf("\nThr is nothing to dlt
"); rturn; } iTotal = fnDLL_Count_Total_Nods(trStart); //Count total numbr o
f nods. if(iTotal > 1) //If list contains mor than on nods. { trLastNod =
fnDLL_Find_Position(trStart, iTotal); //Gt th addrss of nod Q. trLastNod>trLft->trRight = NULL; //St NULL to right link fild of scond last nod. 
trLastNod->trLft = NULL; //St NULL to th lft link fild of last nod. iDat
a = trLastNod->iData; fr(trLastNod); } rturn iData; }//End of Function DL
LNod *fnDLL_Dlt_from_Scific_Position (DLLNod *trStart, int iPosition)

// Puros : This function dlts th last nod of th list. // Inut : trStar
t is th addrss of th first nod in th list. iPosition is th osition from w
hr th nod is to b dltd. //Outut : Rturns th udatd addrss of first
nod in th list. { int iTotal,iData; DLLNod *trPosition; iTotal = fnDLL_Count
_Total_Nods(trStart); if(iPosition <= iTotal && iPosition > 0) //If valid osi
tion. { if(iPosition == 1) //If nod is in th first osition. trStart = fnDLL_
Dlt_From_Bginning(trStart); ls if(iPosition == iTotal) //If th nod is t
h last nod. iData = fnDLL_Dlt_From_End(trStart); ls { trPosition = fnDL
L_Find_Position(trStart, iPosition); //Gt th addrss of th nod. iData = fnD
LL_Dlt(trPosition); } } ls rintf("\nNot a valid osition"); rturn trSta
rt; }//End of Function void fnDLL_Dislay_Nods(DLLNod *trStart) // Puros :
This function dislays all th nods in th list. // Inut : trStart is th add
rss of th first nod in th list. //Outut : Non. { DLLNod *trTm; trTm
= trStart; //Initializ ointr. whil(trTm!=NULL) //Rat sts 10 and 11
until trTm is NULL. { rintf("%d\t",trTm->iData); //Print th data. trT
m = trTm->trRight; //Advanc trTm to nxt nod. } }//End of Function voi
d main(void) { DLLNod *trStart=NULL; int choic,iData,iPosition; clrscr(); do
{ rintf("1. Insrt lmnt at bgining \n"); rintf("2. Insrt lmnt at nd 
ositon\n"); rintf("3. Insrt at th scific osition\n"); rintf("4. Dislay\n
"); rintf("5. Dlt from th bgining\n");

rintf("6. Dlt from th last\n"); rintf("7. Dlt th lmnt from th sc
ific osition\n"); rintf("8. Exit\n"); rintf("Entr your choic\n"); scanf("%d
",&choic); switch(choic) { cas 1: rintf("Entr th itm\n"); scanf("%d",&iDa
ta); trStart = fnDLL_Insrt_At_Bginning (trStart, iData); brak; cas 2: if(
trStart!=NULL) { rintf("Entr th itm\n"); scanf("%d",&iData); fnDLL_Insrt_At
_End(trStart, iData); } ls rintf("For insrtion into mty list choos otio
n 1\n"); brak; cas 3: rintf("Entr th scific osition and th itm\n " );
scanf("%d%d", &iPosition, &iData); trStart = fnDLL_Insrt_At_Scific_Position
(trStart,iData,iPosition); brak; cas 4: rintf("\nTh Elmnts in th list ar
\n"); fnDLL_Dislay_Nods(trStart); rintf("\n*****************************\n"
); brak; cas 5: trStart = fnDLL_Dlt_From_Bginning (trStart); brak; cas
6: if(fnDLL_Count_Total_Nods(trStart)==1) { rintf("Thr is only on nod in
th list. Choos ithr otion 5 or otion 7\n"); brak; } fnDLL_Dlt_From_En
d(trStart); brak; cas 7: rintf("\nEntr th osition of th lmnt to b d
ltd\n"); scanf("%d",&iPosition); trStart = fnDLL_Dlt_from_Scific_Positio
n (trStart,iPosition);

brak; cas 8: xit(1); dfault: rintf("\nWrong choic\n"); } }whil(1); } /* P


rogram to add two olynomials maintaind as linkd lists. */ /* Fil nam : Poly
Add.c */ #includ <stdio.h> #includ <conio.h> #includ <alloc.h> /* structur r
rsnting a nod of a linkd list. Th nod can stor trm of a olynomial */
struct Polynomial { int iCoff; int iEx; struct Polynomial *trNxt; }; tydf
struct Polynomial PolyNod; PolyNod * fnCrat_Polynomial(PolyNod *, int , in
t); void fnDislayPoly ( PolyNod *); PolyNod * fnPolyADD(PolyNod *, PolyNod
*, PolyNod *); PolyNod *fnCrat_Polynomial(PolyNod *trPoly, int iCoff, int
iEx) // Puros : This function crats a nod in a olynomial. // Inut : tr
Poly is nam of th olynomial. iCoff and iEx ar th cofficint and xonnt
of th nod rsctivly. // Outut : Rturns th starting addrss (trPoly) of
th olynomial. { PolyNod *trTm,*trNwNod ; trTm = trPoly; trNwNod
= (PolyNod*) malloc(sizof (PolyNod)) ; if ( trPoly == NULL ) trPoly = trN
wNod; //St nw nod as first nod if list is mty. ls { whil ( trTm ->
trNxt != NULL ) // travrs th ntir linkd list. trTm = trTm -> trN
xt; trTm -> trNxt = trNwNod; //St nw nod as th nxt nod of trTm
. } trNwNod -> iCoff = iCoff ; // St cofficint in th nw nod. trNwNo
d -> iEx = iEx ; // St xonnt in th nw nod. trNwNod -> trNxt = NUL
L ; // St link fild of nw nod to NULL as this is th last nod. rturn trPo
ly; }// End of function

void fnDislayPoly ( PolyNod *trPoly ) // Puros : This function dislays a 


olynomial. // Inut : trPoly is th starting addrss of th list. // Outut : N
on. { if(trPoly==NULL) { rintf("List is mty"); rturn; } /* travrs till t
h nd of th linkd list */ whil ( trPoly != NULL ) { rintf ( "%dx^%d + ", 
trPoly -> iCoff, trPoly -> iEx ) ; trPoly = trPoly -> trNxt ; } rintf (
"\b\b\b " ) ; /* rass th last colon */ }//End of Function PolyNod *fnPolyADD
(PolyNod *trPolyA, PolyNod *trPolyB, PolyNod *trPolyC) //Puros : This fu
nction adds two olynomials A and B and stors th rsult in C. //Inut : trPol
yA ointr to th first nod of olynomial A. // : trPolyB ointr to th first
nod of olynomial B. // : trPolyC ointr to th first nod of th rsultant
olynomial C. //Outut : Rturns Non. { int iX; PolyNod *trTmA, *trTmB;
trTmA = trPolyA; trTmB = trPolyB; whil(trTmA != NULL && trTmB !=
NULL) { if(trTmA->iEx == trTmB->iEx) { iX = trTmA->iCoff + trTmB>iCoff; if(iX != 0) trPolyC = fnCrat_Polynomial(trPolyC, iX, trTmA->iEx
); trTmA = trTmA->trNxt; trTmB = trTmB->trNxt; } ls if(trTm
A->iEx < trTmB->iEx) { trPolyC = fnCrat_Polynomial(trPolyC, trTmB->i
Coff, trTmB->iEx); trTmB = trTmB->trNxt; } ls { trPolyC = fnCra
t_Polynomial(trPolyC, trTmA->iCoff, trTmA->iEx); trTmA = trTmA->
trNxt; }

} whil(trTmA != NULL) { trPolyC = fnCrat_Polynomial(trPolyC, trTmA->i


Coff, trTmA->iEx); trTmA = trTmA->trNxt; } whil(trTmB != NULL)
{ trPolyC = fnCrat_Polynomial(trPolyC, trTmB->iCoff, trTmB->iEx); t
rTmB = trTmB->trNxt; } rturn trPolyC; } // End of function void main( )
{ PolyNod *trPolyA, *trPolyB, *trPolyC; int i = 0,iChoic,iCoff,iEx ; tr
PolyA = trPolyB = trPolyC = NULL ; /* mty linkd lists */ clrscr(); whil(1)
{ rintf("\n 1. Add trm in first olynomial"); rintf("\n 2. Show first olyno
mial"); rintf("\n 3. Add trm in scond olynomial"); rintf("\n 4. Show scond
olynomial"); rintf("\n 5. Add two olynomials"); rintf("\n 6. Exit"); rintf
("\nEntr your choic"); scanf("%d",&iChoic); switch(iChoic) { cas 1: rintf(
"\nEntr cofficint and xonnt"); scanf("%d%d",&iCoff,&iEx); trPolyA = fnC
rat_Polynomial(trPolyA,iCoff,iEx); brak; cas 2: fnDislayPoly(trPolyA);
brak; cas 3: rintf("\nEntr cofficint and xonnt"); scanf("%d%d",&iCoff,
&iEx); trPolyB = fnCrat_Polynomial(trPolyB,iCoff,iEx); brak; cas 4: fnD
islayPoly(trPolyB); brak; cas 5: trPolyC=NULL; trPolyC = fnPolyADD(trPoly
A,trPolyB,trPolyC); fnDislayPoly (trPolyC) ; /* dislays th rsultant olyn
omial */

brak; cas 6: xit(1); dfault: rintf("\nWrong choic"); } } } /* Program to a


dd two olynomials maintaind as linkd lists. */ /* Fil nam : PolyMul.c */ #i
nclud <stdio.h> #includ <conio.h> #includ <alloc.h> /* structur rrsnting
a nod of a linkd list. Th nod can stor trm of a olynomial */ struct Poly
nomial { int iCoff; int iEx; struct Polynomial *trNxt; }; tydf struct Pol
ynomial PolyNod; PolyNod * fnCrat_Polynomial(PolyNod *, int , int); void fn
DislayPoly ( PolyNod *); PolyNod * fnPolyADD(PolyNod *, PolyNod *, PolyNod
*); PolyNod *fnCrat_Polynomial(PolyNod *trPoly, int iCoff, int iEx) // P
uros : This function crats a nod in a olynomial. // Inut : trPoly is nam
 of th olynomial. iCoff and iEx ar th cofficint and xonnt of th nod
 rsctivly. // Outut : Rturns th starting addrss (trPoly) of th olyno
mial. { PolyNod *trTm,*trNwNod; trTm = trPoly; trNwNod = (PolyNod
*) malloc(sizof (PolyNod)) ; if ( trPoly == NULL ) trPoly = trNwNod; //S
t nw nod as first nod if list is mty. ls { whil ( trTm -> trNxt !=
NULL ) // travrs th ntir linkd list. trTm = trTm -> trNxt; trTm
-> trNxt = trNwNod; //St nw nod as th nxt nod of trTm. } trNwNo
d -> iCoff = iCoff ; // St cofficint in th nw nod. trNwNod -> iEx =
iEx ; // St xonnt in th nw nod. trNwNod -> trNxt = NULL ; // St l
ink fild of nw nod to NULL as this is th last nod. rturn trPoly; }// End
of function

void fnDislayPoly ( PolyNod *trPoly ) // Puros : This function dislays a 


olynomial. // Inut : trPoly is th starting addrss of th list. // Outut : N
on. { if(trPoly==NULL) { rintf("List is mty"); rturn; } /* travrs till t
h nd of th linkd list */ whil ( trPoly != NULL ) { rintf ( "%dx^%d + ", 
trPoly -> iCoff, trPoly -> iEx ) ; trPoly = trPoly -> trNxt ; } rintf (
"\b\b\b " ) ; /* rass th last colon */ }//End of Function PolyNod *fnPolyADD
(PolyNod *trPolyA, PolyNod *trPolyB, PolyNod *trPolyC) //Puros : This fu
nction adds two olynomials A and B and stors th rsult in C. //Inut : trPol
yA ointr to th first nod of olynomial A. // : trPolyB ointr to th first
nod of olynomial B. // : trPolyC ointr to th first nod of th rsultant
olynomial C. //Outut : Rturns Non. { int iX; PolyNod *trTmA, *trTmB;
trTmA = trPolyA; trTmB = trPolyB; whil(trTmA != NULL && trTmB !=
NULL) { if(trTmA->iEx == trTmB->iEx) { iX = trTmA->iCoff + trTmB>iCoff; if(iX != 0) trPolyC = fnCrat_Polynomial(trPolyC, iX, trTmA->iEx
); trTmA = trTmA->trNxt; trTmB = trTmB->trNxt; } ls if(trTm
A->iEx < trTmB->iEx) { trPolyC = fnCrat_Polynomial(trPolyC, trTmB->i
Coff, trTmB->iEx); trTmB = trTmB->trNxt; } ls { trPolyC = fnCra
t_Polynomial(trPolyC, trTmA->iCoff, trTmA->iEx); trTmA = trTmA->
trNxt; }

} whil(trTmA != NULL) { trPolyC = fnCrat_Polynomial(trPolyC, trTmA->i


Coff, trTmA->iEx); trTmA = trTmA->trNxt; } whil(trTmB != NULL)
{ trPolyC = fnCrat_Polynomial(trPolyC, trTmB->iCoff, trTmB->iEx); t
rTmB = trTmB->trNxt; } rturn trPolyC; } // End of function PolyNod *fn
PolyMUL (PolyNod *trPolyA, PolyNod *trPolyB, PolyNod *trPolyC) //Puros :
This function multilis two olynomials A and B and stors th rsult in C. //
Inut : trPolyA ointr to th first nod of olynomial A. // : trPolyB oint
r to th first nod of olynomial B. // : trPolyC ointr to th first nod of
th rsultant olynomial C. //Outut : Rturns th ointr to olynomial C trPo
lyC. { PolyNod *trTmA, *trTmB,*trPolyC1=NULL,*trPolyC2; int coff1,x1
; trTmA = trPolyA; trTmB = trPolyB; if(trPolyA == NULL) //If olynomial
A is mty, thn st olynomial C as B. rturn trPolyB; if(trPolyB == NULL) /
/If olynomial B is mty, thn st olynomial C as A. rturn trPolyA; trPolyC
1 = (PolyNod*)malloc(sizof(PolyNod)); trPolyC1->trNxt = NULL; whil ( trT
mA != NULL) // for ach trm of th first list A { whil (trTmB != NULL) //
multily ach trm of th scond list B with a trm of A. { coff1 = trTmA->
iCoff * trTmB->iCoff; x1 = trTmA->iEx + trTmB->iEx; trPolyC1->iC
off = coff1; trPolyC1->iEx = x1; trTmB = trTmB->trNxt; trPolyC2 =
trPolyC; trPolyC = NULL; trPolyC = fnPolyADD (trPolyC2, trPolyC1, trPolyC
); } trTmB = trPolyB; // rosition q to th starting of B. trTmA = trT
mA->trNxt; // go to th nxt nod of A. } fr(trPolyC1); rturn trPolyC; }
//End of function

void main( void) { PolyNod *trPolyA, *trPolyB, *trPolyC; int iChoic,iCoff,


iEx ; trPolyA = trPolyB = trPolyC = NULL ; /* mty linkd lists */ clrscr()
; whil(1) { rintf("\n 1. Add trm in first olynomial"); rintf("\n 2. Show fi
rst olynomial"); rintf("\n 3. Add trm in scond olynomial"); rintf("\n 4. S
how scond olynomial"); rintf("\n 5. Multily two olynomials"); rintf("\n 6.
Exit"); rintf("\nEntr your choic"); scanf("%d",&iChoic); switch(iChoic) {
cas 1: rintf("\nEntr cofficint and xonnt"); scanf("%d%d",&iCoff,&iEx);
trPolyA = fnCrat_Polynomial(trPolyA,iCoff,iEx); brak; cas 2: fnDislayP
oly(trPolyA); brak; cas 3: rintf("\nEntr cofficint and xonnt"); scanf(
"%d%d",&iCoff,&iEx); trPolyB = fnCrat_Polynomial(trPolyB,iCoff,iEx); br
ak; cas 4: fnDislayPoly(trPolyB); brak; cas 5: trPolyC = NULL; trPolyC =
fnPolyMUL(trPolyA,trPolyB,trPolyC); fnDislayPoly (trPolyC) ; /* dislays th
 rsultant olynomial */ brak; cas 6: xit(1); dfault: rintf("\nWrong choic
"); } } } 8.13 MCQ Chatr 8 Qustions No. 1 to No. 2 ar basd on th followin
g doubly linkd list and its data structur.

1. What would b th corrct statmnt(s), whn th doubly linkd list is mty?
(a) Had.nxt=tail (b) Tail.rv=Had (c) Currnt=nill (d) All of ths 2. Whic
h of th following corrctly dscrib(s) th sts to dlt lmnt b from th
abov doubly linkd list? (a) Currnt.nxt.nxt.rv=Currnt.rv, Currnt.nxt
= Currnt.nxt.nxt (b) Currnt.nxt = Currnt.rv.nxt, Currnt.nxt.nxt.rv
=Currnt.rv (c)Currnt.nxt=Currnt.nxt.nxt, Currnt.nxt.nxt.rv=Currnt.
nxt.rv (d) Currnt.nxt=tail, Had.nxt=Currnt.nxt.rv 3. In linkd list,
th logical ordr of lmnts (a) is sam as thir hysical arrangmnt. (b). is
dtrmind by thir hysical m:rangmnt. (c) can not b dtrmind from thir
hysical arrangmnt (d) Non of ths. 4. Dirct or random accss of lmnt is
not ossibl in (a) linkd list (b) array (c) string (d) Non of ths. 5. Odd
man out (in linkd list) (a) modify (c) to dtrmin if it is mty
(b) (d)
rlac Non of ths
6. Th nth nod in singly linkd list, is accssd via (whr n> 1) (a) th had
nod (b) th tail nod (c) ( n - 1) nods (d) Non of ths 7. In linkd list,
th succssiv lmnts (a) must occuy contiguous sac in mmory (b) nd not
occuy contiguous sac in mmory . (c) must not occuy contiguous sac in mmo
ry (d) Non of ths 8. Linar ordr in linkd list is rovidd through (a) ind
x numbr

(b) th imlid osition of th nod (c) ointr (d) Non of ths 9. Null oint
r is usd to tll (a) nd of linkd list (c) th linkd list is mty
(b) mty ointr fild of a structur (d) All of th abov
10. List ointr variabl in linkd list contains addrss of th (a) following n
od in th list (b) currnt nod in th list (c) first nod in th list (d) Non
of ths. 11. Undrflow condition in linkd list may occur whn attmting to (
a) insrt a nw nod whn thr is no fr sac for it. (b) dlt a non-xist
nt nod in th list. (c) dlt a nod in mty list (d) Non of ths 12. Ovrf
low condition in linkd list may occur whn attmting to (a) crat a nod whn
fr sac ool is mty (b) travrs th nods whn fr sac ool is mty (
c) crat a nod whn linkd list is mty (d) Non of ths 13. Bcaus of lin
ar structur of th linkd list having natural linar ordring, thr is similar
ity btwn linkd list and array in (a) insrtion of a nod (b) dltion of a n
od (c) travrsal of lmnts of list (d) non of ths 14. Sarching a linkd l
ist rquirs linkd list b cratd (a) in sortd ordr only (b) in any ordr (c
) without undrflow condition (d) Non of ths 15. Coying all or art of link
d list consists of (a) taking a null string and adding aroiat lmnts to th
 list on by on. (b) taking a null string and utting th addrss of th bgin
ning of th list (c) changing only addrss of th addrss of bginning of th li
st. (d) Non of ths. 16. Dltion of a nod in linkd list involvs king tr
ack of th addrss of th nod(a) which immdiatly follows th nod that is to
b dltd. (b) which immdiatly rcds th nod that is to b dltd (c) th
at is to b dltd (d) Non of ths 17. Hadr of a linkd list is a scial n
od at th

(a) nd of th linkd list (c) bginning of th linkd list
(b) at th middl of th linkd list (d) Non of ths
18. Hadr linkd list in which last nod contains th null ointr is calld (a
) groundd hadr list (b) circular hadr list (c) gnral hadr list (d) Non
of ths 19. Hadr linkd list in which last nod oints to th hadr nod is
calld (a) groundd hadr list (b) circular hadr list (c) gnral hadr lis
t (d) Non of ths 20. Polynomials in mmory may b maintaind through (a) link
d list with hadr nod (b) on dimnsional array (c) stack (d) Non of ths 2
1. Having addrss of th nod to b dltd in doubl linkd list, th nod can
b dltd (a) without travrsing th list (b) only aftr travrsing th list fr
om th had (c) only travrsing th list (from th tail (d) Non of ths. 22. R
rsnting th olynomial in mmory using linkd list rquirs ach nod having
(a) two filds (b) thr filds (c) mor than thr filds (d) Non of ths 23
. Th n - th nod in a singly linkd list is accssd via (a) Th first n - 1 no
ds . (b) 1 nod - only th had (c) 1 nod - only tlt tail (d) th first n + 1
nods 24. It is rquird to insrt a nod at th nd of a singly connctd link
d list having ",," nods. How many nods ar to b travrsd for this insrtion
? (a) 1 (b) n/2 (c) II (d) non of th abov 25. Thr could b two rrsntati
ons of a circular linkd list. In th first rrsntation th list is idntifi
d by a ointr ointing to th bginning of th list as shown blow. In th sco
nd rrsntation, th list is idntifid by a ointr ointing to th nd of th
 list as shown blow. Which of th following statmnts is NOT tru about ths
two rrsntations? (a) In th first rrsntation, insrtion at th front (i
.. bfor th nod X1) rquirs travrsing th list. (b) In th first rrsnt
ation, insrtion at th rar (i.. aftr th nod X3) rquirs travrsing th li
st. (c) In th scond rrsntation, insrtion only at th front (and not at th
 rar) dos not rquir travrsing th list. (d) In th scond rrsntation,
insrtion only at th front (and not at th rar) dos not rquir travrsing th
 list. 26. Linkd lists ar not suitabl data structurs for which on of th f
ollowing roblm (a) insrtion sort (GATE-1994)

(b) binary sarch (c) radix sort (d) olynomial maniulation. 27. Considr th f
ollowing statmnts. Stat fals statmnt. (GATE-1996) (a) First-in-first-out t
ys of th comutations ar fficintly suortd by STACKS. (b) Imlmnting L
ISTS on linkd lists is mor fficint than imlmnting Lists on an array for a
lmost all th basic LIST orations. (c) Imlmnting QUEUES on a circular array
is mor fficint than imlmnting QUEUES on a linar array with two indics.
(d) Last-in-Last-out tys of th comutations ar fficintly suortd by QUEU
ES. 28. Th concatnation of two lists is to b rformd in O(1) tim. Which of
th following imlmntations of a list should b usd? (GATE-1997) (a) singly
linkd list (b) doubly linkd list (c) circular doubly linkd list (d) array im
lmntation of list 29. A olynomial (x) is such that  (0) = 5, (1) = 4, (2)
= 9 and (3) = 20. Th minimum dgr it can hav is (GATE-1997) (a) 1 (c) 3 (
b) 2 (d) 4 30. In which of th following cass, linkd list imlmntation of s
ars matrics consums th sam mmory sac as th convntional way of storing
th ntir array? (Assum all data-tys nd th sam amount of storag.) (a) 5
x 6 matrix with 9 non-zro ntris (b) 5 x 6 matrix with 8 non-zro ntris (c)
6 x 5 matrix with 8 non-zro ntris (d) 6 x 5 matrix with 9 non-zro ntris 3
1. Th linkd list imlmntation of sars matrics is surior to th gnrali
zd do vctor mthod bcaus it is (a) conctually asir (b) comltly dyna
mic (c) fficint in accssing an ntry (d) fficint if th sars matrix is a
band matrix 32. In a circularly linkd list organization, insrtion of a rcord
involvs th modification of (a) no ointr (b) 1 ointr (c) 2 ointrs (d) 3 
ointrs 33. Linkd lists ar not suitabl for imlmnting (a) insrtion sort (b
) binary sarch (c) radix sort (d) olynomial maniulation 34. Th concatnation
of two lists is to b rformd in 0(1) tim. Which of th following imlmnta
tions of a list could b usd? (a) Singly linkd list (b) Doubly linkd list (c)
Circular doubly linkd list (d) Array imlmntation of list 35. Writ a statm
nt to do th following "Mak B oint to th last nod in th list" (a) B: = B^.
Nxt; (b) B:=nd; (c) B : = last; (d) B : = B^.Info.Ky; 36. Writ a statmnt t
o do th following "Mak List oint to an mty list" (a) List: = mty; (b) Lis
t: = NIL; (c) List: = Zro; (d) Non of ths.

37. In a linkd list (a) ach link contains a ointr to th nxt link (b) an ar
ray of ointrs oint to th links (c) ach link contains data or a ointr to d
ata (d) th links ar stord in an array.
Solutions:
1. d 2. c 16. b 17. c 31. a,b 32. c 8.13 3. c 18. a 33. b 4. a 19. b 34. c 5. c
20. a 35. d 6. a 21. a 36. d 7. b 22. b 37. a 8. c 23. b 9. a 24. d 10. a 25. c
11. c 26. b 12. a 27. d 13. c 28. c 14. a 29. c 15. a 30. c
Exrcis Chatr 8
1. What is a singl Linkd List? What ar th advantags and disadvantags of si
ngl Linkd List? 2. Considr a singl Linkd List contains th following lmn
ts: roll numbr: intgr, nam: string of max 25 char, avg no: float rrsnt a
singl linkd link with th lmnts abov in C languag. 3. Writ down C funct
ions to: (i) insrt an lmnt into (ii) dlt an lmnt from (a) bginning of
a singl linkd list (b) middl osition of a singl linkd list (a) bginning
of a singl linkd list (b) middl osition of a singl linkd list
4. Writ an algorithm and a C function to rvrs a singl linkd list. 5. How c
an you rrsnt a olynomial using singl linkd list. Stat an olynomial xam
l and show how can you rrsnt th olynomial using linkd list using a C r
ogram. 6. What is a Doubl Linkd List? What ar th advantags and disadvantag
s of Doubl Linkd List? 7. Considr a Doubl Linkd List contains th following
lmnts: roll numbr: intgr, nam: string of max 25 char, avg no: float rr
snt a doubl linkd link with th lmnts abov in C languag. 8. Writ down
C functions to: (i) insrt an lmnt into (ii) dlt an lmnt from 9. Dfin
and diffrntiat circular and doubl linkd list. (a) bginning of a doubl li
nkd list (b) middl osition of a doubl linkd list (a) bginning of a doubl
linkd list (b) middl osition of a doubl linkd list
CHAPTER 9 RECURSION
9.1 Dfinition
Rcursion mans rocss of solving a roblm by rducing it to smallr vrsions
of itslf. Mor rcisly, rcursion is a tchniqu that allows us to brak down
a roblm into on or mor sub roblms that ar similar

in form of original roblm. It is a mthod for solving thos roblms which fal
l into th divid and conqur aradigm. Suos P is a rocdur containing ith
r a call statmnt to itslf or a call statmnt to a scond rocdur that may
vntually rsult in a call statmnt back to th original rocdur P. Thn P
is calld a rcursiv rocdur. So that th rogram will not continu to run in
dfinitly, a rcursiv rocdur must hav th following two rortis: i) Th
r must b crtain critria calld bas critria for which th rocdur dos no
t call itslf. ii) Each tim th rocdur dos call itslf (dirctly or indirc
tly) it must b closr to th bas critria. A rcursiv rocdur with ths tw
o rortis is said to b wll-dfind. Th rcursiv rograms though ar small
and asy to writ but ar not fficint in trms of th tim and sac comlxi
ty. Rcursion may b imlmntd by mans of stack.
9.2
Tys of rcursion

Rcursion is of two tys dnding on whthr a function calls itslf from its
lf or whthr two functions call on anothr mutually. Th formr is calld dir
ct rcursion and lattr is calld indirct rcursion. Thus two tys of rcursio
ns ar:(i) Dirct rcursion (ii) Indirct rcursion Both tys of rcursions ar
shown diagrammatically blow: fn1() { ; fn1(); } } fn2() { fn1(); ; } (a) Dire
n (b) Indirect recursion fn1() { ; ; fn2();
Figure 9.1: Examples of direct and indirect recursion Depending on the number of
recursive calls recursion can be further categorized as: (a) Linear recursion (
b) Binary recursion (c) Multiple recursion
9.2.1 Linear recursion
Linear recursion can be defined as follows: (I) It performs a single recursive c
all. If there are more than one recursive calls in a procedure then only one of
them should be chosen based on some tests or criteria. (II) Define each recursiv
e call, so that it makes progress to base case.

9.2.2 Binary recursion


Binary recursion can be defined as follows: (I) It performs two recursive calls
for each non
base case. (II) Define each recursive call, so that it makes progre
ss to base case.
9.2.3 Multiple recursion
Multiple recursion can be defined as follows: (I) It performs many recursive cal
ls. (II) Define each recursive call, so that it makes progress to base case.
9.3
Some recursive algorithms
In this section we will go through some recursive algorithms. But at first we wi
ll see how a recursive algorithm is written. Suppose a problem has the following
recursive definition: F(x) = c for G(x)

(1) = F(H(x)) for other v


alues of x

(2) For the above problem condition 1 is the base case a


nd condition 2 implies recursive call. So for x=G(x) return the value c to the c
alling function and for the other values of x calls the same function with the n
ew argument H(x). Algorithm fnF(x) { if(x==G(x)) return c; else fnF(H(x); }// En
d of Algorithm Using the above said concept we can implement any recursive funct
ion for any recursive solution of a problem.
9.3.1 Factorial function
The recursive definition to calculate the factorial value of a number is as foll
ows: Fact (n) = 1 for n=0 and n=1 = n*Fact (n
1) for n>1 Algorithm 9.1 1. Algori
thm fnFact (n) 2. // Purpose : This algorithm calculates the factorial of a posi
tive number. 3. // Input : n is the given number. 4. // Output : This function r
eturns
1 for negative value of n, otherwise return factorial of n. 5. { 6. if(n
<0) 7. return
1; 8. if(n == 1 || n == 0 ) // base criteria 9. return 1; 10. els
e 11. return (n*fnFact(n
1)); // recursive call 12. }// End of Algorithm In the
algorithm 9.1, line 6 checks for a negative n. If n is negative then line 7 retu
rns
1. Line 8 returns 1 if n is 0 or 1. Otherwise line 11 solves the problem re
cursively. Example 9.1 shows how the algorithm works. Example 9.1: Let us calcul
ate the value of 4! using the above recursive algorithm: fnFact(4) = 4* fnFact(3
) fnFact(3) = 3*fnFact(2)

fnFact(2) = 2*fnFact(1) fnFact(1) = 1 fnFact(2) = 2*1 = 2 fnFact(3) = 3*2 = 6 fn


Fact(4) = 4*6 = 24
9.3.2 G.C.D. of two numbers
According to Euclids algorithm, the recursive definition the gcd value of two pos
itive integers x and y is as follows: Gcd(x,y) = Gcd(y,x) if x<y =y if xy and x%y
=0 = Gcd(x,x%y) if x>y Algorithm 9.2 1. Algorithm fnGcd (x, y) 2. //Purpose : Th
is algorithm calculates the gcd value of two numbers. 3. //Input : x and y are t
he two positive integers and x>y. 4. //Output : The calculated gcd value of x an
d y. 5. { 6. if (x>=y && x%y==0) //Base criteria 7. return y; 8. else 9. return(
fnGcd(y, x%y)); //Recursive call 10. }// End of algorithm Example 9.2: Let us sh
ow the execution of above algorithm to calculate the gcd value of 10 and 6. fnGc
d(10,6) fnGcd(6,10%6) fnGcd(4, 6%4) As here 4>2 and 4%2=0, fnGcd(4,2) returns 2.
2 2 2
9.3.3 Exponential power
We can define a recursive function to compute the value of x as follows: Power(x
,n) = 1 if n = 0 =x if n = 1 = Power(x, n/2) * Power(x, n/2) if n is even and n
> 1 = x * Power(x, (n
1)/2) * Power(x, (n
1)/2) if n is odd and n > 1 Algorithm
9.3 1. Algorithm fnPower(x,n) n 2. //Purpose : This algorithm computes x . 3. //
Input : x is mantissa and n is exponent. n 4. //Output : The value of x . 5. { 6
. if (n == 0) //Base criteria. 7. return 1; 8. if (n == 1) //Base criteria. 9. r
eturn x; 10. if (n>1 && n%2 == 0) 11. return(fnPower(x,n/2) * fnPower(x,n/2));
n
//Recursive call.

12. if (n>1 && n%2 == 1) 13. return(x * fnPower(x,(n


1)/2) * fnPower(x,(n
1)/2))
; 14. }// End of algorithm.
//Recursive call.
6
Example 9.3: Figure 9.2 shows the execution of algorithm 9.3 to calculate the va
lue of 2 and the order of the function calls are shown with each and every funct
ion call within third braces. 64 [1] fnPower(2,6)
[2] 8 fnPower(2,3)
*
8 [5] fnPower(2,3)
2
[3] 2 * fnPower(2,1)
*
2 [4] fnPower(2,1)
2
[6] 2 * fnPower(2,1)
*
[7] 2 fnPower(2,1)
return 2
return 2
return 2
6
return 2
Figure 9.2: A recursion tree to compute the value of 2 .
9.3.4 Fibonacci sequence
The celebrated Fibonacci sequence is as follows: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
, 55 The recursive definition to calculate the nth number in the above series can b
e stated as follows: Fib(n) = n for n= 0 or 1 = Fib(n
2) + Fib(n
1) for n>1 Algo
rithm 9.4 1. Algorithm fnFib(n) 2. // Purpose : This algorithm finds the nth num
ber in the Fibonacci series. 3. // Input : n is an integer. 4. // Output : The v
alue of nth number in the Fibonacci series. 5. { 6. if(n == 0 || n ==1 ) //Base
criteria. 7. return n; 8. else 9. return(fnFib(n
2) + fnFib(n
1)); //Recursive c
all. 10. }//End of algorithm Example 9.4: The recursion tree to calculate the va
lue of Fib(5) using the algorithm is shown in Figure 9.3 and the order of the fu
nction calls are shown with each and every function within third braces. 5 [1] f
nFib(5)

[2] 2 fnFib(3) [3] 1 fnFib(1) 1 [4] fnFib(2)


+ [8] 1 fnFib(2) 0 [9] 1 [10] fnFib(0) + fnFib(1)
3 [7] fnFib(4) 2 [11] fnFib(3) 1 [13] fnFib(2)
+
+
return 1
[5] 0 1 [6] fnFib(0) + fnFib(1)
[12] 1 fnFib(1)
+
return 0 return 1
return 0
return 1
[14] 0 [15] 1 return 1 fnFib(0) + fnFib(1)
return 0 return 1 Figure 9.3: A recursion tree to find the n value in Fibonacci
series
th
9.3.5 Towers of Hanoi
The Towers of Hanoi problem is a famous recursive problem, which is based on 3 p
egs and a set of discs with different sizes. Suppose 3 pegs A, B and C are given
and on peg A there are finite number of n discs in increasing order i.e. bigges
t one at the bottom and smallest one at the top. The object is to move the discs
from peg A to peg C using peg B as an auxiliary peg. The rules are: a) Only one
disc can be moved at a time. b) Only the top disc on any peg can be moved to an
y other peg. c) A larger disc cant be placed on a smaller one. If there is one di
sc on peg A then move the only disc to peg C (A C). For more than one disc on pe
g A, move top n
1 discs recursively to peg B using peg C as auxiliary according
to the above stated rules. Now move remaining one disc from peg A to peg C. Then
again move n
1 discs from peg B to peg C using peg A as auxiliary. The solution
to the Towers of Hanoi problem for n = 3 appear in the figure 9.4. Move top dis
c from peg A to peg C. Move top disc from peg A to peg B. Move top disc from peg
C to peg B. Move top disc from peg A to peg C. Move top disc from peg B to peg
A. Move top disc from peg B to peg C. Move top disc from peg A to peg C. A B C A
B C

(1) A
Initial B C
(2) A
A
> C B C
(3) A
A
> B B C
(4) A
C
> B B C
(5) A
A
> C B C
(6) A
B
> A B C
(7)
B
> C
(8)
A
> C
Figure 9.4: The moves to solve Tower of Hanoi problem for 3 discs. Algorithm 9.5
1. Algorithm fnTowers_of_Hanoi(A, B, C, N) 2. //Purpose : This algorithm finds
the moves to solve the Tower of Hanoi problem for N discs. 3. //Input : N is tot
al number of discs. 4. //Output : None. 5. { 6. if(N == 1) 7. { 8. Move top disc
from A to C (A C); 9. return; 10. }

11. else 12. { 13. fnTowers_of_Hanoi(A, C, B, N


1); 14. fnTowers_of_Hanoi(A, B,
C, 1); 15. fnTowers_of_Hanoi(B, A, C, N
1); 16. } 17. } // End of algorithm Let
us find the moves for N = 3 using the above recursive algorithm:
TOH(A,B,C,3)
TOH(A,C,B,2)
TOH(A,B,C,1)
TOH(B,A,C,2)
A
> C
TOH(A,B,C ) TOH(A,C,B,1)
TOH(C,A,B,1)
TOH(B,C,A,1)
TOH(B,A,C,1) TOH(A,B,C,1)
A
> C
s are:
for N
2N
1 +

A
> B C
> B B
> A B
> C
A
> C A
> B C
> B A
> C
discs are: T(N) = 2T(N
1) +
2N
2 + ..+ 2 + 1 [Let N
i

Therefore the total moves required for 3 disc


B
> A B
> C A
> C Number of moves required
1 = 22T(N
2) + 2 + 1 = ... = = 2iT(N
i) + 2i
= 1. So T(1) = 1] = 2N 1

A
> C
9.4
Tail recursion
A recursive function is said to be tail recursive if there are no pending operat
ions to be performed on return from a recursive call. Consider the function fnFa
ct() of the algorithm 9.1. Notice that there is a pending operation, namely mult
iplication, to be performed on return from each recursive call. Whenever there i
s a pending operation, the function is called non
tail recursive. The fnFact() f
unction can be rewritten in a tail recursive way as shown in algorithm 9.6. Algo
rithm 9.6 1. Algorithm fnFact1(n, result) 2. // Purpose : This algorithm finds t
he factorial of a number in a tail
recursive way. 3. // Input : result is the ca
lculated factorial value of n 4. // Output : This function returns the value of
result. 5. {

6. if(n == 0 || n == 1) 7. return result; 8. else 9. return fnFact1(n


1, n*resul
t); 10. }// End of Algorithm Assume factorial value of 3 is to be calculated. Th
en the function fnFact1() described in Algorithm 9.6 is to be called as fnFact1(
3,1). Now the question is how does the algorithm work? First the condition of li
ne 6 executes. As n=3, so program control goes to line 9 of the else part. Now t
he function fnFact1(3,1) calls itself but with the different parameters like fnF
act1(2,3). Similarly fnFact1(2,3) calls fnFact1(1,6). Now as n=1, the function f
nFact1(1,6) returns 6 to fnFact1(2,3) and so on. Example 9.5 shows how the algor
ithm works. From the example it is clear that there is no pending operation afte
r return from any function call. Thus we can implement a factorial function in a
tail
recursive way. Example 9.5: Factorial of 3 is to be calculated. fnFact1(3,
1) call return 6
fnFact1(2,3) call return 6
fnFact1(6,1)
9.5
Disadvantages of recursion
The disadvantages of recursion are as follows: (i) It consumes more storage spac
e because the recursive calls along with automatic variables are stored on the s
tack. (ii) If proper precautions are not taken, recursion may result in non
term
inating iterations. (iii) It also slows down execution speed, as function call r
equire jumps, and saving the current state of program onto stack before jump.
9.6
Recursion Vs Iteration
Iteration It is a process of executing a statement or a set of statements repeat
edly, until some specific condition is satisfied. Iteration involves four clear
cut steps initialization, condition, execution, and updation. Any recursive prob
lem can be solved iteratively. Iterative counterpart of a problem is more Recurs
ion Recursion is the technique of defining anything in terms of itself. There mu
st be an exclusive if statement inside the recursive functions, specifying stopp
ing condition which indicates the base criteria. Not all problems have recursive
solution. Recursion is generally a worse option to go for
Serial No. 1. 2. 3. 4.

efficient in terms of memory utilization and simple problems, or problems not re


cursive in execution speed. nature.
/****C code to solve some problems using recursion****/ /****File Name: recursio
n.c****/
#include<stdio.h> #include<conio.h> int iCount_total_moves_for_toh; int fnFact (
int n) // Purpose : This function calculates the factorial of a positive number.
// Input : n is the given number. // Output : This function returns
1 for nega
tive value of n, otherwise return factorial of n. { if(n<0) return
1; if(n == 1
|| n == 0 ) // base criteria return 1; else return (n*fnFact(n
1)); // recursiv
e call }// End of function int fnGcd (int x, int y) //Purpose : This function ca
lculates the gcd value of two numbers. //Input : x and y are the two positive in
tegers and x>y. //Output : The calculated gcd value of x and y. { if (x>=y && x%
y==0) //Base criteria return y; else return(fnGcd(y, x%y)); //Recursive call }//
End of function int fnPower(int x,int n) //Purpose : This function computes xn.
//Input : x is mantissa and n is exponent. //Output : The value of xn. { if (n
== 0) //Base criteria. return 1; if (n == 1) //Base criteria. return x; if (n>1
&& n%2 == 0) return(fnPower(x,n/2) * fnPower(x,n/2)); if (n>1 && n%2 == 1) retur
n(x * fnPower(x,(n
1)/2) * fnPower(x,(n
1)/2)); }// End of function. int fnFib(i
nt n) // Purpose : This function finds the nth number in the Fibonacci series.
//Recursive call. //Recursive call.

// Input: n is an integer. // Output : The value of nth number in the Fibonacci


series. { if(n == 0 || n ==1 ) //Base criteria. return n; else return(fnFib(n
2)
+ fnFib(n
1)); //Recursive call. }//End of function void fnTowers_of_Hanoi(char
A, char B, char C, int N) //Purpose : This function finds the moves to solve th
e Tower of Hanoi problem for N discs. //Input : N is total number of discs. //Ou
tput : None. { if(N == 1) { printf("%c
>%c\n",A,C); iCount_total_moves_for_toh++
; return; } else { fnTowers_of_Hanoi(A, C, B, N
1); fnTowers_of_Hanoi(A, B, C, 1
); fnTowers_of_Hanoi(B, A, C, N
1); } } // End of function void main(void) { int
n,iChoice,x,y; clrscr(); do { printf("1. Calculate factorial recursively\n"); p
rintf("2. Calculate GCD recursively\n"); printf("3. Calculate x^n recursively\n"
); printf("4. Calculate nth term of fibonacci series recursively\n"); printf("5.
Tower of Hanoi problem\n"); printf("6. Exit\n"); printf("Enter your choice\n");
scanf("%d",&iChoice); switch(iChoice) { case 1: printf("Enter the number to cal
culate the factorial"); scanf("%d",&n); printf("The factorial of %d = %d\n",n,fn
Fact(n)); break; case 2: printf("Enter two numbers to calculate GCD value"); sca
nf("%d%d",&x,&y);

printf("The GCD value of %d and %d is %d\n",x,y,fnGcd(x,y)); break; case 3: prin


tf("Enter the value of x and n"); scanf("%d%d",&x,&y); printf("The GCD value of
%d and %d is %d\n",x,y,fnPower(x,y)); break; case 4: printf("Enter n"); scanf("%
d",&n); printf("The %d term in fibonacci series is %d\n",n,fnFib(n)); break; cas
e 5: printf("Enter the number of disks\n"); scanf("%d",&n); iCount_total_moves_f
or_toh=0; printf("The moves for %d disks are\n",n); fnTowers_of_Hanoi(A,B,C
,n); printf("Total number of moves are %d\n\n",iCount_total_moves_for_toh); bre
ak; case 6: exit(1); default: printf("Wrong Choice\n"); } }while(1); } 9.7 MCQ C
hapter 9 1. Tail recursion (a) occurs when the recursive call is the last statem
ent executed in a recursive procedure or function (b) is a path that includes a
recursive call to the routine, to solve a smaller version of the original proble
m (c) is a structure that keeps track of the activation records at run time, in
order to preserve the values of parameters, return addresses, registers, and so
on (d) refers to the point in the compile/execution cycle when variable names ar
e associated with addresses in memory. 2. Recursive case (a) is a nonrecursive e
xit from the recursive routine (b) is a path that includes a recusive call to th
e routine, to solve a similer version of the original problem (c) is a structure
that keeps track of the activation records at runtime, in order to preserve the
values of parameters, return address, registers and so on. (d) refers to the po
int in the compile / execution cycle when variable names are associated with add
resses in memory. 3. Base case (a) is a nonrecursive exit from the recursive rou
tine (b) is a path that includes a recusive call to the routine, to solve a simi
ler version of the original problem (c) is a structure that keeps track of the a
ctivation records at runtime, in order to preserve the values of parameters, ret
urn address, registers and so on.

(d) refers to the point in the compile / execution cycle when variable names are
associated with addresses in memory. 4. Binding time (a) is a nonrecursive exit
from the recursive routine (b) is a path that includes a recusive call to the r
outine, to solve a similer version of the original problem (c) is a structure th
at keeps track of the activation records at runtime, in order to preserve the va
lues of parameters, return address, registers and so on. (d) refers to the point
in the compile / execution cycle when variable names are associated with addres
ses in memory. 5. Run time stack (a) is a nonrecursive exit from the recursive r
outine (b) is a path that includes a recusive call to the routine, to solve a si
miler version of the original problem (c) is a structure that keeps track of the
activation records at runtime, in order to preserve the values of parameters, r
eturn address, registers and so on. (d) refers to the point in the compile / exe
cution cycle when variable names are associated with addresses in memory. 6. Inf
inite regress occurs when: (a) a base case is ommited (b) a base case is never r
eached (c) both (a) and (b) (d) none of these 7. Fibonacci function fib(n) = fib
(n
1) + fib(n
2) is an example of (a) Direct recursion (b) Tree recursion (c) l
inear ecursion (d) both (a) and (b) 8. Any recursive function can be converted i
nto an equivalent non recursive function (a) Always (b) never (c) sometimes (d)
if and only if the function is tail recursive 9. Recursion is equivalent to (a)
Greedy paradigm (c) both (a) and (b) 10. Advantage of recursion is (a) Coding co
mplexity is less (c) Space complexity is less (b) Divide and Conquer paradigm (d
) None of these (b) Time complexity is less (d) None of these
Solutions:
1. a 2. b 3. a 4. d 5. c 6. c 7. d 8. a 9. b 10. a
9.8 Exercise Chapter 9 1. What is Recursion? Write a C recursive algorithm to co
mpute factorial of any given number. Check your algorithm with n=5.

2. Discuss and differentiate different types of recursions. 3. Write a C Program


to determine GCD of given numbers. Show using a stack how your algorithm works.
4. Hence, Write a C Program to determine LCM of given numbers. Show using a sta
ck how your algorithm works. 5. Write a C Program to determine nth element of a
Fibonacci series. Show using a stack how your algorithm works. 6. What is iterat
ion? How does it differs from recursion? What are the disadvantages of recursion
. 7. Every recursive algorithm can be expressed as a iterative algorithm

Justi
fy the statement with a suitable example. 8. What is tail recursion? Explain wit
h a suitable example and diagram.
Chapter 10 TREE
10.1 Definition
A tree is a finite set of vertices connected by edges such that (i) There is one
specially designated vertex called root. (ii) The remaining vertices are partit
ioned into a collection of sub
trees T1, T2 Tn each of which is also a tree.

root A T2 T1 B C D T3
E
F
G
H
I
J
K
Figure 10.1: Example of a tree
10.2 Basic terminologies
Root: A node without any parent is called root node. In figure 10.1 A is the roo
t node. Node (or Vertex): Each data item in a tree is called a node. The tree in
figure10.1 has 11 nodes (A, B, C, D, E, F, G, H, I, J and K). Edge: The line dr
awn from one node to another node is called an edge. Internal node: A node with
at least one child is called an internal node. In figure 10.1 A, B, C, D and F a
re the internal nodes. External node (or Leaf node): A node without any children
is called an external node or leaf node. In figure 10.1 E, K, G, H, I and J are
the leaf nodes. Ancestor and Descendant: A node n is an ancestor of node m (and
m is descendant of n) if n is either the father of m or the father of some ance
stors of m. In figure 10.1 node B is an ancestor of the nodes E, F and K. Degree
of a node: The number of sub trees of a node is called its degree. In figure 10
.1 degree of node A is 3, degree of node B is 2, degree of node E is 0, degree o
f node F is 1, and degree of node K is 0 and so on. Degree of a tree: It is the
maximum degree of nodes in a given tree. In figure 10.1 node A has degree 3 and
another node D is also having its degree 3. In all, this value is the maximum. S
o the degree of the above tree is 3. Siblings: The nodes who share the same pare
nt are called siblings. In figure 10.1 H, I and J are siblings. Level: Number of
ancestors of a node is called its level. Each node in a tree is assigned a leve
l number as follows: 1) The root of tree is at level 0. 2) Level of other node =
level of its parent + 1. In figure 10.1 node A is at level 0, nodes B, C and D
are at level 1, nodes E, F, G, H, I and J are at level 2 and node K is at level
3. Depth (or height): The depth of a tree T can be defined as follows: depth of
T = maximum level number of T + 1 In figure 10.1 depth of the tree is 4.

Path and Path length: It is a sequence of consecutive edges from the source node
to the destination node. The number of edges in a path is path length. In figur
e 10.1, the path between A and H is A D H and the path length is 2. Branch: Path
ending in a leaf node is called as branch. In figure 10.1 A B F K is a branch.
Internal path length: Internal path length of a tree can be defined as the sum o
f the levels of all the internal nodes in the tree. In figure 10.1 the internal
path length of the tree is 0+1+2+1+1 = 5. External path length: External path le
ngth of a tree is the sum of the levels of all the external nodes in the tree. T
he external path length of the tree in figure 10.1 is 2+3+2+2+2+2 = 13. Forest:
A set of disjoint trees is called a forest. The following figure is a forest wit
h three trees. Figure 10.2(d) shows an example of a forest.
10.3 Binary tree
A binary tree is a finite set of elements that is either empty or is partitioned
into three disjoint subsets. 1) The first subset contains a single element call
ed the root of the tree. 2) The other two subsets are themselves binary trees, c
alled the left and right sub trees of the original tree. 3) Here each and every
node can have at most two children.
(a)
(b)
(c)
(d)
(d) Figure 10.2: Example of some binary trees and forest
10.4 Types of binary trees
Complete binary tree: A binary tree is said to be complete if all its levels exc
ept possibly the last, have the maximum number of possible nodes, and if all the
nodes at the last level appear as far left as possible.
A
B
C
D
E
F

Figure 10.3: Complete binary tree Full binary tree: A binary tree is called a fu
ll binary tree if it satisfies the following two conditions: 1) Each node has ei
ther zero or two children. 2) All the leaf nodes are in the same level (and obvi
ously this is the last level).
A
B
C
D
E
F
G
Figure 10.4: Full binary tree Extended binary tree (or 2
tree): This is a binary
tree where each node has either two or zero children. The node with zero childr
en is called external node and the node with two children is called internal nod
e. External nodes are represented by a square and internal nodes are represented
by a circle. Frequently an algorithm can be represented by a 2
tree where inter
nal nodes represent tests and external nodes represent actions.
6
1
5 0
2
3
Figure 10.5: Extended binary tree Here, NE = NI + 1 whereNE = number of external
nodes NI = number of internal nodes
For the above 2
tree External path length = LE = 2 + 2 + 3 + 3 + 3 + 3 = 16 Inte
rnal path length = LI = 0 + 1 + 1 + 2 + 2 = 6 Observe thatLE = LI + 2NI
10.5 Properties of binary trees
The followings are the properties of a binary tree: 1. A binary tree with n node
s has exactly n
1 edges. Proof: This property can be proved by induction. Basis:
Let n=1. That is there is only one node in the tree. So number of edge is 0. He
nce the property is true for one node. Induction hypothesis: n = k: Assume the p
roperty is true for n = k i.e. for k nodes there is k
1 edges.

n = k+1: Now addition of one node includes one extra edge into edge set. So, now
total number of edges are = (k
1) + 1 = k. Hence proved. 2. The maximum number
of nodes on level i is 2i. Proof: By induction: Basis: Let i = 0. At level 0 the
re is only one node (root node). Hence the property is true for i = 0. Induction
hypothesis: i = k: Assume the property is true for kth level. So at level k the
re is 2k nodes. i = k + 1: In a binary tree maximum number of children for each
node is 2. Now at level k there is 2k nodes. Thus at level k+1 the maximum numbe
r of nodes can be 2*2k = 2k+1. Hence proved. 3. The number of nodes in a full bi
nary tree with height h is 2h 1 (or the maximum number of nodes in a binary tree
with height h is 2h 1). Proof: Total number of nodes in a full binary tree with
height h is h
1 i 0 N = 2 = 2 + 21 + .. + 2h
1 = 2h
1 i=0 4. If n is the total nu
mber of nodes in a complete binary tree of height h, then h = log2 n + 1. Proof:
From the definition of a complete binary tree of height h, it is full up to hei
ght h-1 and in the last level it may have some shortage of nodes. Hence e can 
rite 2h-1 < n 2h 1 [As maximum number of nodes at height h-1 is 2h-1-1 and at he
ight h is 2h-1] h-1 h 2 <n<2 h-1< log2 n < h So the value of log2 n lies beteen
h and h-1. So if e take the floor value of log2 n then it ill be h-1. Hence h
= log2 n + 1. 5. If n0 be the total number of leaf nodes and n2 be the total nu
mber of nodes having to children in a binary tree, then prove that n2 = n0 - 1.
Proof: Assume n1 is the total number of nodes ith one child. No the total num
ber of nodes N = n0 + n1 + n2 And total number of edges E = n0 * 0 + n1 * 1 + n2
* 2 = n1 + 2n2. Again e kno E = N 1 Hence, n1 + 2n2 = (n0 + n1 + n2) -1 hich
yields n2 = n0 1.
10.6 Representation of binary tree
There are to general ays to represent a binary tree in memory. 1) Linked repre
sentation: The most common and easiest ay to represent a binary tree is using l
inked list. Each node in a binary tree has three fields. One field is used to st
ore the data value and other to fields are used to store the address of the to
children. struct Node { struct Node *ptrLeft; left info right char info; struct
Node *ptrRight;

}; typedef struct Node TreeNode;


A
B
C
D
E
G
H
F
Figure 10.6: Example of a binary tree The linked representation of the binary tr
ee in figure 10.6 is shon in figure 10.7. N represents the NULL value.
A
B
C
N
D
N
E
N
N
G
N
N
H
N
N
F
N
Figure 10.7: Linked representation of the binary tree in figure 10.6 Here e tak
e a pointer variable ptrRoot to store the address of the root node in the tree.
TreeNode *ptrRoot; The NULL value of ptrRoot indicates an empty tree. For a leaf
node both the value of ptrLeft and ptrRight is NULL. 2) Sequential representati
on: Another method to represent a binary tree in memory is by array. This method
is useful for a complete binary tree and is most efficient for a full binary tr
ee. The rules to store the data values of a binary tree in an array are: i) The

root R of tree T is stored in TREE [1]. ii) If a node N occupies TREE [k] then i
ts left child is stored in TREE [2*k] and right child is stored in TREE [2*k + 1
]. For a binary tree ith height h, 2h 1 array spaces are required to store it.
The sequential representation of the binary tree of figure 10.7 is

1
A
2
B
3
C
4
D
5
E
6
G
7
H
8
N
9
N
10
F
11
N
12
N
13
N
14
N
15
N
No the question is ho e can get the leaf nodes from the sequential representa
tion. If the height of the binary tree is h, then all the nodes at level h-1 are
obviously the leaf nodes. No in the array the range of index of the nodes at l
evel h-1 is from 2h-1 to 2h -1. So any node ithin this range in the array is a
leaf node. For the other nodes N (that are above the last level) at index K, if
TREE[2*K] and TREE[2*K + 1] both is NULL then N is leaf node.
10.7 Binary tree traversal methods
There are three standard ays of traversing a binary tree T ith root R. A) Preo
rder traversal: 1. Process the root R 2. Traverse the left sub tree of R in preo
rder 3. Traverse the right sub tree of R in preorder
A
B

C
D
E
F
G
Figure 10.8: Example of a binary tree Preorder traversal of figure10.8: ABDECFG
Algorithm 10.1 1. Algorithm fnRecursivePreorder (ptrRoot) 2. // Purpose : This a
lgorithm finds the preorder traversal of a binary tree using recursion. 3. // In
put : ptrRoot is the address of the root node of the tree. 4. //Output : None. 5
. { 6. if(ptrRoot != NULL) 7. { 8. print(ptrRoot->info); 9. fnRecursivePreorder
(ptrRoot->ptrLeft); 10. fnRecursivePreorder (ptrRoot->ptrRight); 11. } 12. }//En
d of algorithm Figure 10.9 shos the different steps of the recursive preorder a
lgorithm for the binary tree of Figure 10.8. B D A print(A) print(B) print(D) fn
RecurPreorder(NULL) fnRecurPreorder(NULL) print(E) print(F)
fnRecurPreorder(D) fnRecurPreorder(E)

fnRecurPreorder(B)
fnRecurPreorder(NULL) E
fnRecurPreorder(A) C print(C)
fnRecurPreorder(NULL) F
fnRecurPreorder(F)
fnRecurPreorder(C) G print(G)
fnRecurPreorder(G)
fnRecurPreorder(NULL) Figure 10.9: Tree of recursive calls for preorder of the t
ree in figure 10.8 Algorithm 10.2 1. Algorithm fnNon_Recursive_Preorder(ptrRoot)
2. // Purpose : This algorithm finds the preorder traversal of a binary tree in
a non-recursive ay. 3. // Input : ptrRoot is the address of the root node of t
he tree. 4. //Output : None. 5. { 6. TreeNode *N; 7. Initialize stack S; // init
ialize a stack s to be empty 8. fnPush(ptrRoot, S) // push root node onto the st
ack 9. hile(!empty(S)) // hile the stack is not empty 10. { 11. N = fnPop(S);
// pop a node from the stack 12. if(N != NULL) // if the node is not NULL 13. {
14. print N->info; // print the contents of the node

15. fnPush(N->ptrRight, S); 16. fnPush(N->ptrLeft, S); 17. } 18. } 19. }//End of
algorithm
// push the root of the right sub tree // push the root of the left sub tree
B) Inorder traversal: 1. Traverse the left sub tree of the root R in inorder. 2.
Process the root R. 3. Traverse the right sub tree of the root R in inorder. In
order traversal of figure 10.8 is DBEAFCG Algorithm 10.3 1. Algorithm fnRecursiv
eInorder(ptrRoot) 2. // Purpose : This algorithm finds the in-order traversal of
a binary tree using recursion. 3. // Input : ptrRoot is the address of the root
node of the tree. 4. //Output : None. 5. { 6. if(ptrRoot != NULL) 7. { 8. fnRec
ursiveInorder (ptrRoot->ptrLeft); 9. print(ptrRoot->info); 10. fnRecursiveInorde
r (ptrRoot->ptrRight); 11. } 12. }//End of algorithm Algorithm 10.4 1. Algorithm
fnNon_Recursive_Inorder(ptrRoot) 2. // Purpose : This algorithm finds the in-or
der traversal of a binary tree in a non-recursive ay. 3. // Input : ptrRoot is
the address of the root node of the tree. 4. //Output : None. 5. { 6. TreeNode *
P; 7. P = ptrRoot; //Assign the address of the root node to P. 8. Initialize sta
ck S; // initialize a stack s to be empty. 9. hile( !empty(S) || P != NULL) //
hile the stack is not empty or P is not NULL. 10. { 11. hile(P != NULL) //Whil
e P is not NULL. 12. { 13. fnPush(S, P); //Push P to stack. 14. P = P->ptrLeft;
//Traverse the left child of P. 15. } 16. if( !empty(S)) //If Stack is not empty
. 17. { 18. P= fnPop(S); // Pop from stack and assign the address to P. 19. Prin
t P->info; // Print the information field of P. 20. P = P->ptrRight; //Traverse
the right child of P. 21. } 22. }

23. }//End of algorithm C) Postorder traversal: 1. Traverse the left sub tree of
R in postorder 2. Traverse the right sub tree of R in postorder 3. Process the
root R Postorder traversal of figure 10.8 is: DEBFGCA Algorithm 10.5 1. Algorith
m fnRecursivePostorder(ptrRoot) 2. // Purpose : This algorithm finds the post-or
der traversal of a binary tree using recursion. 3. // Input : ptrRoot is the add
ress of the root node of the tree. 4. //Output : None. 5. { 6. if(ptrRoot != NUL
L) 7. { 8. fnRecursivePostorder(ptrRoot->ptrLeft); 9. fnRecursivePostorder(ptrRo
ot->ptrRight); 10. print (ptrRoot->info); 11. } 12. }//End of algorithm
Algorithm 10.6 1. Algorithm fnNon_Recursive_Postorder(ptrRoot) 2. // Purpose : T
his algorithm finds the post-order traversal of a binary tree in a non-recursive
ay. 3. // Input : ptrRoot is the address of the root node of the tree. 4. //Ou
tput : None. 5. { 6. TreeNode *P, *N; 7. P = ptrRoot; //Assign the address of ro
ot node to P. 8. hile( !empty(S)) //While stack is not empty. 9. { 10. hile(P
!= NULL) //While P is not NULL. 11. { 12. fnPush(S, P); //Push P onto stack. 13.
if(P->ptrRight != NULL); 14. fnPush(S, NULL); //Push NULL if right child of P e
xists. 15. P = P->ptrLeft; //Traverse to the left child of P. 16. } 17. N = fnPo
p(S); //Pop one node from stack assign it to N. 18. if(N != NULL) 19. print N->i
nfo; // If N is not null then print its information field. 20. else 21. { 22. N =
fnPop(S); // Pop one node from stack assign it to N. 23. P = N->ptrRight; //Ass
ign the address of the right child of N to P. 24. fnPush(S, N); //Push N onto st
ack.

25. } 26. } 27. }//End of algorithm


10.8 Creation of binary tree from preorder and inorder traversal
Consider the folloing preorder and inorder traversals of a binary tree. Preorde
r :ABDGHEICFJK Inorder :GDHBEIACJFK No the different steps to create the binary
tree are as follos: STEP 1: In preorder traversal, first e print the data and
then move to left child and right child respectively. Therefore the first node
in preorder traversal is obviously the root node and then the left sub tree and
right sub tree of the root can be obtained from the inorder traversal. Preorder
:ABDGHEICFJK Inorder :GDHBEIACJFK
A GDHBEI CJFK
STEP 2: Among the nodes of the left sub tree of A, node B comes first in the pre
order traversal. So B is the immediate left child of A. Similarly C is the immed
iate right child of A. Preorder :ABDGHEICFJK Inorder :GDHBEIACJFK
A
B
C
GDH
EI
JFK
STEP 3: Preorder Inorder
:ABDGHEICFJK :GDHBEIACJFK
A
B G D H E I
C J F K

10.9 Creation of binary tree from postorder and inorder traversal


Consider the folloing post-order and in-order traversals of a binary tree. Post
order :HDIEBJFKLGCA Inorder :HDBIEAFJCKGL The steps to build the binary tree fro
m to traversals are as follos: STEP 1: In post-order traversal, first e move
to left child and right child respectively and then print the data. Therefore th
e last node in post-order traversal is obviously the root node and then the left
sub tree and right sub tree of the root can be obtained from the in-order trave
rsal. Postorder :HDIEBJFKLGCA Inorder :HDBIEAFJCKGL
A
HDBIE
FJCKGL
STEP 2: No among the nodes of the left sub tree of root A, node B is traversed
last in post-order traversal. Therefore node B is immediate left child of A. Sim
ilarly e get node C as the immediate right child of A. Postorder :HDIEBJFKLGCA
Inorder :HDBIEAFJCKGL
A
B
C

DH
IE
IE
KGL
STEP 3: Postorder Inorder
:HDIEBJFKLGCA :HDBIEAFJCKGL
A
B
C
D
E
F
G
H
I
L
K
L
10.10
Expression tree
Expressions tree generally a 2-tree in hich external nodes contain operands and
internal nodes contain operators. But due to presence of unary operators into e
xpressions it may not be a 2-tree. An expression tree does not contain parenthes
is, the reason for this is that for evaluating an expression using expression tr
ee, structure of tree itself decides the order of operations. An expression tree
may not unique for an expression. But the result they produce must be correct.
The preorder and post-order traversal of an expression tree gives the prefix and
postfix notation of the arithmetic expression respectively. Example 1: Create e
xpression tree for the arithmetic expression A+B-C.
+
+
C
A
A

B
B
C
To expression trees for A+B-C Example 2: Create an expression tree for A + B *
C D + logE / F. Step 1:
+
A
B*CD+logE/F

Step 2:
+
A
B*C
D+logE/F
Step 3:
+
A
*
+
B
C
D
logE/F
Step 4:
+
A
*
+
B
C
D
/
logE Step 5:
+
F
A
*

+
B
C
D
/
F

lo g
E
10.11
Binary search tree
A binary search tree is a binary tree in hich each node has value greater than
every node of its left sub tree and less than every node of its right sub tree.
This type of tree does not contain duplicate value. The inorder traversal of a b
inary search tree gives a list in ascending order. An example of a binary search
tree is shon in figure 10.10.
E
B
G
A
C
F
H
D
I
J
Figure 10.10: An example of a binary search tree Insertion into binary search tr
ee: Consider the folloing items: ITEMS: M F P B I Q We have to create a binary
search tree using the items. Solutions: Step 1: The first item in the list is M.
As the tree is empty, insert M as the root node. insert M Step 2: The second it
em F is less than the root M. SoM insert F as the left child of M. insert F
M
F
Step 3: Next item P is greater than M, so insert P as the right child of M.

insert P
M
F
P
Step 4: Next item in the list is B. B is less than the root M. So next compariso
n takes place ith F (the left child of M). No B is less than F and left child
of F is NULL. So insert B as the left child of F. insert B
M
F
P
B
Step 5: Next item I is less than the root M and greater than F (the left child o
f M). As the right child of F is NULL, insert I as the right child of F. insert
I
M
F
P
B
I
Step 6: The last item Q is greater than the root M and its child P. So insert Q
as the right child of P. insert Q
M
F
P
B
I
Q
Algorithm for insertion into binary search tree: Algorithm 10.7 1. Algorithm fnI
nsert_BST(cData) 2. //Purpose : This algorithm inserts a ne node into a binary
search tree. 3. //Input : The item cData. 4. //Output : This algorithm returns 0
for a duplicate node and returns 1 for a successful insertion. 5. //Comments: R
oot of the tree is ptrRoot hich is a global variable. 6. {

7. TreeNode *ptrNeNode, *ptrParent, *ptrChild; 8. ptrNeNode=(TreeNode *)malloc


(sizeof(TreeNode)); 9. ptrNeNode->ptrLeft=ptrNeNode->ptrRight=NULL; 10. ptrNe
Node->info=cData; 11. if(ptrRoot == NULL) 12. ptrRoot = ptrNeNode; 13. else 14.
{ 15. ptrChild = ptrRoot; 16. hile(ptrChild != NULL) 17. { 18. ptrParent = ptr
Child; 19. if(ptrChild->info > cData) ptrChild = ptrChild->ptrLeft; 20. else if(
ptrChild->info < cData) ptrChild = ptrChild->ptrRight; 21. else return 0; 22. }
23. if(ptrParent->info > cData) ptrParent->ptrLeft = ptrNeNode; 24. else ptrPar
ent->ptrRight = ptrNeNode; 25. } 26. return 1; 27. }//End of Algorithm Recursiv
e algorithm for insertion into binary search tree: Algorithm 10.8 1. Algorithm T
reeNode *fnInsert_BST( ptrRoot, iData) 2. //Purpose : This algorithm inserts a n
e node into a binary search tree in recursive ay. 3. //Input : Root of the tre
e is ptrRoot and the item to be inserted is iData. 4. //Output : This algorithm
returns address of a node. 5. { 6. if (ptrRoot == NULL) // position found. 7. {
8. ptrRoot = (TreeNode *) malloc(sizeof(TreeNode)); //Create ne node. 9. ptrRoo
t ->ptrLeft = NULL; // Set its left child to NULL. 10. ptrRoot ->ptrRight = NULL
; // Set its right child to NULL. 11. ptrRoot ->info = iData; //Insert the data
value into the ne node. 12. } 13. elseif ( iData < ptrRoot->info) // traverse t
o the left of p 14. ptrRoot->ptrLeft = fnInsert_BST(ptrRoot->ptrLeft, iData); 15
. elseif( iData > ptrRoot->info) // traverse to the right of p 16. ptrRoot->ptrR
ight = fnInsert_BST(ptrRoot->ptrRight, iData); 17. else 18. print (Duplicate nod
e); 19. return(ptrRoot); 20. }//End of algorithm Deletion from binary search tre
e: Rules: 1. If the node has no child then simply remove it.
M

F
P
B
Q
Node I is deleted 2. If the node has one child then moves up the only child.
M
F
Q
B
I
Node P is deleted 3. If the node has to children then replace its position by i
ts inorder successor (or predecessor).
M P
F
P
F
Q
B
I
Q
B
I
Inorder : B F I M P Q M is to be deleted. As M has to children replace node M b
y its inorder successor P Node M is deleted Algorithm to delete a node from a BS
T: Algorithm 10.9 1. Algorithm fnDelete_BST(ptrDeleteNode) 2. //Purpose : This a
lgorithm deletes a node from a binary search tree. 3. //Input : The node ith th
e address ptrDeleteNode is to be deleted. 4. //Output : None. 5. { 6. if(ptrDele
teNode->ptrLeft == NULL && ptrDeleteNode->ptrRight == NULL)

7. { 8. free(ptrDeleteNode); 9. return; 10. } 11. else if(ptrDeleteNode->ptrLeft


!= NULL && ptrDeleteNode->ptrRight != NULL) 12. { 13. ptrSuccessor = Get_Inorde
r_Successor(ptrDeleteNode); 14. ptrSuccessor->ptrLeft = ptrDeleteNode->ptrLeft;
15. ptrSuccessor->ptrRight = ptrDeleteNode->ptrRight; 16. free(ptrDeletenode); 1
7. return; 18. } 19. else if(ptrDeleteNode->ptrLeft == NULL && ptrDeleteNode->pt
rRight !=NULL) 20. { 21. ptrParent = Get_Parent(ptrDeleteNode); 22. if(ptrParent
->ptrLeft == ptrDeleteNode) 23. ptrParent->ptrLeft = ptrDeleteNode->ptrRight; 24
. else 25. ptrParent->ptrRight = ptrDeleteNode->ptrRight; 26. free(ptrDeleteNode
); 27. return; 28. } 29. else 30. { 31. ptrParent = Get_Parent(ptrDeleteNode); 3
2. if(ptrParent->ptrLeft == ptrDeleteNode) 33. ptrParent->ptrLeft = ptrDeleteNod
e->ptrLeft; 34. else 35. ptrParent->ptrRight = ptrDeleteNode->ptrLeft; 36. free(
ptrDeleteNode); 37. return; 38. } 39. }//End of algorithm
10.12
Heap
A heap is a complete binary tree and is implemented in array as sequential repre
sentation rather than linked representation. A heap is called max heap or descen
ding heap if every node of heap has a value greater than or equal to the value o
f every child of that node. Similarly a heap is called min heap or ascending hea
p if every node of heap has a value less than or equal to the value of every chi
ld of that node. Insertion into max heap: M Step 1: insert node M
M
F
P
B
I
Q
Step 2: insert node F

M
M
F
F
Step 3: insert node P
M
Reheap
P F
P
F
M
Step 4: insert node B
P P
F
M
F
M
B
B
Step 5: insert node I
P P
Reheap
F M I M
B
I
B
F
Step 6: insert node Q
P
Q
Reheap
I M I P

B
F
Q
B
F
M
Deletion from heap: 1. Assign the node to some variable ITEM 2. Replace ITEM by
the last node L of the tree 3. Reheap
Q
I
P
Q 1
I 2
P 3
B 4
F 5
M 6
B
F
M
Suppose ITEM = Q. Then replacing node Q by the last node (L=) M e get
M
P
Reheap
I P I M
B
F
B
F
10.13
Weight balanced binary tree

Huffman tree: Consider the extended binary tree shon in the figure 10.10.

Figure 10.10 Suppose every external node has some eight W, then the eighted pa
th length for the external node ill be here W denotes the eight and P denotes
the path length of an external node. Let us take the eights 4, 7, 8, 12 and cr
eate three different 2-trees. P = W1P1 + W2P2 + .. + WnPn
4
4
7
8
12
8
7
12
Figure 10.11
Figure 10.12
12
8

4
7
Figure 10.13 Pa = 4 X 2 + 7 X 2 + 8 X 2 + 12 X 2 = 62 Pb = 4 X 1 + 7 X 3 + 12 X
3 + 8 X 2 = 77 Pc = 12 X 1 + 4 X 3 + 7 X 3 + 8 X 2 = 61 No e can see that thre
e different trees have different path lengths. So problem arises for obtaining a
unique tree hich has minimum eighted path length. This extended binary tree c
an be obtained by Huffman algorithm Huffman algorithm: 1. Let us take there are
n eights W1, W2, . , Wn. 2. Take to minimum eights and create a sub tree. Suppos
e W1 and W2 are first to minimum eights then sub tree ill beW1
W2
3. No the remaining eights ill be W1 + W2, W3, W4, . , Wn. 4. Create all sub trees
at the last eight. Example: W1 16 STEP 1: W2 11 W3 7 W4 20 W5 25 W6 5 W7 16
5
7
STEP 2:
W1 16
W2 11
W3+W6 12 20
W4 25
W5 16
W7

11
5
7
STEP 3:
W1 16
W2 + W3+W6 23
W4 20
W5 25
W7 16
16
16
11
5
7
STEP 4:
W1 + W7 32
W2 + W3+W6 23
W4 20
W5 25
16
16
20
11
5
7
Step 5:
W1 + W7 32
W2 + W3+W6 + W4 43
W5 25

25
20
16
16
11
5
7
Step 6:
W1 + W7 + W5 57
W2 + W3+W6 + W4 43
25
20
16
16
11
5
7
10.14
AVL Search tree / Height balanced binary tree
An AVL tree is a binary search tree here the balance factor of any node can hav
e only three values -1, 0 or 1. The name AVL comes from the Russian mathematics
ho developed this tree in 1962 : G. M. Adelson Velskii and E. M. Landis. Balance
factor = height of left sub tree (hL) height of right sub tree (hR)
0 M 0 F 0 B 0 I -1 P 0 Q 0 B 1 F 0 M -1 P 0 Q

Figure 10.14: Examples of AVL tree Insertion into AVL tree: First insert an item
into AVL tree according to the rules of insertion into binary search tree. Then
check hether the tree is balanced or not. If it is unbalanced, then find the n
earest ancestor node (P) to the inserted node ith balance factor +2 or -2 on th
e path from inserted node to root node. P is called the pivot node. Then perform
one of the folloing four rotations on the unbalanced tree to make it balanced
depending on some criteria. 1. Left to left rotation: When the pivot node is lef
t heavy and the ne node is inserted in left sub tree of the left child of pivot
node then the rotation performed is left to left rotation.
+1 P 0 1 Insert into AL +2 P 0 A 0
A
P R
A
h A L A R
P R
LL rotation
h
A L
P
h+1 A R P R
h
A L
A R
h
h+1
h
h
h
Balanced Unbalanced Balanced 2. Right to Right rotation: When the pivot node is
right heavy and the ne node is inserted in right sub tree of the right child of
pivot node then the rotation performed is right to right rotation. -1 -2 0
A P P
0 P L A L h
A
-1 Insert into AR A R h P L
A
0
P

RR rotation A R P L A L
A R
h
h
A L h
h+1
h
h
h+1
Balanced Unbalanced Balanced 3. Left to Right rotation: When the pivot node is l
eft heavy and the ne node is inserted in right sub tree of the left child of pi
vot node then the rotation performed is left to right rotation. Here e insert a
ne node into BL (left sub tree of node B). But the ne node can also be insert
ed into BR (i.e. the right sub tree of the node B). Actually left to right rotat
ion is a kind of double rotation. First rotate the unbalanced tree right to righ
t taking node A as pivot node and then perform left to left rotation on the resu
ltant tree taking node P as pivot node.

0
P
+2
P
+0
B
0
A
-1 0
B
0 LR rotation
A
-1
A P
P h R
Insert into BL h P +1 R
B
A h L B h-1 L
h A L B R h-1 h B L
A h L B R h
B h L
B R h-1
P h R
h-1
Balanced
Unbalanced
Balanced
4. Right to Left rotation: When the pivot node is right heavy and the ne node i
s inserted in left sub tree of the right child of pivot node then the rotation p
erformed is right to left rotation. Here e insert a ne node into BL (left sub
tree of node B). Insertion can also take place into BR. Right to left rotation i
s also a double rotation. Here first e perform a left to left rotation taking t
he node A as pivot node and then a right to right rotation taking the node P as
pivot node. The final balanced tree is shon in figure. -1
P
-2 0
P
0 h P L
B A

1 Insert into BL h A R h B L h P L
B A
B
RL rotation
P
0
-1
A
0 B R
1 B R
A R h h-1 h
h h-1
B L
P L
h
B L
B R h-1
A R
h-1 Balanced
Unbalanced
Balanced
Example: Construct an AVL search tree ith the folloing elements in the order o
f their occurrence: G, B, A, K, M, C

Insert G, A:
G
A
Insert B:
G
LL Rotation
B A A
B G
Insert K, M:
A
B
B
RR Rotation
G K M G B A C K M A K M
G
Insert C:
B A G C K M
RL Rotation
Deletion from AVL tree: If deletion of a node from an AVL search tree makes the
tree unbalanced, then first find the pivot node in the tree. No perform the fol
loing rotations on the unbalanced tree to make it balance. 1. R0 rotation: If d
eletion takes place from the right sub tree of P and the balance factor of the l
eft child (A) of P is 0, then perform R0 rotation. +1 +2 -1
P
Delete from PR
R0 rotation
A

P
0
A
0 P R A R h h A h L
A
1 P R A R h h-1 A L h A h R
P
A h L
P R
h-1
Balanced
Unbalanced
Balanced
2. R1 rotation: If deletion takes place from the right sub tree of P and the bal
ance factor of the left child (A) of P is 1, then perform R1 rotation. +1
P
+2 Delete from PR +1 P R
P
0 R1 rotation P R A L
A
+1
A
0
A
h A h L
h-1
h h-1 A R
P
A h L
A R
h-1
A R
h-1
P R
h-1

Balanced
Unbalanced
Balanced
3. R-1 rotation: If deletion takes place from the right sub tree of P and the ba
lance factor of the left child (A) of P is -1, then perform R2 rotation. +1
P
+2
P
0
B
-1
A
-1 0 P h R Delete from PR
A
0 0 P h-1 R R-1 rotation
A P
0
A h-1 L B L h-1
B
A h-1 L B R h-1 h-1 B L
B
B R h-1
h h-1
A L
B L h-1
B R h-1
P R h-1
Balanced
Unbalanced
Balanced
4. L0 rotation: If deletion takes place from the left sub tree of P and balance
factor of the right child (A) of P is 0, then perform L0 rotation. 5. L1 rotatio
n: If deletion takes place from the left sub tree of P and the balance factor of
the right child (A) of P is 1, then perform L1 rotation.

6. L-1 rotation: If deletion takes place from the left sub tree of P and the bal
ance factor of the right child (A) of P is -1, then perform R2 rotation.
10.15
Threaded binary tree
Consider the binary tree in figure 10.6 and its linked presentation in figure .10.17.
In figure 10.17, the total number of links is 16 and the total number of NULL link
s is 9 here as the total number of nodes in the binary tree is 8. In fact if a
binary tree has n number of nodes, then total number of links in the tree 2n and
total number of NULL links is n+1. A.J. Perlis and C. Thornton jointly proposed
an idea to make effective use of these NULL pointers. The basic idea is to repl
ace the NULL pointers by some appropriate pointer values called thread. The gene
ral rule says to replace the NULL left pointer of a node ith the address of the
immediate predecessor of this node and replace the NULL right pointer of a node
by the address of the immediate successor of this node. The threaded binary tre
e corresponding to the tree of figure 10.6 is shon in the figure 10.15. In the
threaded binary tree still the left pointer of node D and right pointer of node
H is NULL. To eliminate these to NULL values e take a header node. Left pointe
r of node D and right pointer of node H both contain the address of the header n
ode. No the question comes ho e can differentiate beteen a thread pointer an
d normal pointer from memory representation of the tree. For this purpose e can
include to more fields ith each node to decide hether this is a thread point
er or normal pointer. Then the structure definition for a node is: struct Node {
struct Node *ptrLeft; int lThread; left lThread info rThread right char info; s
truct Node *ptrRight; int rThread; }; typedef struct Node ThreadedTreeNode; The
value 0 of lThread or rThread indicates that it is a normal pointer, otherise a
thread pointer. For any node p in a threaded binary tree: lThread(p) = 0 indica
tes left child of p is a normal pointer. lThread(p) = 1 indicates left child of
p is a thread pointer. rThread(p) = 0 indicates right child of p is a normal poi
nter. rThread(p) = 1 indicates right child of p is a thread pointer. No the alg
orithm to find the in-order successor of a node x in the tree is: Algorithm 10.1
0 1. Algorithm fnFind_Inorder_Successor(x) 2. // Purpose : This algorithm finds
the successor node of x in in-order traversal of a threaded binary tree. 3. // I
nput : The address of the node for hich the in-order successor node is required
to find. 4. // Output : The address of the in-order successor node of x. 5. { 6
. ThreadedTreeNode *p; 7. p = x->ptrRight; 8. if(x->rThread == 0) //if q has rig
ht child 9. hile(p->lThread==0) 10. p = p->ptrLeft; 11. return p; 12. }//End of
algorithm No the algorithm to find the in-order predecessor of a node x in the
tree is:

Algorithm 10.11 1. Algorithm fnFind_Inorder_Predecessor(x) 2. // Purpose : This


algorithm finds the predecessor node of x in inorder traversal of a threaded bin
ary tree. 3. // Input : The address of the node for hich the inorder predecesso
r node is required to find. 4. // Output : The address of the inorder predecesso
r node of x. 5. { 6. ThreadedTreeNode *p; 7. p = x->ptrLeft; 8. if(x->lThread ==
0) //if q has left child 9. hile(p->rThread==0) 10. p = p->ptrRight; 11. retur
n p; 12. }//End of algorithm Finally the algorithm for performing in-order trave
rsal on the threaded binary tree is: Algorithm 10.12 1. Algorithm fnInorder(H) 2
. // Purpose : This algorithm finds the inorder traversal of a threaded binary t
ree. 3. // Input : H is the address of the header node of the tree. 4. // Output
: None. 5. { 6. ThreadedTreeNode *Header; 7. Header = H; // stores the address
of the header node into the variable Header. 8. hile(1) 9. { 10. H = fnFind_Ino
rder_Successor(H); 11. if(H==Header) // Traversing is finished. 12. return; 13.
else 14. print(H->info); 15. } 16. }//End of Algorithm
A
B
C
N
D
E
G
H
N
F
Figure 10.15: Threaded binary tree corresponding to figure 10.6
Header node
1
1

0
A
0
0
B
0
0
C
0
1
D
1
0
E
1
1
G
1
1
H
1
1
F
1
Figure 10.16: To ay in-order threading using lThread and rThread fields ith h
eader node
10.16
M-ay search tree
If e relax the restriction that each node can have only one key, e can reduce
the height of the tree. An M-ay search tree means a search tree ith degree M.
An M-ay search tree T may be an empty tree. If T is nonempty, then it satisfies
the folloing properties: 1. Each and every node of T has at least one key valu
e and at most M-1 key values. 2. If in a node there are n keys k0, k1kn-1, then k0

< k1 < < kn-1. 3. All keys in left sub tree of a key are less than it and all key
s in right sub tree of a key are greater than it. 4. Each of the sub trees of a
node are also M-ay search tree. The figure 10.17 shos an M-ay search tree of
order 3. The value N in the link part of every node denotes a NULL link. G M
N
A
D
N
N
J
N
L
N
N
X
N
Z
N
N
B
N
C
N Figure 10.17: An M-ay search tree ith M=3
The height of an M-ay search tree ith n keys is logM(n + 1). The maximum numbe
r of keys in an M-ay search tree of height h is Mh -1. Rules for insertion into
M-ay search tree: First find the position of the node for the ne key in the t
ree. If the node is not full then insert the key into appropriate position in th
e node. For a full node create a ne node in proper place. Example: Insert the f
olloing keys into an M-ay search tree of order 3.

W, A, X, P, M, K, J Insert W, A: Insert X: N A N W N N A N W
N Insert P, M:
X
N
N
N
A
W
N Insert K:
M
N
P
N
N
X
N
N
N
A
W
M
N
P
N
N
X
N
-

N
N Insert J:
K
N
N
N
A
W
M
N
P
N
N
X
N
N
N
J
N
K
N
Rules for deletion from an M-ay search tree: Suppose key Ki is to be deleted fr
om a node of an M-ay search tree.

..
Li-1
Ki
Li
..
Li-1 and Li are the addresses of the left child node and the right child node of
K i respectively. No the folloing four conditions may come into consideration
. 1. Li-1 and Li both are NULL. Delete Ki simply. N A J Delete key B N A J
N
B
N
E
N
N
N
N
P
N
N
E
N
N
N
N
N
P
N
Before Deletion
After Deletion
2. Li-1 is not NULL and Li is NULL. Pick the largest key value (K) from the left
child node of K i, delete key K and replace Ki ith K. N A J Delete key N N A J

N
B
N
E
N
N
N
P
N
N
B
N
E
N
M
N
P
N
N
L
N
M
N
N
L
N
N
Before Deletion
After Deletion

3. Li-1 is NULL and Li is not NULL. Pick the smallest key value (K) from the rig
ht child node of Ki, delete key K and replace Ki ith K. N A J Delete key A N B
J
N
B
N
E
N
N
N
N
P
N
N
E
N
N
N
N
N
P
N
Before Deletion
After Deletion
4. Li-1 and Li both are NULL. Choose either the largest key value from the left
child node of Ki or the smallest key value from the right child node of Ki, dele
te the key and replace Ki ith the chosen key. J Delete key J

N
A
N
A
E
N
B
N
E
N
N
N
N
P
N OR Delete key J
N
B
N
N
N
N
N
P
N
Before Deletion N A J N A
After Deletion N
N
B
N

E
N
N
N
N
P
N
N
B
N
E
N
N
P
N
N
Before Deletion
After Deletion
10.17
B-Tree/Balanced M-ay search tree
M-ay search tree minimizes the time of file access due to its reduced height. B
ut it is required to keep the height of the tree as lo as possible and for this
purpose e need to balance the height of the tree. This balanced M-ay search t
ree is called B-Tree. Definition: A B-tree of order M is an M-ay search tree in
hich 1. Root node has at least 1 key value and at most M-1 key values. 2. The
other nodes except the root contain at least M/2 -1 key values and M-1 key values.
3. All leaf nodes are on the same level. 4. Keys are arranged in a defined orde
r ithin the node. Rules for insertion a ne key into a B-tree: 1. First search
the tree to check the existence of ne key value in the tree. If no duplicate ke
y is found, then get the leaf node N here the ne key is to be inserted. 2. If
N is not full (a node is called full hen it contains at most keys), then insert
the ne key in N and exit. 3. If N is full, then split the node into to ne no
des at its median value and move the median key value to its parent node. Repeat
step 3 until the tree is balanced. Rules for deletion a key from a B-tree: In B
-tree deletion is done from the leaf node only. If e need to delete a key from
an internal node then replace the node ith its immediate successor (or predeces
sor) until a key from any leaf node is promoted to its upper level. Then balance
the tree according to the given rules: 1. If the leaf node has enough key, then

simply remove it. J N N N


N
A
N
C
N
F
N
I
N
N Delete I
L
N
O
N
R
N
V
N
J
N
N
N
N
A
N
C

N
F
N
N
N
L
N
O
N
R
N
V
N
2. If the leaf node contains less than minimum number of keys, then check its im
mediate left sibling node and immediate right sibling node.

i) If the left sibling node has more than the minimum number of key, then move t
he largest key value of this node to its parent and move don the intervening en
try from the parent node to its right child node. J N N N
N
A
N
C
N
F
N
I
N
N
L
N
O
N
N
N
Delete O
I
N
N
N
N
A

N
C
N
F
N
N
N
J
N
L
N
N
N
ii) If the right sibling node has more than the minimum number of key, then move
the smallest key value of this node to its parent and move don the intervening
entry from the parent node to its left child node. J N N N
N
A
N
C
N
N
N
N
L
N

O
N
R
N
V
N
Delete A
L
N
N
N
N
C
N
J
N
N
N
N
O
N
R
N
V
N

N
iii) If both the sibling nodes have minimum number of keys, then create a ne no
de merging the to leaf nodes and the intervening key value of their parent node
. J P N N

N
A
N
C
N
N
N
N
Q
N
S
N
N
N
N
L
N
M
N
N
N
Delete J
P
-

N
N
N
N
A
N
C
N
L
N
M
N
N
Q
N
S
N
V
N
N
Example: Insert the folloing elements in a B-tree of order 3. W, A, X, P, M, Z,
K, J, T, L Insert W, A: N A N W N Insert X, P, M, Z: N A W
N
M
N
P
N
N

X
N
Z
N
Insert K:
M
N
N
A
N
W
N
K Insert J, T:
N
N
N M
P
N N
N
N
X
N
Z
N

N
A
N
W
N
J
N
K
N
N
P
N
T
N
N
X
N
Z
N
10.18
Red/Black tree:
A Red-Black tree is a colored binary search tree hich has the folloing propert
ies: 1. Every node is RED or BLACK. 2. Every leaf is a NULL node and colored BLA
CK. 3. If a node is RED, then both children are BLACK. 4. Every path from a node
to a leaf contains the same number of BLACK nodes. Black Nodes Red Nodes
H D C E J K M
N
N
N
N

N
N
N
N
Figure 10.18: An example of a Red-Black tree /* Program to implement a Binary Se
arch Tree */ /* File Name: BST.C */ #include<stdio.h> #include<conio.h> #include
<alloc.h> struct Node { struct Node *ptrLeft; int iData; struct Node *ptrRight;
}; typedef struct Node TreeNode;

//Prototype Declaration void fnRecursivePreorder (TreeNode *); void fnRecursiveI


norder(TreeNode *); void fnRecursivePostorder(TreeNode *); TreeNode *fnInsert_BS
T( TreeNode *, int); void fnRecursivePreorder (TreeNode *ptrRoot) // Purpose : T
his function finds the preorder traversal of a binary tree using recursion. // I
nput: ptrRoot is the address of the root node of the tree. //Output : None. { if
(ptrRoot != NULL) { printf("%d\t",ptrRoot->iData); fnRecursivePreorder (ptrRoot>ptrLeft); fnRecursivePreorder (ptrRoot->ptrRight); } }//End of function void fn
RecursiveInorder(TreeNode *ptrRoot) // Purpose : This function finds the in-orde
r traversal of a binary tree using recursion. // Input: ptrRoot is the address o
f the root node of the tree. //Output : None. { if(ptrRoot != NULL) { fnRecursiv
eInorder (ptrRoot->ptrLeft); printf("%d\t",ptrRoot->iData); fnRecursiveInorder (
ptrRoot->ptrRight); } }//End of function void fnRecursivePostorder(TreeNode *ptr
Root) // Purpose : This function finds the post-order traversal of a binary tree
using recursion. // Input: ptrRoot is the address of the root node of the tree.
//Output : None. { if(ptrRoot != NULL) { fnRecursivePostorder(ptrRoot->ptrLeft)
; fnRecursivePostorder(ptrRoot->ptrRight); printf("%d\t",ptrRoot->iData); } }//E
nd of function TreeNode *fnInsert_BST( TreeNode *ptrRoot, int iData) //Purpose :
This function inserts a ne node into a binary search tree in recursive ay. //
Input : Root of the tree is ptrRoot and the item to be inserted is iData. //Outp
ut : This function returns address of a node. { if (ptrRoot == NULL) // position
found. {

ptrRoot = (TreeNode *) malloc(sizeof(TreeNode)); //Create ne node. ptrRoot ->pt


rLeft = NULL; // Set its left child to NULL. ptrRoot ->ptrRight = NULL; // Set i
ts right child to NULL. ptrRoot ->iData = iData; //Insert the data value into th
e ne node. } else if ( iData < ptrRoot->iData) // traverse to the left of p ptr
Root->ptrLeft = fnInsert_BST(ptrRoot->ptrLeft, iData); else if( iData > ptrRoot>iData) // traverse to the right of p ptrRoot->ptrRight = fnInsert_BST(ptrRoot->
ptrRight, iData); else printf("\nDuplicate node"); return(ptrRoot); }//End of fu
nction void main(void) { TreeNode *ptrRoot; int iChoice; int iData; clrscr(); pt
rRoot = NULL; hile(1) { printf("\n1. Insert a node"); printf("\n2. Delete a nod
e"); printf("\n3. Inorder Traversal"); printf("\n4. Postorder Traversal"); print
f("\n5. Preorder Traversal"); printf("\n6. Exit"); printf("\n4. Enter your choic
e"); scanf("%d",&iChoice); sitch(iChoice) { case 1: printf("\nEnter Node value"
); scanf("%d",&iData); ptrRoot = fnInsert_BST(ptrRoot,iData); break; case 2: bre
ak; case 3: fnRecursiveInorder(ptrRoot); break; case 4: fnRecursivePostorder(ptr
Root); break; case 5: fnRecursivePreorder(ptrRoot); break; case 6: exit(1); }

} } /* Program to implement an AVL tree */ /* File Name: AVL.C */ #include <stdi


o.h> #include <conio.h> #include <alloc.h> #define FALSE 0 #define TRUE 1 struct
Node { int iData ; int iBalanceFactor ; struct Node *ptrLeft ; struct Node *ptr
Right ; }; typedef struct Node AVLNode; //Prototype Declaration AVLNode * fnBuil
d_Tree ( AVLNode *, int, int * ) ; AVLNode * fnDelete_Data ( AVLNode *, int, int
* ) ; AVLNode * del ( AVLNode *, AVLNode *, int * ) ; AVLNode * fnBalance_Right
( AVLNode *, int * ) ; AVLNode * fnBalance_Left ( AVLNode *, int * ) ; void fnD
isplay ( AVLNode * ) ; void fnDelete_Tree ( AVLNode * ) ; AVLNode * fnBuild_Tree
( AVLNode *ptrRoot, int iData, int *h ) // Purpose : This function inserts an e
lement into an AVL tree. // Input: ptrRoot is root and iData is the data value t
o be inserted. // Output : Returns address of root node. { AVLNode *node1, *node
2 ; if ( !ptrRoot ) { ptrRoot = ( AVLNode * ) malloc ( sizeof ( AVLNode ) ) ; pt
rRoot -> iData = iData ; ptrRoot -> ptrLeft = NULL ; ptrRoot -> ptrRight = NULL
; ptrRoot -> iBalanceFactor = 0 ; *h = TRUE ; return ( ptrRoot ) ; } if ( iData
< ptrRoot -> iData ) { ptrRoot -> ptrLeft = fnBuild_Tree ( ptrRoot -> ptrLeft, i
Data, h ) ; /* If ptrLeft subtree is higher */

if ( *h ) { sitch ( ptrRoot -> iBalanceFactor ) { case 1: node1 = ptrRoot -> pt


rLeft ; if ( node1 -> iBalanceFactor == 1 ) { printf ( "\nRight rotation along %
d.", ptrRoot -> iData ) ; ptrRoot -> ptrLeft = node1 -> ptrRight ; node1 -> ptrR
ight = ptrRoot ; ptrRoot -> iBalanceFactor = 0 ; ptrRoot = node1 ; } else { prin
tf ( "\nDouble rotation, Left along %d", node1 -> iData ) ; node2 = node1 -> ptr
Right ; node1 -> ptrRight = node2 -> ptrLeft ; printf ( " then Right along %d.\n
", ptrRoot -> iData ) ; node2 -> ptrLeft = node1 ; ptrRoot -> ptrLeft = node2 ->
ptrRight ; node2 -> ptrRight = ptrRoot ; if ( node2 -> iBalanceFactor == 1 ) pt
rRoot -> iBalanceFactor = -1 ; else ptrRoot -> iBalanceFactor = 0 ; if ( node2 > iBalanceFactor == -1 ) node1 -> iBalanceFactor = 1 ; else node1 -> iBalanceFac
tor = 0 ; ptrRoot = node2 ; } ptrRoot -> iBalanceFactor = 0 ; *h = FALSE ; break
; case 0: ptrRoot -> iBalanceFactor = 1 ; break ; case -1: ptrRoot -> iBalanceF
actor = 0 ; *h = FALSE ; } } } if ( iData > ptrRoot -> iData ) { ptrRoot -> ptrR
ight = fnBuild_Tree ( ptrRoot -> ptrRight, iData, h ) ;

/* If the ptrRight subtree is higher */ if ( *h ) { sitch ( ptrRoot -> iBalance


Factor ) { case 1: ptrRoot -> iBalanceFactor = 0 ; *h = FALSE ; break ; case 0:
ptrRoot -> iBalanceFactor = -1 ; break; case -1: node1 = ptrRoot -> ptrRight ; i
f ( node1 -> iBalanceFactor == -1 ) { printf ( "\nLeft rotation along %d.", ptrR
oot -> iData ) ; ptrRoot -> ptrRight = node1 -> ptrLeft ; node1 -> ptrLeft = ptr
Root ; ptrRoot -> iBalanceFactor = 0 ; ptrRoot = node1 ; } else { printf ( "\nDo
uble rotation, Right along %d", node1 -> iData ) ; node2 = node1 -> ptrLeft ; no
de1 -> ptrLeft = node2 -> ptrRight ; node2 -> ptrRight = node1 ; printf ( " then
Left along %d.\n", ptrRoot -> iData ) ; ptrRoot -> ptrRight = node2 -> ptrLeft
; node2 -> ptrLeft = ptrRoot ; if ( node2 -> iBalanceFactor == -1 ) ptrRoot -> i
BalanceFactor = 1 ; else ptrRoot -> iBalanceFactor = 0 ; if ( node2 -> iBalanceF
actor == 1 ) node1 -> iBalanceFactor = -1 ; else node1 -> iBalanceFactor = 0 ; p
trRoot = node2 ; } ptrRoot -> iBalanceFactor = 0 ; *h = FALSE ; } } } return ( p
trRoot ) ; }// End of function

AVLNode * fnDelete_Data ( AVLNode *ptrRoot, int iData, int *h ) // Purpose : Thi


s function deletes an item from the tree. // Input: ptrRoot is the adress of roo
t and iData is the data to be inserted. // Output : Returns the address of the r
oot. { AVLNode *node ; if ( !ptrRoot ) { printf ( "\nNo such Data." ) ; return (
ptrRoot ) ; } else { if ( iData < ptrRoot -> iData ) { ptrRoot -> ptrLeft = fnD
elete_Data ( ptrRoot -> ptrLeft, iData, h ) ; if ( *h ) ptrRoot = fnBalance_Righ
t ( ptrRoot, h ) ; } else { if ( iData > ptrRoot -> iData ) { ptrRoot -> ptrRigh
t = fnDelete_Data ( ptrRoot -> ptrRight, iData, h ) ; if ( *h ) ptrRoot = fnBala
nce_Left ( ptrRoot, h ) ; } else { node = ptrRoot ; if ( node -> ptrRight == NUL
L ) { ptrRoot = node -> ptrLeft ; *h = TRUE ; free ( node ) ; } else { if ( node
-> ptrLeft == NULL ) { ptrRoot = node -> ptrRight ; *h = TRUE ; free ( node ) ;
} else { node -> ptrRight = del ( node -> ptrRight, node, h ) ; if ( *h ) ptrRo
ot = fnBalance_Left ( ptrRoot, h ) ; }

} } } } return ( ptrRoot ) ; } AVLNode * del ( AVLNode *succ, AVLNode *node, int


*h ) { AVLNode *temp = succ ; if ( succ -> ptrLeft != NULL ) { succ -> ptrLeft
= del ( succ -> ptrLeft, node, h ) ; if ( *h ) succ = fnBalance_Right ( succ, h
) ; } else { temp = succ ; node -> iData = succ -> iData ; succ = succ -> ptrRig
ht ; free ( temp ) ; *h = TRUE ; } return ( succ ) ; } AVLNode * fnBalance_Right
( AVLNode *ptrRoot, int *h ) // Purpose :This function balances the tree, if ri
ght sub-tree is higher. // Input: ptrRoot is address of the root. // Output : Re
turns the address of root. { AVLNode *node1, *node2 ; sitch ( ptrRoot -> iBalan
ceFactor ) { case 1: ptrRoot -> iBalanceFactor = 0 ; break; case 0: ptrRoot -> i
BalanceFactor = -1 ; *h = FALSE ; break; case -1: node1 = ptrRoot -> ptrRight ;
if ( node1 -> iBalanceFactor <= 0 ) { printf ( "\nptrLeft rotation along %d.", p
trRoot -> iData ) ; ptrRoot -> ptrRight = node1 -> ptrLeft ;

node1 -> ptrLeft = ptrRoot ; if ( node1 -> iBalanceFactor == 0 ) { ptrRoot -> iB


alanceFactor = -1 ; node1 -> iBalanceFactor = 1 ; *h = FALSE ; } else { ptrRoot
-> iBalanceFactor = node1 -> iBalanceFactor = 0 ; } ptrRoot = node1 ; } else { p
rintf ( "\nDouble rotation, ptrRight along %d", node1 -> iData ); node2 = node1
-> ptrLeft ; node1 -> ptrLeft = node2 -> ptrRight ; node2 -> ptrRight = node1 ;
printf ( " then ptrLeft along %d.\n", ptrRoot -> iData ); ptrRoot -> ptrRight =
node2 -> ptrLeft ; node2 -> ptrLeft = ptrRoot ; if ( node2 -> iBalanceFactor ==
-1 ) ptrRoot -> iBalanceFactor = 1 ; else ptrRoot -> iBalanceFactor = 0 ; if ( n
ode2 -> iBalanceFactor == 1 ) node1 -> iBalanceFactor = -1 ; else node1 -> iBala
nceFactor = 0 ; ptrRoot = node2 ; node2 -> iBalanceFactor = 0 ; } } return ( ptr
Root ) ; }//End of function AVLNode * fnBalance_Left ( AVLNode *ptrRoot, int *h
) // Purpose : This function balances the tree, if left sub-tree is higher. // I
nput : ptrRoot is address of the root. // Output : Returns the address of root.
{ AVLNode *node1, *node2 ; sitch ( ptrRoot -> iBalanceFactor ) { case -1: ptrRo
ot -> iBalanceFactor = 0 ; break ; case 0:

ptrRoot -> iBalanceFactor = 1 ; *h = FALSE ; break ; case 1: node1 = ptrRoot ->


ptrLeft ; if ( node1 -> iBalanceFactor >= 0 ) { printf ( "\nptrRight rotation al
ong %d.", ptrRoot -> iData ) ; ptrRoot -> ptrLeft = node1 -> ptrRight ; node1 ->
ptrRight = ptrRoot ; if ( node1 -> iBalanceFactor == 0 ) { ptrRoot -> iBalanceF
actor = 1 ; node1 -> iBalanceFactor = -1 ; *h = FALSE ; } else { ptrRoot -> iBal
anceFactor = node1 -> iBalanceFactor = 0 ; } ptrRoot = node1 ; } else { printf (
"\nDouble rotation, ptrLeft along %d", node1 -> iData ) ; node2 = node1 -> ptrR
ight ; node1 -> ptrRight = node2 -> ptrLeft ; node2 -> ptrLeft = node1 ; printf
( " then ptrRight along %d.\n", ptrRoot -> iData ) ; ptrRoot -> ptrLeft = node2
-> ptrRight ; node2 -> ptrRight = ptrRoot ; if ( node2 -> iBalanceFactor == 1 )
ptrRoot -> iBalanceFactor = -1 ; else ptrRoot -> iBalanceFactor = 0 ; if ( node2
-> iBalanceFactor == -1 ) node1 -> iBalanceFactor = 1 ; else node1 -> iBalanceFa
ctor = 0 ; ptrRoot = node2 ; node2 -> iBalanceFactor = 0 ; } } return ( ptrRoot
) ; }//End of function void fnDisplay ( AVLNode *ptrRoot ) // Purpose : This fun
ction displays the nodes of the tree in in-order fashion. // Input: ptrRoot is a
ddress of the root. // Output : None.

{ if ( ptrRoot != NULL ) { fnDisplay ( ptrRoot -> ptrLeft ) ; printf ( "%d\t", p


trRoot -> iData ) ; fnDisplay ( ptrRoot -> ptrRight ) ; } }//End of function voi
d main( ) { AVLNode *ptrRoot = NULL ; int h,iChoice,iData; clrscr( ) ; hile(1)
{ printf("\n1. Enter ne node in AVL tree"); printf("\n2. Delete a node from AVL
tree"); printf("\n3. Display Tree"); printf("\n4. Exit"); printf("\nEnter your
choice"); scanf("%d",&iChoice); sitch(iChoice) { case 1: printf("\nEnter data")
; scanf("%d",&iData); ptrRoot = fnBuild_Tree ( ptrRoot, iData, &h ); break; case
2: printf("\nEnter data"); scanf("%d",&iData); ptrRoot = fnDelete_Data ( ptrRoo
t, iData, &h ); break; case 3: printf ( "\nAVL tree:\n" ); fnDisplay (ptrRoot);
break; case 4: exit(1); default: printf("\nWrong Choice"); } } }
10.19 MCQ Chapter 10

1. Consider the folloing paragraph. The traversal proceeds as far as possible t


o the left, then backs up until the first cross road, goes one step to the right
and again as far as possible to the left. Repeat this process until all nodes a
re visited. What does the above paragraph describe? (a) Breadth first traversal
(b) Critical path traversal (c) Shortest path traversal (d) Depth first traversa
l Questions No. 2 and No. 3 are based on the folloing tree structure.
2. Consider the folloing five statements. (i) It is a tree. (ii) It is a binary
tree. (iii) It is an AVL tree. (iv) It is a binary search tree. (v) It is a str
ictly binary tree. Which of the above statements is correct ith respect to the
above tree? (a) (i) only (b) (i) and (ii) only (c) (i) , (ii) and (iii) only (d)
(i), (ii) and (iv) only 3. Consider the folloing four statements. (i) Depth of
the above tree is equal to 4. (ii) Cs proper descendants are I, J, K, L only. (i
ii) Bs siblings are C, D, E only. (iv) K, L, M, N are siblings. Which of the abov
e statements is correct? (a) (i) and (ii) only (b) (iii) only (c) (ii) and (iii)
only (d) (ii) only 4. Consider the folloing expression tree representation.
(e) All
(e) (ii), (iii) and (iv) only
Which of the folloing expressions is correct in relation to the above tree? (a)
(A*B+C)^((A+B)*C) (b) (A+B*C)^((A+B)*C)
(c) (A+B*C)^( A+(B *C))

(d) (A+B^C)*((A+B)*C)
(e) (A+B*C)^( A+B*C)

5. Consider the folloing binary search tree algorithm. Public Bsnode search ( B
snode p, int el) { While (p!=null) if(el==p.key) return p; else if (el < p.key) (i
)..; else .(ii); (iii); } Identify suitable entries to fill in the blank positi
, (ii), (iii) of the above algorithm so that it ill insert el to the binary sea
rch tree. (a) (i) p = p.right (ii) p =p.left; (iii) return null; (b) (i) p = p.l
eft (ii) p =p.right; (iii) return null; (c) (i) p = p.left.next (ii) p =p.right.
next; (iii) return null; (d) (i) p = p.right.next (ii) p =p.left.next; (iii) ret
urn null; (e) (i) p = p.right (ii) p =p.left; (iii) return null; 6. A Game tree
(a) A special type of Binary tree (b) A special type of m-ary tree (c) A special
type of binary search tree (d) None of these 7. Consider the folloing statemen
t (Algorithm Segment). The method one uses to replace the node being deleted by t
he rightmost node in its left sub tree or leftmost node in its right sub tree. Wh
at does the above statement (algorithm segment) intend to do? (a) Deleting a nod
e from an AVL, if deleting node has both a left and a right child (b) Deleting a
node from a binary tree (c) Deleting a node from a binary search tree, if delet
ing node has both a left and a right child (d) Deleting a node from a binary sea
rch tree, if deleting node is a leaf node 8. Consider the folloing table.
Which of the above ould be correct for inserting a ne node into an AVL tree? (
a) (i) only (b) (i) and (ii) only (c) (i), (ii) and (iii) only (d) (i) (ii) (iii
) and (iv) only. (e) (i) (iii) and (iv) only 9. If a binary tree is threaded for
an inorder traversal order, a NULL left link of any node is replaced by the add
ress of its (a) successor (b) predecessor (c) root (d) None of these

10. Which of the folloing process is faster for threaded trees compared ith th
eir unthreaded counterparts ? (a) Insertion (b) Deletion (c) Traversal (d) None
of these 11. Which of the folloing statement is TRUE in vie of a threaded bina
ry tree ? It can have (a) NULL links but no structural link. (b) only structural
links but no NULL links (c) structural links and NULL links (d) None of these 1
2. Which of the folloing steps is performed first for inorder traversal of a bi
nary tree ? (a) Traversal of the left subtree in postorder (b) Processing of "th
e root node. (c) Traversal of the left sub tree in inorder. (d) None of these 13
. The preorder traversal of a binary tree begins ith (a) processing of the root
node (b) traversal of the right subtree in preorder (c) None of the above. 14.
If a binary tree is threaded for an inorder traversal order, a NULL right link o
f any node is replaced by the address of its (a) successor (b) predecessor (c) r
oot (d) None of these 15. The postorder traversal of a binary tree begins ith (
a) the post order traversal of the left subtree (b) processing of the root node
II (c) the post order traversal of the right subtree (d) None of these 16. The i
norder traversal of some binary tree produced the sequence DBEAFC, and the posto
rder traversal of the same tree produced the sequence DEBFCA. Which of the follo
ing is a correct preorder traversal sequence. ? (a) DBAECF (b) ABEDFC (c) ABDEC
F (d) None of these 17. The inorder traversal of some binary tree produced the s
equence DBEAFC, and the postorder traversal of the same tree produced the sequen
ce DEBFCA. What ill be the total number of nodes in the left subtree of the giv
en tree ? (a) 1 (c) 5 (b) 4 (d) None of these 18. The inorder traversal of some
binary tree produced the sequence CBDAFE, and the postorder traversal of the sam
e tree produced the sequence CDBFEA. What ill be the total numrer of nodes in t
he right subtree of the given tree ? (a) 2 (b) 3 (c) 4 (d) None of these 19. The
inorder traversal of some binary tree produced the sequence CBDAFE, and the pos
torder traversal of the same tree produced the sequence CDBFEA. What ill be the
total numrer of nodes in the left subtree

of the given tree ? (a) 2 (c) 5


(b) 3 (d) None of these
20. The inorder traversal of some binary tree produced the sequence CBDA, and th
e postorder traversal of the same tree produced the sequence CDBA. Which of the
folloing statement is TRUE for the given tree ? Its : (a) left subtree is. empt
y, and the total number of nodes in its right subtree is 3. (b) right subtree is
empty, and the total number of nodes in its left subtree is 3. (c) both left su
btree and right subtree must be nonempty (d) None of the above 21. Which of the
folloing statements is TRUE in vie of the threaded binary trees ? (a) Insertio
n into a threaded tree is time-consuming but deletion from it is not (b) both in
sertions into and deletions from a threaded tree are more time-consuming. (c) de
letion from a threaded tree is time-consuming but the insertion into it is not.
(d) None of these 22. Searching of a node in lexical ordered binary tree is fast
, because the number of comparisons needed to determine if an item exists in the
tree ill be : (a) 1 alays (b) 2 alays (c) 0 alays (d) None of these 23. Whi
ch of the folloing statements is TRUE in vie of the lexical ordered binary tre
e ? (a) Its left subtree contains nodes hose keys are lexically greater than th
e key associated ith the root node. (b) Its left subtree contains nodes hose k
eys are lexically less than the key associated ith the root node. (c) Its root
node contains a key hich is lexically greater than most of the keys associated
ith the nodes of the right subtree. (d) None of these 24. If for the given dire
cted tree outdegree of every node is exactly equal to 2 or 0, and the number of
nodes at I is 2 raised to the poer of I-1, the tree is called: (a) binary tree
(b) complete binary tree (c) m-ary tree (d) None of these 25. While performing i
norder threading of a binary tree, if the left link represents a structural link
, then it is: (a) replaced ith a NULL link (b) left unchanged (c) replaced ith
a ne thread link. (d) None of these 26. While performing inorder threading of
a binary tree, if the right link represents a NULL link, then it is: (a) replace
d ith a structural link (b) left unchanged (c) replaced ith a ne thread link.
(d) None of these 27. For hich of the folloing trees, is the process of trave
rsal is faster than others ? (a) Threaded binary trees (b) Lexical ordered binar
y tree (c) m-ary tree (d) None of these 28. Level of any node of a tree is:

(a) its distance from the root (b) height of its left subtree minus height of it
s right subtree (c) height of its right subtree minus height of its left subtree
(d) None of these 29. Which of the folloing statements is TRUE in vie of a th
readed storage representation of a binary tree ? (a) Its inorder threading is di
fferent from its postorder threading (b) The number of NULL links in a threaded
binary tree is very small, but it is non-zero. (c) The number of thread links is
reduced to zero. (d) None of these 30. A dynamic data structure here e can se
arch for desired records in 0 (log n) time is: (a) heap (b) binary search tree (
c) cicularly linked list (d) array 31. Inorder traversal of the binary search tr
ee implies visiting records in: (a) the order of increasing magnitude of their k
ey (b) the order of decreasing magnitude of their key (c) arbitrary order (d) No
ne of these 32. A threaded binary tree has folloing problem: (a) more time cons
uming tree traversal (b) nonsequential memory allocation (c) additional storage
requirement (d) None of these 33. The tree traversal technique in hich the root
is traversed before its children is knon as (a) post order traversal (b) pre-o
rder traversal (c) inorder traversal (d) None of these 34. The maximum number of
nodes in a binary tree of depth 5, is : (a) 31 (b) 16 (c) 32 (d) 15 35. Post or
der traversal of a binary tree starts ith (a) postorder traversal of the left s
ubtree (b) postorder traversal of the right subtree (c) processing of the root n
ode (d) none of the above 36. Ho many cycles must be contained in a tree? (a) I
(b) at least (c) zero (d) 2 37. Suppose that each node in a tree is represented
by a self referential structure having to pointers to point to its left and ri
ght children. These pointers are set to NULL if the corresponding child is empty
. Ho many

NULL pointers does a binary tree ith "n" internal nodes have? (a) n (b) n + 1 (
c) n 1 (d) The number depends on the shape of the tree. 38. If the inorder and p
reorder traversal of a binary tee are D, B, F, E, G, H, A, C and A, B, D, E, F,
G, G, H, C respectively then the postorder traversal of that tree is : (a) D, F,
G, A, B, C, H, E, (b) F, H, D, G, E, B, C, A (c) C, G, H, F, E, D, B, A (d) D,
F, H, G, E, B, C, A 39. In a binary tree, the number of terminal or leaf nodes i
s 10. The number of nodes ith to children is : (a) 9 (c) 15 (b) 11 (d) None of
the above 40. Number of all possible binary trees ith 4 nodes is (a) 14 (b) 34
(c) 24 (d) none of the above 41. Number of nodes in a complete binary tree of d
epth k is (a) 2k (b) 2k (c) 2k - 1 (d) None of the above 42. The number of roote
d binary trees ith n nodes is, (a) equal to the number of ays of multiplying (
n + 1) matrices (b) equal to the number of ays of arranging n out of 2n distinc
t elements. (c) equal to 1/(n + 1)2n Cn (d) equal to n ! (GATE-1990)
43. The toral external path length, EPL, of a binary treeith n external nodes i
s, (EPL= L l here l is the path length of external node ), (GATE-1990) 2 (a)
n alays (b) n log2 n alays 2 (c) equal to n alays (d) O(n) for some special
trees 44. A binary tree T has n leaf nodes. The number of nodes of degree 2 in T
is (a) log2 n (c) n (b) n - 1 (d) 2n (GATE-1995)
45. In the balanced binary tree in Figure given belo, ho many nodes ill becom
e unbalanced hen a node is inserted as a child of the node "g"? (GATE-1996)

(a) 1 (b) 3 (c) 7 (d) 8 46. Which of the folloing sequences denotes the post or
der traversal sequence of the tree of Question above? (a) f e g c d b a (b) g c
b d a f e (c) g c d b f e a (d) f e d g c b a
(GATE-1996)
47. A binary search tree contains the values 1, 2, 3, 4, 5, 6, 7, 8. The tree is
traversed in pre-order and the values are printed out. Which of the folloing s
equences is a valid output? (GATE-1997) (a) 5 3 1 2 4 7 8 6 (c) 5 3 2 4 1 6 7 8
(b) 5 3 1 2 6 4 8 7 (d) 5 3 1 2 4 7 6 8 48. The minimum number of record movemen
ts required to merge five files A (ith 10 records), B (ith 20 records), C (it
h 15 records), D (ith 5 records) and E (ith 25 records) is: (GATE-1999) (a) 16
5 (c) 75 (b) 90 (d) 65 49. Consider the folloing nested representation of binar
y trees: (X Y Z) indicates Y and Z are the left and right subtrees, respectively
, of node X. Note that Y and Z may be NULL, or further nested. Which of the foll
oing represents a valid binary tree? (GATE-2000) (a) (1 2 (4 5 6 7)) (b) (1 ( (
2 3 4) 5 6) 7) (c) (1 (2 3 4)(5 6 7)) (d) (1 (2 3 NULL) (4 5)) 50. Let LASTPOST,
LASTIN and LASTPRE denote the last vertex visited in a postorder, inorder and p
reorder traversal, respectively, of a complete binary tree. Which of the folloi
ng is alays true? (GATE-2000) (a) LASTIN=LASTPOST (b) LASTIN=LASTPRE (c) LASTPR
E=LASTPOST (d) None of the above 51. The number of possible ordered trees ith 3
nodes A, B , C is (a)16 (b) 12 (c) 6 (d) 10 52. A binary tree in hich every no
n-leaf node has non-empty left and right subtrees is called a strictly binary tr
ee. Such a tree ith 10 leaves (a) cannot have more than 19 nodes (b) has exactl
y 19 nodes (c) has e~actly 17 nodes (d) cannot have more than 17 nodes 53. The d
epth of a complete binary tree ith on nodes is (log is to the base to) (a) lo
g(n+l) 1 (b) log(n) (c) log (n-l) + 1 (d) log (n) + 1 54. Which of the folloing
traversal techniques lists the nodes of a binary search tree in ascending order
? (a) Post-order (b) In-order (c) Pre-order (d) None of the above

55. The number of possible binary trees ith 3 nodes is (a) 12 (b) 13 c)5 (d) 15
56. The number of possible binary trees ith 4 nodes is (a) 12 (b) 13 (c) 14 (d
) 15 57. Which of the folloing remarks about Trie Indexing is not true? (a) It
is efficient in dealing ith strings of variable length. (b) It is efficient if
there are fe number of data items. (c) The number of disk accesses cant exceed
the length of the particular string that is searched. (d) It can handle inserti
ons and deletions, dynamically and efficiently. 58. Which of the folloing remar
ks about Trie Indexing is not true? (a) It is an m-ary tree. (b) It is a search
tree of order m. (c) Successful searches should terminate in leaf nodes. (d) Uns
uccessful searches may terminate at any level of the tree structure. 59. A binar
y tree has n leaf nodes. The number of nodes of degree 2 in this tree is (a) 10g
2n (b) n-l (c) n (d) 2n 60. The number of binary trees ith 3 nodes hich hen t
raversed in post-order gives the sequence A, B, C is (a) 3 (b) 9 (c) 7 (d) 5 61.
A 3-ary tree is a tree in hich every internal node has exactly 3 children. The
number of leaf nodes in such a tree ith 6 internal nodes ill be (a) 10 (b) 23
(c) 17 (d) 13 62. A binary search tree contains the values - 1, 2, 3, 4, 5, 6,
7, and 8. The tree is traversed in preorder and the values are printed out. Whic
h of the folloing sequences is a valid output? (a) 5 3 1 2 4 7 8 6 (b) 5 3 1 2
6 4 9 7 (c) 5 3 2 4 1 6 7 8 (d) 5 3 1 2 4 7 6 8 63. Which of the folloing need
not be a binary tree? (a) Search tree (b) Heap (c) AVL-Tree (d) B-Tree
64. What is the maximum total number of nodes in a tree that has N levels? Note
that the root is level (zero) (a) 22N (b) 2N+ 1-1 (c) 2N - 1 (d) 2N - 2N. 65. Ho
 many different binary search trees can be made from three nodes that contain t
he key values 1,2 and 3? (a) 30 (b) 20 (c) 10 (d) 15. 66. Tell hether the follo
ing tree is:

(a) complete
(b) full
(c) heap
(d) None of these
67. Tell hether the folloing tree is:
(a) complete and heap
(b) full (and complete)
(c) full
(d) heap.
68. Tell hether the folloing tree is:
(a) heap
(b) heap (and complete)
(c) full (and complete)
(d) None of these.
69. Ho many different binary trees can be made from three nodes that contain th
e key values 1,2 and 3? (a) 30 (b) 20 (c) 10 (d)5.
Solutions:
1. d 16. c 31. a 46. c 61. d 2. a 17. d 32. d 47. d 62. d 3. b 18. a 33. b 48. c
63. d 4. b 19. b 34. a 49. c 64. b 5. b 20. b 35. a 50. b 65. d 6. b 21. b 36.
c 51. b 66. d 7. c 22. d 37. b 52. b 67. a 8. d 23. b 38. b 53. a 68. c 9. b 24.
b 39. a 54. b 69. a 10. c 25. b 40. a 55. c 11. d 26. c 41. d 56. c 12. a 27. a
42. c 57. b 13. a 28. a 43. b 58. b 14. a 29. a 44. b 59. b 15. a 30. b 45. b 6
0. d
10.20 Exercise Chapter 10
1. What is a tree? Give a suitable example ith a neat diagram. 2. What is a bin
ary tree? Write a C program to insert ne nodes to a binary tree and delete a gi
ven node from a binary tree. 3. State th to different ays to represent binary
tree and explain. 4. Write don the recursive algorithms and find their time co
mplexity for (i) preorder traversal (ii) inorder traversal and (iii) postorder t
raversal of a binary tree

5. What is an expression tree? Create expression tree from the folloing express
ion and explain the construction process. a - b * c + d - log e / f 6. What is a
binary search tree? Write a C program to insert ne nodes to a binary search tr
ee and delete a given node from a binary search tree. 7. What is a Heap? Write a
lgorithms to insert ne nodes to a heap and delete a given node from a heap. 8.
What is a eight balanced binary tree? Briefly describe the Huffman tree and Huf
fman algorithm. 9. What is a height balanced binary tree? Write algorithms to in
sert ne nodes to a height balanced binary tree and delete a given node from a h
eight balanced binary tree. 10. What is a Threaded binary tree? Write algorithms
to (i) find the inorder successor of a node for a threaded binary tree, (ii) fi
nd the inorder predecessor of a node for a threaded binary tree, (iii) perform t
he inorder traversal in a threaded binary tree. 11. What is a m ay search tree?
Write a application of m ay search tree and explain. 12. What is a balanced m
ay search tree? Write algorithms to insert ne nodes to a balanced m ay search
tree and delete a given node from a balanced m ay search tree. 13. What is a R
ed-black tree?explain ith a suitable diagram.

Chapter 11 GRAPH
11.1 Definition
Graph is non linear data structure. Mathematically graph can be defined by the p
air G = (V, E) here, V = finite and non empty set of vertices. E = set of edges
hich are the pair of vertices. For the graph shon in figure 11.1, V = {1, 2,
3, 4} E = {<1, 2>, <1, 3>, <1, 4>, <2, 3>, <3, 4>}
11.2 Basic Terminologies
Undirected graph: A graph, hich has unordered pair of vertices, is called undir
ected graph. In an undirected graph, pictorially the edges have no direction. Su
ppose there is an edge beteen to vertices V 0 and V1, then the edge can be rep
resented as <V0, V1> or <V1, V0>. The graph shon in the figure 11.1 is an undir
ected graph. 1 2
4
3
Figure 11.1: An example of an undirected graph Directed graph: It is a graph in
hich each edge is represented by an ordered pair of vertices <V1, V2> here V1
is the tail and V2 is the head of the edge. In this type of graph each edge has
direction, means <V1, V2> and <V2, V1> ill represent different edges. Directed
graph is also knon as diagraph. The directed graph shon in figure 11.2 can be
represented as: V = {1, 2, 3, 4} E = {<1, 2>, <2, 3>, <3, 1>, <3, 4>, <4, 1>} 1
2
4
3
Figure 11.2: An example of a directed graph Weighted graph: A graph is said to b
e eighted if every edge in the graph is assigned some non-negative value as ei
ght. The eight may be the distance of the edge or the cost to travel along the
edge or some other positive values depending on some parameters. A eighted grap
h is also knon as netork. The graph shon in the figure 11.3 is an example of
a eighted graph. 1
10 8

9
2
12
3
Figure 11.3: An example of a eighted directed graph Adjacent nodes: A node V1 i
s adjacent to or neighbor of another node V 2 if there is an edge from node V 1
to node V2. In figure 11.1, node 1 is adjacent to node 2 and node 2 is adjacent
to node 1 also. But in figure 11.2, node 1 is adjacent to node 2 and node 2 is a
djacent from node 1. Incidence: In an undirected graph the edge <V0, V1> is inci
dent on nodes V0 and V1. In a diagraph the edge <V0, V1> is incident from node V
0 and is incident to node V1. Path and length of path: Path is a sequence of ver
tices and edges, in hich any to consecutive edges are incident and no vertex i
s repeated. The total number of edges on a path is called its length. 2 e1 1 e7
6 Figure 11.4 In the graph shon in figure 11.4 some paths and their path length
s are given belo. Path length 1 e1 2 e2 3 e3 4 e4 5 4 4 e3 3 e2 2 e11 3 1 e5 3
e8 6 2 Cycle and Hamiltonian cycle: A cycle is a path that starts and ends at th
e same vertex. A cycle is a path here the last vertex is adjacent to the first.
A cycle in hich no vertex repeats (such as 1-2-3-1 verus 1-2-3-21) is said to
be simple. The shortest cycle in the graph defines its girth, hile a simple cyc
le hich passes through each vertex is said to be a Hamiltonian cycle. In Figur
11.1 the hamiltonian cycle is 1-2-3-4-1. But in figure 11.4 there is no hamilton
ian cycle. Directed acyclic graph(DAG): A directed acyclic graph is a directd gr
aph that has no cycle. For certain applications it is convenient to deal ith gr
aphs that contain no cycles. For example, a tree is a special kind of graph that
contains no cycles. Obviously, all trees are DAGs. Hoever, not all DAGs are tr
ees. Figure 11.5 shos example of to directed acyclic graph. 1 1 e5 e8 e2 3 e3
4 e4 e6 5
2
3
2
3
4
5
6
7
4

Figure 11.5 Distance: Distance beteen to vertices V1 and V2 is the length of t
he shortest path beteen V1 and V2. In the figure 11.4, distance beteen vertice
s 1 and node 5 is 2. Walk: Walk is a sequence of vertices and edges, in hich an
y to consecutive edges are incident and vertex and edge both can be repeated. I
n figure 11.4, 1 e1 2 e2 3 e6 5 e6 3 e8 6 e7 1 is a alk. Tour: Tour is a sequen
ce of vertices and edges, in hich any to consecutive edges are incident and no
edge is repeated. In figure 11.4, 1 e1 2 e2 3 e3 4 e4 5 e6 3 e8 6 is a tour. De
gree: Number of nodes adjacent from a vertex V is called degree of V and is repr
esented as dg (V). In the figure 11.1, the degree of the vertices of the graph i
s: dg (1) = 3 dg (2) = 2 dg (3) = 3 dg (4) = 2 Indegree: The indegree of a verte
x in a graph is the number of edges coming to that vertex or the number of edges
incident to it. In figure 11.6, the indegrees of vertices 1, 2, 3, 4, 5 and 6 a
re 0, 1, 1, 2, 2 and 2 respectively. 2 1 3 5 4 6
Figure 11.6 Outdegree: The outdegree of a vertex in a graph is the number of edg
es going outside of that vertex or the number of edges incident from it. In figu
re 11.6, the outdegree of vertices 1, 2, 3, 4, 5 and 6 are 2, 3, 1, 1, 2 and 0 r
espectively. Source: In a graph, a vertex hich has no incoming edges, but has o
utgoing edges, is called a source. The in degree of a source vertex is 0. In fig
ure 11.6, node 1 is a source vertex. Sink: A vertex, hich has no outgoing edges
, but has incoming edges, is called a sink. The outdegree of a sink vertex is 0.
In figure 11.6, node 6 is a sink vertex. Pendant Vertex: In a directed graph, a
vertex is said to be pendant if its indegree is equal to 1 and outdegree is equ
al to 0. In an undirected graph, the degree of a pendant vertex is 1. In figure
11.7, node 5 is pendant vertex. 1 3 5

2
4 Figure 11.7
Complete graph: A graph G is complete iff every node U in G is adjacent to every
other node V in G. Total number of edges in a complete graph = n(n-1)/2 here n
= total number of vertices.
2
Figure 11.8: An example of a complete graph Multiple edge: Distinct edges e and
e are called multiple edges if they connect the same end points i.e. e (U, V) and
e (U, V). In figure 11.9, the edges e6 and e7 are multiple edges. Loop: An edge
is called loop if it has identical endpoints i.e. e (U, U). In figure 11.9, e3 i
s a loop. Multigraph: A graph is said to be a multigraph if it contains either m
ultiple edges or loops. Figure 11.9 shos a multi graph.
e3 e2 e4 e1 e6 e8 e7 e5
4
3
Figure 11.9: An example of a multi graph Chromatic number: The chromatic number
of a graph is the least number of colors it takes to color its vertices so that
adjacent vertices have different colors. For example, the graph of figure 11.6 h
as chromatic number to. Bipartite graph: A graph G is called bipartite if the v
ertex set V of G can be partitioned into to disjoint subsets V1 and V2 such tha
t every edge joins a vertex in V1 ith a vertex in V2. Figure 11.10 shos a bipa
rtite graph.
V1 V2 V1
V2

Figure 11.10: Example of bipartite graph Planar graph: A graph is called planar
if it can be dran in the plane so that edges intersect only at their end points
. Properties: 1. For any planar graph G ith n 3 vertices has at most 3n 6 edges
. 2. Four color theorem: Every planar graph can be colored using no more than fo
ur colors. 3. Kuratoskis theorem: Graph G is non-planar iff it has a sub graph K
5 or K3, 3.
Figure 11.11(a): K5
Figure 11.11(b): K3, 3
Connected graph: An undirected graph is connected if there is a path from any no
de of graph to any other node, or any node is reachable from any other node. Fig
ure 11.12(a) shos a connected graph. e2 1 2 1 2 e3 e6 3 e1 e4 3 5 e5 Figure 11.
12(a): Connected graph Figure 11.12(b): Disconnected graph 4 5 4
Articulation point: Let G be a connected graph. An articulation point of G is a
vertex hose removal (along ith all adjacent edges) disconnects G. In a graph t
here can be more than one articulation points. In figure 11.12(a) vertex 2 is an
articulation point. Bridge: Let G be a connected graph. A bridge of G is an edg
e hose removal disconnects G. In figure 11.12(a) edge e3 is a bridge. Euler tou
r: An Euler tour of a connected graph G is a cycle that traverses each edge of G
exactly once, although it may visit a vertex more than once.
11.3 Representation of a graph
There are to ays; e can implement a graph in a computer program. These are: 1
. Sequential representation: In sequential representation e use a 2-dimentional
array of order n X n here n is the total number of vertices in the graph. This
is a simple ay to represent a graph into memory. A graph ith n nodes takes n
2 space to represent it sequentially in memory and also takes O(n2) time to perf
orm the graph operations and to solve the graph problems. Adjacency Matrix:

Suppose G is a graph ith n nodes and suppose the vertices of graph G are ordere
d and are called 1, 2, 3 n. Then the adjacency matrix A of the graph G is an n X
n matrix defined as follos: A [i][j] = 1 if there is an edge from node i to nod
e j. =0 Otherise Such a matrix hich contains only 1 or 0 is called a bit matri
x or Boolean matrix. The adjacency matrix of an undirected simple graph is a sym
metric matrix. In the adjacency matrix of an undirected simple graph, the number
of 1 is tice the number of edges in the graph. The adjacency matrix for the fi
gure 11.13 is: is: 1 1 2 3 4 5 0 1 0 0 1 2 1 0 1 1 1 3 0 1 0 1 0 4 0 1 1 0 1 5 1
1 0 1 0 1 2 3 4 5 1 0 0 0 0 0 2 1 0 0 0 1 10 4 5 3 0 1 0 0 0 4 0 1 1 0 0 5 1 0
0 1 0 The adjacency matrix for the figure 11.14
1
2 3
1
2 3 2
1
2 7 4 8
6 3
5
4 Figure 11.13
5
4 Figure 11.14
5 Figure 11.15
Path Matrix: Suppose G is a directed graph ith n nodes and suppose the vertices
of graph G are ordered and are called 1, 2, 3 n. Then the path matrix P of the g
raph G is an n X n matrix defined as follos: P [i][j] = 1 if there is a path fr
om vertex i to vertex j. =0 Otherise The path matrix for the figure 11.14 is: 1
1 2 3 4 5 0 0 0 0 0 2 1 1 1 1 1 3 1 1 1 1 1 4 1 1 1 1 1 5 1 1 1 1 1

Weighted matrix: The eighted matrix W of a eighted graph G ith n


n X n matrix hich can be defined as: W [i][j] = eight of the edge
ere is an edge from i to j. = (i.e. a large value) Otherise. The
x for the figure 11.15 is: 1 1 2 3 4 5 2 10 4 3 6

nodes is an
<i, j> if th
eighted matri
4 7 8 5 2

2. Linked representation: In the adjacency matrix it is difficult to insert ne


nodes or edges in the graph. First of all the time complexity for insertion or d
eletion of ne nodes or edges in the adjacency matrix is high. More over as the
array is static in nature; some spaces in the matrix defined to represent the gr
aph, may be asted or due to more vertices underflo in space may occur. Further
more if the number of edges in the graph ith n nodes is O(n) or O(nlog2n), the
n the matrix is sparse; hence a great deal of spaces ill be asted. If the adja
cency matrix of the graph is sparse then it is more efficient to represent the g
raph through adjacency list. In adjacency list representation of graph, e ill
maintain to lists. First list ill keep track of all the nodes in the graph and
second list ill maintain a list of adjacent nodes for each node to keep the tr
ack of the edges. Structure of a node in the vertex list: struct VNode { struct
VNode *ptrNV; int VNo; struct ENode *ptrAV; }; typedef struct VNode Vertex;
// Pointer to next vertex in the list. // Name of the vertex. // Pointer to adja
cent vertex to this node.
Name of the vertex ptrNV VNo ptrAV Pointer hich points to the first vertex adja
cent to this node.
Pointer hich points to the next vertex in the list. Structure of an edge node i
n the edge list: struct ENode { int VNo; struct ENode *ptrAV;
// Name of the Vertex. // Pointer to the destination vertex of the next edge.

}; typedef struct ENode Edge; Pointer hich points to the next adjacent node.
VNo
ptrAV
Destination node of the edge The adjacency list for the graph shon in figure 11
.13 is: 1 2 3 4 N 5 2 1 2 2 1 5 3 4 3 2 N 5 4 N N N 4 5 N
The adjacency list for the graph shon in figure 11.14 is: 1 2 3 4 N 5 2 3 4 5 2
N N N 5 4 N N
11.4 Operations on a graph
Suppose a graph is maintained in memory by the linked representation. No e il
l look for the folloing operations on a graph. 11.4.1 Searching in a graph: Sup
pose first e ant to find a vertex in the graph. Algorithm 11.1 1. Algorithm fn
FindVertex(V) 2. // Purpose : This algorithm finds hether a vertex is in the gr
aph or not. 3. // Input : We have to search for the vertex V in the vertex list.
4. // Output : This algorithm returns the address of the vertex V for a success
ful search. Otherise it returns //NULL. 5. {

6. 7.
Vertex *ptrTemp; ptrTemp = ptrStart;
// A global variable ptrStart contains the address of the first vertex in the ve
rtex
list 8. hile(ptrTemp != NULL) // Continue until vertex list is not empty. 9. {
10. if(ptrTemp->VNo == V) 11. return ptrTemp; 12. ptrTemp = ptrTemp->ptrNV; //Go
to next vertex in the vertex list. 13. } 14. return NULL; //Return NULL if vert
ex does not exist. 15. }//End of algorithm No e ill find an edge (U, V) in th
e graph. For this purpose first find the vertex U in the vertex list and then se
arch the edge list of U to find the vertex V. Algorithm 11.2 1. Algorithm fnFind
Edge(U,V) 2. // Purpose : This algorithm finds hether an edge is in the graph o
r not. 3. // Input : We have to search for the edge (U, V) in the edge list. 4.
// Output : This algorithm returns the address of the edge (U, V) for a successf
ul search. Otherise it returns //NULL. 5. { 6. Vertex *ptrTemp1; 7. Edge *ptrTe
mp2; 8. ptrTemp1 = ptrStart; // A global variable ptrStart contains the address
of the first vertex in the vertex list 9. // Find the vertex U from the vertex l
ist. 10. hile(ptrTemp1 != NULL) // Continue until vertex list is not empty. 11.
{ 12. if(ptrTemp1->VNo == U) // Get the address of the node U from the vertex l
ist. 13. break; 14. ptrTemp1 = ptrTemp1->ptrNV; // Go to next vertex in the vert
ex list. 15. } 16. // Find the vertex V from the edge list of U. 17. if(ptrTemp1
!= NULL) // If U exists in the vertex list, then traverse the edge list of the
vertex U. 18. { 19. ptrTemp2 = ptrTemp1->ptrAV; 20. hile(ptrTemp2 != NULL) // C
ontinue until the edge list of vertex U is NULL. 21. { 22. if(ptrTemp2->VNo == V
) 23. return ptrTemp2; 24. ptrTemp2 = ptrTemp2->ptrAV; // Go to next vertex in t
he edge list. 25. } 26. } 27. return NULL; 28. }// End of algorithm Insertion in
a graph: Insert ne vertex To insert a ne vertex V the folloing steps are per
formed: Step 1: First check hether V exists in the list or not. If V is already
in the list then exit.

Step 2: Create ne vertex. Step 3: Copy V to the data field of the nely created
vertex. Step 4: Set NULL to the adjacent vertex list of it. Step 5: Set V as th
e first vertex in the list. Algorithm 11.3 describes the above steps. Algorithm
11.3 1. Algorithm fnInsertNode(V) 2. // Purpose : This algorithm inserts a ne n
ode at the first of the vertex list. 3. // Input : V is the vertex number to be
inserted in the graph. 4. // Output : None. 5. { 6. Vertex ptrNeVertex; 7. if(f
nFindVertex(V) != NULL) 8. { 9. print Duplicate Vertex; 10. exit(); 11. } 12. ptrN
eVertex = (Vertex *)(malloc(sizeof(Vertex))); // Create a ne vertex. 13. ptrNe
Vertex->VNo = V; //Copy V to data field of ne vertex. 14. ptrNeVertex->ptrAV
= NULL; //Set edge field of ne vertex to NULL. 15. ptrNeVertex->ptrNV = ptrSta
rt; //Set current first vertex as the next vertex of ne one. 16. ptrStart = ptr
NeVertex; //No ne vertex is the first vertex in the vertex list. 17. }// End
of algorithm Inert ne edge To insert a ne edge (U, V) perform folloing steps:
Step 1: If U is not in the vertex list or edge (U, V) already exist, then exit.
Step 2: Create ne edge. Step 3: Set V in the data field of ne edge. Step 4: I
nert nely created edge V at the beginning of the adjacency vertex list of U. Al
gorithm 11.4 describes the process. Algorithm 11.4 1. Algorithm fnInsertEdge(U,
V) 2. // Purpose : This algorithm inserts a ne edge at the last of the edge lis
t of vertex U. 3. // Input : The edge is from vertex U to vertex V. 4. // Output
: None. 5. { 6. Vertex *ptrLoc1; 7. Edge *ptrLoc2; 8. ptrLoc1 = fnFindVertex(U)
; //Get the address of the vertex U. 9. ptrLoc2 = fnFindEdge(U, V); // Get the a
ddress of the edge (U, V). 10. if(ptrLoc1 != NULL and ptrLoc2 === NULL) // If U
is in the vertex list but V is not in the edge list of U. 11. { 12. ptrNeEdge =
(Edge *)(malloc(sizeof(Edge))); //Create a ne edge. 13. ptrNeEdge->VNo = V; /
/Copy V to the data field of ne edge. 14. ptrNeEdge->ptrAV = ptrLoc1->ptrAV; /
/Insert V in the edge list of U. 15. ptrLoc1->ptrAV = ptrNeEdge; //Set vertex V
as the first edge in the edge list of U. 16. } 17. } // End of algorithm 11.4.3
Deletion from graph:

Delete a vertex The steps to delete a vertex V are folloings: Step 1: If V does
not exist, then exit. Step 2: Delete all the edges ending at V. Step 3: Delete
all the edges starting ith V. Step 4: Delete V from the list. Algorithm 11.5 de
scribes the steps to delete a vertex. Algorithm 11.5 1. Algorithm fnDeleteVertex
(V) 2. // Purpose : This algorithm deletes an existing node from the vertex list
of a graph. 3. // Input : V is the vertex number to be deleted from the vertex
list. 4. // Output : None. 5. { 6. Vertex *ptrLoc1, *ptrTemp; 7. Edge *ptrLoc2,
*ptrLoc3; 8. ptrLoc1 = fnFindVertex(V); //Get the address of the vertex V in the
vertex list. 9. ptrLoc2 = ptrLoc1->ptrAV; //Get the address of the first vertex
in the edge list of V. 10. hile(ptrLoc2 NULL) 11. { 12. ptrLoc3 = ptrLoc2->ptr
AV; //Delete all the edges from the edge list of V. 13. free(ptrLoc2); 14. ptrLo
c2 = ptrLoc3; 15. } 16. ptrTemp = ptrStart; 17. hile(ptrTemp NULL) 18. { 19. U
= ptrTemp->VNo; 20. // Get the address of the edges ending at the vertex V. //De
lete all the edges ending at V. 21. fnDeleteEdge(U,V); 22. ptrTemp = ptrTemp->pt
rNV; 23. } 24. ptrTemp = ptrStart; 25. hile(ptrTemp->ptrNV ptrLoc1) 26. ptrTemp
= ptrTemp->ptrNV; //Delete the node V from the vertex list. 27. ptrTemp->ptrNV
= ptrLoc1->ptrNV; 28. free(ptrLoc1); 29. }// End of algorithm Delete an edge The
steps to delete an edge (U, V) are: Step 1: If the edge (U, V) does not exist,
then exit. Step 2: First go the vertex U in the vertex list. Step 3: Delete vert
ex V from the adjacency vertex list of U. See algorithm 11.6. Algorithm 11.6 1.
Algorithm fnDeleteEdge(U, V) 2. // Purpose : This algorithm deletes the edge <U,
V> from the edge list of vertex U. 3. // Input : The edge is from vertex U to v
ertex V. 4. // Output : None. 5. {

6. Vertex *ptrLoc1; 7. Edge *ptrLoc2,*ptrTemp2; 8. ptrLoc1 = fnFindVertex(U); //


Find the address of the vertex U in the vertex list. 9. ptrLoc2 = fnFindEdge(U,
V); //Find the address of the edge to be deleted. 10. if(ptrLoc1!=NULL) // If th
e edge exists. 11. { 12. ptrTemp2 = ptrLoc1->ptrAV; 13. //Get the address of the
previous edge of <U, V> in the edge list of U. 14. hile(ptrTemp2->ptrAV!=ptrLo
c2) 15. ptrTemp2 = ptrTemp2->ptrAV; 16. ptrTemp2->ptrAV = ptrLoc2->ptrAV; //Set
the link. 17. free(ptrLoc2); 18. } 19. }//End of Algorithm
11.5 Traversal of a graph
There are to standard ays to traverse a graph. First one is Breadth first sear
ch (BFS) and the second one is Depth first search (DFS). The procedure BFS uses
a queue to store the unvisited vertices and DFS uses a stack for this purpose. T
o distinguish beteen the visited vertices and unvisited vertices, e give the c
olor to each and every node of the graph. Initially all the vertices have color
WHITE to indicate that they are not yet visited. When a node is placed into a qu
eue or stack, then the color is changed to BLACK to indicate that the vertex is
no visited. 11.5.1 Breadth first search: In this traversal technique, first sel
ect a vertex S to start the traversal. Initially set the color of all the vertic
es to WHITE. Insert S into the queue and change its color to BLACK as no S is a
visited vertex. No delete the front node N from the queue. Visit all the adjac
ent vertices of N and insert to queue those neighbors of N that have the color W
HITE. Change their colors to BLACK. Continue this procedure until queue is empty
. Algorithm 11.7 1. Algorithm fnBFS(S) 2. // Purpose : This algorithm finds the
BFS traversal of a given graph. 3. // Input : S is the starting node from hich
e have to start the traversal. 4. // Output : None. 5. { 6. for( all the vertic
es j of the graph) 7. Color[j] = WHITE. //Initialize the color of all nodes to W
HITE. 8. fnInsert(S); //Put the starting node S into queue. 9. Color[S] = BLACK;
//Change its color to BLACK. 10. hile(queue is not empty) 11. { 12. N = fnDele
te(); //Remove the front node N of queue. 13. for(each adjacent vertex j of N) /
/Visit all the adjacent vertex of N. 14. if(Color[j] == WHITE) 15. { 16. fnInser
t(j); //Insert into queue all the neighbors of N of color WHITE. 17. Color[j] =
BLACK; //Change their colors to BLACK. 18. } 19. } 20. }// End of algorithm

Time Complexity: If e represent the graph using adjacency list, then e have to
traverse each edge at most tice (for an undirected graph). Hence time complexi
ty is O (e) here e is the total number of edges. If e represent the graph usin
g adjacency matrix, then e have to check n entries in the matrix for each verte
x to find its adjacent vertices. As there are total n vertices, so time complexi
ty is O (n2). Example 11.1: Consider the graph shon in the figure 11.16. Suppos
e e have to find the BFS traversal of this graph starting from vertex 1.
1
2
3
4
5
Figure 11.16 Initially: Color[1] = Color[2] = Color[3] = Color[4] = Color [5] =
WHITE STEP 1: Insert starting node 1 into queue and change its Color to Black.
1
2
3
4
1
5
Status of the graph Traversal =
Content of the queue
STEP 2: Delete front node 1 from queue and insert into QUEUE nodes 2, 3 and 4 as
their color is WHITE.
1
2
3
4
4 3 2
5
Status of the graph Traversal = 1
Content of the queue

STEP 3: Delete front node 2 from queue. The adjacent nodes of 2 are vertex 1 and
vertex 5. But only the vertex 5 has color WHITE. So insert only vertex 5 into t
he queue.
1
2
3
4
5 4 3
5
Status of the graph
Content of the queue
Traversal = 1 2 STEP 4: Delete node 3 from queue. As all the neighbors of vertex
3 have color BLACK, so no more insertion into queue takes place.
1
2
3
4
5 4
5
Status of the graph Traversal = 1 2 3 STEP 5: Delete node 4 from queue ithout a
ny insertion into queue.
1
Content of the queue
5
2 3 4
5
Status of the graph Traversal = 1 2 3 4 STEP 6: Delete node 5 from queue.
1
Content of the queue
2
3
4
5

Status of the graph Traversal = 1 2 3 4 5 As no the queue is empty, so traversa


l is finished.
Content of the queue
11.5.2 Depth first search: In this traversal technique, e use a stack instead o
f queue. Like the BFS traversal, initially set the color of all the vertices to
WHITE. Insert starting vertex S into the stack and change its color to BLACK. No
 delete the top node N from the stack. Visit all the adjacent vertices of N and
insert to stack those neighbors of N that have the color WHITE. Change their co
lors to BLACK. Continue this procedure until stack is empty. Algorithm 11.8 1. A
lgorithm fnDFS(S) 2. // Purpose : This algorithm finds the DFS traversal of a gi
ven graph. 3. // Input : S is the starting node from hich e have to start the
traversal. 4. // Output : None. 5. { 6. for( all the vertices j of the graph) 7.
Color[j] = WHITE; //Initialize the color of all nodes to WHITE. 8. fnPush(S); /
/Push the starting node S into stack. 9. Color[S] = BLACK; //Change its color to
BLACK. 10. hile(stack is not empty) 11. { 12. N = fnPop(); //Pop the top node
N of the stack. 13. for(each adjacent vertex j of N) //Visit all the adjacent ve
rtex of N. 14. if(Color[j] == WHITE) 15. { 16. fnPush(j); //Push into stack all
the WHITE neighbors of N. 17. Color[j] = BLACK; //Change their colors to BLACK.
18. } 19. } 20. }// End of algorithm Example 11.2: Consider the graph shon in t
he figure 11.16. Suppose e have to find the DFS traversal of this graph startin
g from vertex 1. Initially: Color[1] = Color[2] = Color[3] = Color[4] = Color [5
] = WHITE STEP 1: Insert starting node 1 into stack and change its color to Blac
k.
1
2
3
4
1
5

Status of the graph Traversal =


Content of the stack
STEP 2: Delete top node 1 from stack and insert into stack nodes 2, 3 and 4 (the
neighbors of 1) as their color is WHITE. Change the color of the vertices (2, 3
and 4) to BLACK.
1
2
3
4
4 3 2
5
Status of the graph Traversal = 1
Content of the stack
STEP 3: Delete top node 4 from stack. The adjacent nodes of 4 are vertex 1 and v
ertex 5. But only the vertex 5 has color WHITE. So insert only vertex 5 into the
stack.
1
2
3
4
5 3 2
5
Status of the graph Traversal = 1 4
Content of the stack
STEP 4: Delete node 5 from queue. As all the neighbors of vertex 3 have color BL
ACK, so no more insertion into stack takes place.
1
2
3
4
3 2
5
Status of the graph

Content of the stack

Traversal = 1 4 5
STEP 5: Delete node 3 from stack ithout any insertion into stack.
1
2
3
4
2
5
Status of the graph Traversal = 1 4 5 3 STEP 6: Delete node 2 from stack.
1
Content of the stack
2
3
4
5
Status of the graph Traversal = 1 4 5 3 2 As no the stack is empty, so traversa
l is finished.
Content of the stack
11.6 Shortest path calculation (Dijkstras algorithm)
Dijkstras algorithm is a greedy algorithm for solving the single-source, shorte
st-path problem on an edgeeighted graph in hich all the eights are non-negati
ve. It finds the shortest paths from some initial vertex, say s, to all the othe
r vertices one-by-one. The essential feature of Dijkstras algorithm is the orde
r in hich the paths are determined: The paths are discovered in the order of th
eir eighted lengths, starting ith the shortest, and proceeding to the longest.
Dijkstras algorithm keeps to sets of vertices: U Vertices hose shortest paths
have already been determined V-U Remainder vertices. To differentiate beteen th
ese to sets, e maintain an array status []. Status[i] = Permanent denotes the
vertex i is in set U and status[i] = Temporary indicates i is in V-U. Here e ma
intain to more arrays: dist[] and pred[]. Dist[i] is the length of the shortest
path from source node (s) to node i. pred[i] denotes the node preceding node i
in the shortest path. Initially for all the nodes i of the graph, dist[i] = and
pred[i] = NULL and status[i] = Temporary.

Algorithm 11.9 1. Algorithm fnDijkstra (s, d, n) 2. // Purpose : This algorithm


finds the shortest path beteen the vertex s and vertex d. 3. // Input : s is th
e starting vertex and d is the destination vertex. n is the total number of vert
ices in the graph. 4. // Output : None. 5. { 6. for (i = 1; i <= n; i++) 7. { 8.
dist[i] = ; //Initialize the arrays. 9. pred[i] = NULL; 10. status[i] = Tempora
ry; 11. } 12. status[s] = Permanent; 13. dist[s] = 0; 14. current = s; //current
keeps the track of the last permanent vertex. 15. hile(current != d) //Continu
e the procedure until the status of the destination vertex d is Permanent. 16. {
17. dc = dist[current]; 18. for(all vertices i, that are adjacent of current an
d status[i] = Temporary) 19. { 20. nedist = dc + W[current][i]; //W[][] is eig
hted matrix. 21. if(nedist < dist[i]) 22. { 23. dist[i] = nedist; 24. pred[i]
= current; 25. } 26. } 27. Choose node k such that status[k] = Temporary and dis
t[k] is smallest; 28. current = k; 29. status[k] = Permanent; 30. } 31. }// End
of algorithm
Example 11.3: 8
1 2
5
2 7
4
4
16
6
3
4 3 6 3
7
9 4 5 8
5
5 2
8

Figure 11.17 Suppose here s = 1 and d = 5 Step 1: No current = 1. 8


1 2
5
2 7
4
16
3
4
4 3 6 3
7
9 4 5 8
5
6
5 2
8
NODE dist Pred status 1 0 NULL Permanent 2 NULL Temporry 3 NULL Temporry 4 NUL
L Temporry 5 NULL Temporry 6 NULL Temporry 7 NULL Temporry 8 NULL Temporry
dc = dist[1] = 0 Vertices 2, 3 nd 4 re djcent to 1 nd re Temporry. dist[2
] > dc + weight[1][2] dist[3] > dc + weight[1][3] dist[4] > dc + weight[1][4] =>
> 0 + 8 re lbel 2 => > 0 + 2 re lbel 3 => > 0 + 7 re lbel 4 pred[2] = 1 pred
[3] = 1 pred[4] = 1
NODE dist Pred sttus 1 0 NULL Permnent 2 8 1 Temporry 3 2 1 Temporry 4 7 1 T
emporry 5 NULL Temporry 6 NULL Temporry 7 NULL Temporry 8 NULL Temporry STE
P 2: dist[3] is smllest mong the temporry nodes. So, now current = 3 nd mke
it permnent. NODE dist Pred sttus

1 2 3 4 5 6 7 8 8
1
0 8 2 7
NULL 1 1 1 NULL NULL NULL NULL
Permnent Temporry Permnent Temporry Temporry Temporry Temporry Temporry
2
5
2 7
4
16
3
4
4 3 6 3
7
9 4 5 8
5
6
5 2
8
dc = dist[3] = 2 Here 4 nd 7 re djcent to 3 nd re temporry. dist[4] > dc
+ weight[3][4] => 7 > 2 + 4 dist[7] > dc + weight[3][7] => > 2 + 3 re lbel 4 re
lbel 7 pred[4] = 3 pred[7] = 3
NODE dist Pred sttus 1 0 NULL Permnent 2 8 1 Temporry 3 2 1 Permnent 4 6 3 T
emporry 5 NULL Temporry 6 NULL Temporry 7 5 3 Temporry 8 NULL Temporry STEP
3: dist[7] is smllest mong the temporry nodes. So, now current = vertex 7 n
d mke it permnent. NODE dist Pred sttus 1 0 NULL Permnent 2 8 1 Temporry 3
2 1 Permnent 4 6 3 Temporry 5 NULL Temporry 6 NULL Temporry

7 8 8
1
5
3 Permnent NULL Temporry
2
5
2 7
4
16
3
4
4 3 6 3
7
9 4 5 8
5
6
5 2
8
dc = dist[7] = 5 Here vertices 4, 5 nd 8 re temporry djcent node to 7. dist
[4] < dc + weight[7][4] dist[5] > dc + weight[7][5] dist[8] > dc + weight[7][8]
6<5+3 >5+4 >5+5 Dont re lbel vertex 4 re lbel vertex 5 re lbel vertex 8 pred[5]
= 7 pred[8] = 7
NODE dist Pred sttus 1 0 NULL Permnent 2 8 1 Temporry 3 2 1 Permnent 4 6 3 T
emporry 5 9 7 Temporry 6 NULL Temporry 7 5 3 Permnent 8 10 7 Temporry STEP
4: dist[4] is smllest mong the temporry nodes. So, now current = vertex 4 nd
mke it permnent. NODE dist Pred sttus 1 0 NULL Permnent 2 8 1 Temporry 3 2
1 Permnent 4 6 3 Permnent 5 9 7 Temporry 6 NULL Temporry 7 5 3 Permnent 8
10 7 Temporry

8
1 2
5
2 7
4
16
3
4
4 3 6 3
7
9 4 5 8
5
6
5 2
8
dc = dist[4] = 6 Here only vertex 5 is the temporry djcent node to 4. dist[5]
< dc + weight[4][5] 9<6+9 Dont re lbel vertex 5.
NODE dist Pred sttus 1 0 NULL Permnent 2 8 1 Temporry 3 2 1 Permnent 4 6 3 P
ermnent 5 9 7 Temporry 6 NULL Temporry 7 5 3 Permnent 8 10 7 Temporry STEP
5: dist[2] is smllest mong the temporry nodes. So, now current = vertex 2 nd
mke it permnent. NODE dist Pred sttus 1 0 NULL Permnent 2 8 1 Permnent 3 2
1 Permnent 4 6 3 Permnent 5 9 7 Temporry 6 NULL Temporry 7 5 3 Permnent 8
10 7 Temporry

8
1 2
5
2 7
4
16
3
4
4 3 6 3
7
9 4 5 8
5
6
5 2
8
dc = dist[2] = 8 Here vertex 6 is the temporry djcent node to B. dist[6] > dc
+ weight[2][6] > 8 + 16 re lbel vertex 6 pred[6] = 2
NODE dist Pred sttus 1 0 NULL Permnent 2 8 1 Permnent 3 2 1 Permnent 4 6 3 P
ermnent 5 9 7 Temporry 6 24 2 Temporry 7 5 3 Permnent 8 10 7 Temporry STEP
6: dist[5] is smllest mong the temporry nodes. So, now current = 5 nd mke i
t permnent. NODE dist Pred sttus 1 0 NULL Permnent 2 8 1 Permnent 3 2 1 Perm
nent 4 6 3 Permnent 5 9 7 Permnent 6 24 2 Temporry 7 5 3 Permnent 8 10 7 te
mp

8
1 2
5
2 7
4
16
3
4
4 3 6 3
7
9 4 8
5
6
5 2
5 As 5 is our destintion node, the process will be stopped here. pred[5] = 7 pr
ed[7] = 3 pred[3] = 1 So, the shortest pth from 1 to 5 is 1375 And the cost of the
shortest pth from vertex 1 to 5 is 9.
8
11.7 Wrshlls lgorithm
Let G be  directed grph with n vertices 1, 2, 3n. Suppose we wnt to find the p
th mtrix of G. Wrshll gve n lgorithm for this purpose. This lgorithm is d
iscussed in this section nd  similr lgorithm is used to clculte the shorte
st pth for  weighted grph. Pth Mtrix: First we define n X n Boolen mtrice
s P0, P1Pn s follows: Pk[i][j] = 1 If there is  simple pth from i to j which doe
s not use ny other vertices except possibly 1.k. =0 Otherwise. To store the pth
mtrix of the grph G we re tking  two dimensionl rry P[][] with order n
X n. Initilly the pth mtrix P is sme s the djcency mtrix. Now Pk[i][j] m
ens we wnt to trverse from vertex i to vertex j through vertex k. So Pk[i][j]
is 1 if either we cn go from vertex i to vertex j through vertex k or vertex j
is lredy rechble from vertex i through some previous vertices. Hence Pk[i][
j] = 1 cn occur only if one of the following conditions is stisfied: 1) Pk-1[i
][j] = 1 (i.e. i is rechble from j through some previous vertices) 2) Pk-1[i][
k] = 1 nd Pk-1[k][j] = 1 ( i.e vertex k is rechble from i nd j is rechble
from k) The lgorithm to find the pth mtrix is shown in lgorithm 11.10. Algor
ithm 11.10 1. Algorithm fnWrshllPM(n) 2. // Purpose : This lgorithm finds the
pth mtrix for  directed grph G. 3. // Input : n is the totl number of vert
ices in G. 4. // Output : None. 5. { 6. //First copy the contents of djcency m
trix A to pth mtrix P. 7. for(i = 1;i<=n;i++) 8. for(j=1;j<=n;j++) 9. P[i][j]
= A[i][j];

10. //Compute different itertions of P. 11. for(k=1;k<=n;k++) //k is the itert


ion number. 12. for(i=1;i<=n;i++) 13. for(j=1;j<=n;j++) 14. P[i][j] = P[i][j] ||
(P[i][k] && P[k][j]); 15. }// End of lgorithm. 15 1 6 2 4 1 Figure 11.18 Exmp
le 11.4: The pth mtrix for the figure 11.18 cn be clculted s follows: Firs
t find the djcency mtrix A for the grph. A= 1 0 0 1 1 0 0 0 0 1 0 1 0 0 1 0
3 2 2 1
Initilly: P = A P= 1 0 0 1 1 0 0 0 0 1 0 1 0 0 1 0
Itertion 1: P1 = 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 0 1 0 1 1 1 0
1 1 1 0 1 0 0 1 0 0 0 1 0 1 1 1 1
Itertion 2: P =
2
Itertion 3: P =
3

Itertion 4: P =
4
1 1 1 1
1 1 1 1
1 1 1 1
1 1 1 1

The finl pth mtrix of the grph shown in the figure 11.18 is P4. Shortest pt
h: Consider  directed weighted grph G with n vertices. The weighted mtrix for
G is n n X n mtrix. The pth mtrix of G tells us whether there is  pth bet
ween two nodes. Now our gol is to find the pth between two vertices i nd j wi
th minimum weight or cost nd for this purpose  two dimensionl rry S[][] is
used to store the weight of the shortest pth between vertex i nd vertex j. In
pth mtrix the entry P k[i][j] is 1, if either Pk-1[i] [j] is 1 or (Pk-1[i][k]
= 1 nd Pk-1[k][j] = 1). Similrly, we cn clculte the shortest weighted pth
from vertex i to vertex j s follows: Sk[i][j] = min {weight of Pk-1[i][j], weig
ht of Pk-1[i][k] + weight of Pk-1[k][j]} = min {Sk-1[i][j], Sk-1[i][k] + Sk-1[k]
[j]} The lgorithm to find the shortest pth is shown in lgorithm 11.11. Algori
thm 11.11 1. Algorithm fnWrshllSP(n) 2. // Purpose : This lgorithm finds the
shortest pth for ll the pir of vertices of the grph G. 3. // Input : n is th
e totl number of vertices in G. 4. // Output : None. 5. { 6. //First copy the w
eighted mtrix or cost mtrix W to shortest pth mtrix S. 7. for(i = 1;i<=n;i++
) 8. for(j=1;j<=n;j++) 9. S[i][j] = W[i][j]; 10. //Compute different itertions
of P. 11. for(k=1;k<=n;k++) //k is the itertion number. 12. for(i=1;i<=n;i++) 1
3. for(j=1;j<=n;j++) 14. S[i][j] = min{S[i][j] , (S[i][k] + S[k][j])}; //Compute
new distnce between i nd j 15. }// End of lgorithm Exmple 11.5: The shortes
t pth mtrix for the grph shown in figure 11.18 cn be clculted s follows:
First find the weighted mtrix W for the grph. 15 W= 6 Initilly: S = W 15 2 2
1 1 2

S0 =
6

1 1
2 Shortest pth 2 2 5 3 2 3 5 3 2 3 1, 1 4, 1 1, 1 4, 1 1, 1 4, 1 1, 2 4, 1,
, 2 4, 1, 2 1, 2 4, 1, 2 2, 3 4, 3 3, 4 Minimum weight Itertion 1: S =
1
15 6 15 6 15 6 11 9 8 6
2 8 2 8 2 8 2 11 10 8
1 1 3 1 1 3 1 1 3 1 3 1
Itertion 2: S =
2
1, 2, 3 2, 3 3, 4 4, 3 1, 2, 3 2, 3 4, 3 1, 2 2, 3, 4, 1, 2 3, 4, 1, 2 4, 1, 2 1
, 2, 3, 4 2, 3, 4 3, 4 4, 3, 4 1, 2, 3 2, 3 3, 4, 3 4, 3 1, 2, 3, 4 2, 3, 4 3, 4
4, 3, 4
Itertion 3: S3 =
Itertion 4: S =
4
1, 2, 3, 4, 1 2, 3, 4, 1 3, 4, 1 4, 1
The finl shortest pth mtrix of the grph shown in the figure 11.18 is S4. We
indicte below how some of the highlighted entries re obtined: S1[4][2] = min
{S0[4][2], S0[4][1] + S0[1][2]} = min {, 6 + 2} = 8 S2[1][3] = min {S1[1][3], S1[
1][2] + S1[2][3]} = min {, 2 + 1} = 3 S3[1][4] = min {S2[1][4], S2[1][3] + S2[3][
4]} = min {, 3 + 2} = 5 S3[4][4] = min {S2[4][4], S2[4][3] + S2[3][4]} = min {, 1
+ 2} = 3 S4[1][1] = min {S3[1][1], S3[1][4] + S3[4][1]} = min {15, 5 + 6} = 11 [
Pth is 4, 1, 2] [Pth is 1, 2, 3] [Pth is 1 3, 4] => [Pth is 1, 2, 3, 4] [Pt
h is 4, 3, 4] [Pth is 1 4, 1] => [Pth is 1, 2, 3, 4, 1]
/*C Code to implement dijkstrs function*/ /* File Nme: Dijkstr.c */ #include<s
tdio.h> #include<conio.h> #define NULL -1 #define temp 0 #define perm 1 void dij
kstr(int, int); int n;

int weight[20][20]; void dijkstr (int s, int d) { int i, k, step, dist[50], pre
d[20], sttus[20], current, dc, min, newdist; for (i = 0; i <= n-1; i++) { dist[
i] = 9999; pred[i] = NULL; sttus[i] = temp; } sttus[s] = perm; dist[s] = 0; cu
rrent = s; step=1; while(current != d) { dc = dist[current]; for(i=0;i<=n-1;i++)
{ if(weight[current][i] != 0 && sttus[i] == temp) { newdist = dc + weight[curr
ent][i]; if(newdist < dist[i]) { dist[i] = newdist; pred[i] = current; } } } min
= 32766; for(i=0;i<=n-1;i++) { if(sttus[i]== temp && min > dist[i]) { min = di
st[i]; k = i; } } current = k; sttus[k] = perm; // SHOW THE INTERMEDIATE STEPS
printf("Step%d",step); printf("\nNode\tDist\tPred\tSttus\n"); for(i=0;i<=n-1;i+
+) { printf("%d\t",i); dist[i] >= 9999?printf("%c\t",224) : printf("%d\t", dist[
i]); pred[i] == -1? printf("NULL\t") : printf("%d\t", pred[i]); sttus[i]==1?pri
ntf("PERM\n"): printf("TEMP\n"); } step++;

getch(); } printf("\n The cost is %d",dist[d]); printf("\n And the pth is\t");
i = d; while(i != s) { printf("%d<-",i); i = pred[i]; } printf("%d",s); } void m
in() { int i, j, s, d; clrscr(); printf("\nEnter the number of nodes in the gr
ph"); scnf("%d",&n); printf("\nEnter the weighted mtrix"); for(i=0;i<=n-1;i++)
for(j=0; j<=n-1; j++) scnf("%d",&weight[i][j]); printf("\nEnter the source nd
destintion node"); scnf("%d%d",&s,&d); dijkstr(s,d); getch(); } /*C code to
implement BFS trversl*/ /* File Nme: BFS.c */ #include<stdio.h> #include<coni
o.h> #define MAX 49 #define WHITE 1 #define BLACK 2 void fnDfs(int); void cqinse
rt(int); int cqdelete(); int cqueueempty(); int n; int djmt[20][20]; int front
= 0, rer = 0, [50]; void fnDfs(int s) // Purpose : This function finds the BF
S trversl of  given grph. // Input : s is the strting node from which we h
ve to strt the trversl. // Output : None. { int i, n1, Color[20]; for(i = 0;
i <= n-1; i++) Color[i] = WHITE; cqinsert(s);

Color[s] = BLACK; while ( !cqueueempty() ) { n1 = cqdelete(); printf("\t %d", n1


); for(i = 0; i<= n -1; i++) { if(djmt[n1][i] != 0 && Color[i] == WHITE) { cqi
nsert(i) ; Color[i] = BLACK; } } } }//End of function void cqinsert(int item) {
if(front == (rer + 1) % MAX) { printf("\n Queue is full"); return; } else { re
r = (rer + 1) % MAX; [rer] = item; } } int cqdelete() { int item; if(front ==
rer) { printf("\n Queue is empty"); return; } else { front = (front + 1) % MAX
; item = [front]; } return item; } int cqueueempty() { int i; i = (front == re
r)? 1 : 0; return i; } void min() { int i, j, s;

clrscr(); printf("\nEnter the number of nodes in the grph"); scnf("%d",&n); pr


intf("\nEnter the djcency mtrix"); for(i=0;i<=n-1;i++) for(j=0; j<=n-1; j++)
scnf("%d",&djmt[i][j]); printf("\nEnter the strting node"); scnf("%d",&s);
fnDfs(s); getch(); } /*C code to implement DFS trversl*/ /* File Nme: DFS.c*/
#include<stdio.h> #include<conio.h> #define MAX 49 #define WHITE 1 #define BLAC
K 2 void fnDfs(int); void push(int); int pop(); int stckempty(); int n; int dj
mt[20][20]; int top = -1, [50]; void fnDfs(int s) // Purpose : This function f
inds the DFS trversl of  given grph. // Input: S is the strting node from w
hich we hve to strt the trversl. // Output : None. { int i, n1, Color[20]; f
or(i = 0; i <= n-1; i++) Color[i] = 1; push(s); Color[s] = 2; while ( !stckempt
y() ) { n1 = pop(); printf("\t %d", n1); Color[n1] = 3; for(i = 0; i<= n -1; i++
) { if(djmt[n1][i] != 0 && Color[i] == 1) { push(i) ; Color[i] = 2; } } } }//E
nd of Function

void push(int item) { if(top == MAX - 1) { printf("\n Stck is full"); return; }


else { top++; [top] = item; } } int pop() { int item; if(top == -1) { printf("
\n Stck is empty"); return; } else { item = [top]; top--; } return item; } int
stckempty() { int i; i = (top == -1)? 1 : 0; return i; } void min() { int i,
j, s; clrscr(); printf("\nEnter the number of nodes in the grph"); scnf("%d",&
n); printf("\nEnter the djcency mtrix"); for(i=0;i<=n-1;i++) for(j=0; j<=n-1;
j++) scnf("%d",&djmt[i][j]); printf("\nEnter the strting node"); scnf("%d"
,&s); fnDfs(s); getch(); } /* C code to implement Wrshlls pth mtrix nd short
est pth function */ /* File Nme : wrshll.c*/

#include<stdio.h> #include<conio.h> void fnWrshllPM(int[20][20],int[20][20], i


nt); void fnWrshllSPM(int[20][20],int[20][20], int); void fnWrshllPM(int A[2
0][20],int P[20][20],int n) // Purpose : This function finds the pth mtrix for
 directed grph G. // Input: n is the totl number of vertices in G. // Output
: None. { int i,j,k; //First copy the contents of djcency mtrix A to pth m
trix P. for(i = 1;i<=n;i++) { for(j=1;j<=n;j++) { P[i][j] = A[i][j]; printf("%d\
t",A[i][j]); } printf("\n"); } //Compute different itertions of P. for(k=1;k<=n
;k++) //k is the itertion number. for(i=1;i<=n;i++) for(j=1;j<=n;j++) P[i][j] =
P[i][j] || (P[i][k] && P[k][j]); }// End of function void fnWrshllSPM(int A[2
0][20],int S[20][20],int n) // Purpose : This function finds the pth mtrix for
 directed grph G. // Input : n is the totl number of vertices in G. // Outpu
t : None. { int i,j,k; //First copy the contents of djcency mtrix A to pth m
trix P. for(i = 1;i<=n;i++) { for(j=1;j<=n;j++) { S[i][j] = A[i][j]; printf("%d
\t",A[i][j]); } printf("\n"); } //Compute different itertions of P. for(k=1;k<=
n;k++) //k is the itertion number. for(i=1;i<=n;i++) for(j=1;j<=n;j++) S[i][j]
= S[i][j]<(S[i][k] + S[k][j])?S[i][j]:S[i][k] + S[k][j]; }// End of function

void min(void) { int i,j,n,iChoice; int P[20][20],A[20][20],S[20][20]; clrscr()


; do { printf("1. Show Wrshlls pth mtrix\n"); printf("2. Find shortst pth
mtrix using Wrshlls function\n"); printf("3. Exit\n"); printf("Enter your ch
oice\n"); scnf("%d",&iChoice); switch(iChoice) { cse 1: printf("Enter number o
f nodes in the grph\n"); scnf("%d",&n); printf("Enter the djcency mtrix\n")
; for(i=1;i<=n;i++) for(j=1;j<=n;j++) scnf("%d",&A[i][j]); fnWrshllPM(A,P,n);
printf("The pth mtrix is\n"); for(i=1;i<=n;i++) { for(j=1;j<=n;j++) printf("%
d\t",P[i][j]); printf("\n"); } brek; cse 2: printf("Enter number of nodes in t
he grph\n"); scnf("%d",&n); printf("Enter the djcency mtrix\n"); for(i=1;i<
=n;i++) for(j=1;j<=n;j++) scnf("%d",&A[i][j]); fnWrshllSPM(A,S,n); printf("Th
e pth mtrix is\n"); for(i=1;i<=n;i++) { for(j=1;j<=n;j++) printf("%d\t",S[i][j
]); printf("\n"); } brek; cse 3: exit(1); defult: printf("Wrong Choice\n"); }
}while(1);

} 11.8 MCQ Chpter 11 1. Adjcency mtrix of  digrph is: () Identity mtrix
(b) Symmetric Mtrix (c) Asymmetric Mtrix (d) None of these 2. Wht is not true
for djcency mtrix of  grph () It is  symmetric mtrix (b) It is  bit m
trix (c) Digonl hs ll zeroes (d) All re true sttements. 3. Bcktrcking is
nother nme for this method of trversl: () Depth-first (b) Bredth first (c
) D-serch (d) none of these. 4. A suitble structure for bredth-first nd dept
h-first trversl of grphs : () Adjcency mtrix (b) Edge listing (c) Adjcenc
y list (d) None of these. S. Which method of trversl uses queue to hold nodes
tht re witing to be processed : () Bredth-first (b) Depth-first (c) D-serc
h (d) None of these. 6. Which method of trversl does not use stck to hold nod
es tht re witing to be processed: () Bredth-first (b) Depth-first (c) D-se
rch (d) None of these. 7. In which cse djcency list representtion of grph i
s not useful () When number of edges is smll (b) When number of vertices re c
hnging due to insertion nd deletion (c) In bredth-first trversl (d) It is u
seful in ll bove cses. 8. Bredth first serch : () scns ll incident edges
before moving to other vertex (b) scns djcent unvisited vertex s soon s po
ssible (c) is sme s bcktrcking (d) None of these. 9. If x is the djcency m
trix of  grph then (i,j)th entry of x represents : () No. of edge sequence o
f length k between i th nd j th vertex (b) No. of pth of length k between i th
nd j th vertex (c) No. of wlks of length k betwen i th nd j th vertex (d) No
ne of these.

10. In n djcency mtrix prllel edges re given by : () Similr columns (b)
Similr rows (c) Not representble (d) None of these. 11. A vertex with degree
one in.  grph is clled : () Lef (b) Pendnt vertex (c) End vertex (d) None
of these. 12. A digrph in which ,outdegree is sme s indegree is clled : ()
blnced (b) symmetric (c) regulr (d) None of these. 13. Grph structure is v
ilble in () C (b) C++ (c) Pscl (d) None of these 14. Depth first Trversl o
f  grph produces: ()  spnning forest of the grph (b)  spnning tree of th
e grph (c)  miniml spnning tree (d) None of the bove. 15. Suppose tht n
undirected grph G is represented by n djcency mtrix A. Let B denote the mt
rix A x A x A x A x A. Which of the following is true if n element B (i,j) is n
on. zero? () Vertex j cn be reched from vertex i in exctly 5 steps. (b) Vert
ex i cn be reched from vertex j in exctly 5 steps. (c) Vertex j cnnot be re
ched from vertex i. (d) None of the bove. 16. The time complexity of Depth Firs
t Serch lgorithm to trverse  grph of n vertices nd e edges is : () O(n) i
f the grph is represented by djcency mtrix (b) O (e) if the grph is represe
nted by djcency list (c) O (e) if the grph is represented by djcency mtrix
(d) None of the bove. 17. A grph is plnr if nd only if, () it does not co
ntin subgrphs homomorphic to Ks nd K3.3. (b) it does not contin subgrphs is
omorphic to Ks or K3,3 (c) it does not contin subgrphs isomorphic to Ks nd K
3,3 (d) it does not contin subgrph (GATE-1990)
18. Kruskls lgorithm for finding  minimum spnning tree of  weighted grph
G with n vertices nd m edges hs the time complexity of : (GATE-1991) () O(n2)
(b) O(m n) (c) O(m + n) (d) O(m log n) 2 (e) O(m ).

19. Consider  simple connected grph G with n vertices nd n edges(n > 2). Then
, which of the following sttements re true? (More thn I choice my be correct
) (GATE-1993) () G hs no cycles (b) The grph obtined by removing ny edge fr
om G is not connected (c) G hs t lest one cycle (d) The grph obtined by rem
oving ny two edges from G is not connected. (e) None of the bove. 20. Which of
the following sttements is flse? (GATE-1994)
() Optiml binry serch tree construction cn be performed efficiently using d
ynmic progrmming. (b) Bredth first serch cn not be used to find component o
f  grph. (c) Give the prefix nd postfix wlks over 3 binry tree, the binry
tree cn not be uniquely constructed. (d) Depth first serch cn be used to find
connected components of  grph. 21.The number of distinct simple grphs with u
p to 3 nodes is : () 15 (b) 10 (c) 7 (d) 9. 22. The minimum number of edges in
 connected cyclic grph on n vertices is : () n - 1 (b) n (c) n + I (d) None o
f the bove. 23. Let G be  grph with 100 vertices numbered 1 to 100. Two verti
ces i nd j re djcent iff |i j| = 8 or |i j| = 12. The number of connected co
mponents in G is : (GATE-1997) () 8 (b) 4 (c) 12 (d) 25 24. The number of rtic
ultion points of the following grph is : () 0 (b) 1 (c) 2 (d) 3. 25. Let G be
n undirected grph. Consider  depth-first trversl of G, nd let T be the re
sulting depth-first serch tree. Let u be  vertex in G nd let v be the first n
ew (unvisited vertex) visited fter visiting u in the trversl. Which of the fo
llowing sttements is lwys true? (GATE-2000) () {u, v} must be n edge in G.
nd u is  descendnt of v in T (b) {u, v} must be n edge in G, nd v is  desc
endnt of u in T (c) If {u, v} is not n edge in G then It is  lef in T (d) If
{u, v}is not n edge in G then u nd v must hve the sme prent in T. 26. The
most pproprite mtching for the following pirs : X: depth-first serch 1: he
p Y: bredth-first serch 2: queue Z: sorting 3: stck () X-I, Y - 2, Z - 3 (b)
X - 3, Y - 1, Z - 2 (c) X - 3, y,- 2, Z - 1 (d) X - 2, Y - 3, Z - 1. (GATE-1994
)

27. Let G be n undirected connected grph with distinct edge weights. Let emx
be the edge with mximum weight nd emin the edge with minimum weight. Which of
the following sttements is flse? (GATE-2000) () Every minimum spnning tree,
of G must contin emin (b) If emx is in  minimum spnning tree, then its remov
l must disconnect G (c) No minimum spnning tree contins emx (d) G hs  uniq
ue minimum spnning tree. 28. Consider n undirected un-weighted grph G. Let 
bredth first trversl be done strting from  node r. Let d (r, u) nd d (r, v
) be the lengths of shortest pths from r to u nd v respectively in G. If u is
visited before v during the bredth first trversl, which of the following stt
ement is correct? (GATE-2001) () d (r, u) < d (r, v) (b) d (r, u) > d (r, v) (c
) d (r, u) d (r, v) (d) None of these. 29. Consider the grph below. The third r
ow in the trnsitive closure of the bove grph is 1 2 3
() 1,1,1 (c) 1,0,0
(b) 1,1,0 (d) 0,1,1
30. The eccentricity of node lbeled 5 in the grph below 1
2
3
4
5 () 6 (c) 8 (b) 7 (d) 5
31. The center of the grph in previous question is the node lbeled () 1 (b) 2
(c) 3 (d) 4

32. Consider the grph below. Wht should be the lbels of nodes mrked 1 nd 2
if the bredth first trversl yields the list A B C D E?
A
B 1
2 () D nd E (c) unpredictble
C (b) E nd D (d) none of the bove
33. Consider the grph below. Which of the following is  vlid strong component
? A B
D () , c, d (c) b, c, d (b) , b, d (d) , b, c
C
34. Consider the undirected weighted grph below. The minimum cost spnning tree
for this grph hs the cost
() 18
(b) 20
(c) 24
(d) 22
35. The minimum number of edges in  connected cyclic grph on n vertices is ()
n-l (b) n (c) n+l (d) none of the bove 36. The minimum number of colors needed
to color  grph hving n (>3) vertices nd 2 edges is () 4 (b) 3 (c) 2 (d) 1
37. The mximum degree of ny vertex in  simple grph with n vertices is () n
(b) n-l (c) n+l (d) 2n-l 38. The number of edges in  regulr grph of degree d
nd n vertices is .

() mximum of n, d
(b) n+d
(c) nd
(d) nd/2
Solutions:
1. d 16. d 31. d 2. d 17. b 32.  3.  18. c 33. d 4. c 19. c 34. b 5.  20. b 3
5. b 6.  21.  36. c 7. d 22. b 37. b 8.  23.  38. d 9. c 24. d 10. c 25. b 1
1. b 26. c 12. d 27. c 13. d 28. c 14. b 29. d 15. b 30. b
11. Exercise Chpter 11
1. Wht is  grph? Differentite between (i) Undirected nd directed grph (ii)
cycle nd Hmiltonin cycle 2. How cn you represent  grph. Discuss the two d
ifferent wys of representtion. 3. Write lgorithms for (i) serching for  pr
ticulr node in  grph (ii) serching for  prticulr edge in  grph (iii) in
sert  new node in  grph (iv) insert  new edge in  grph (v) delete  node f
rom  grph (vi) delete  edge from  grph 4. Compre BFS nd DFS. Write lgori
thms nd compute time complexity for both BFS nd DFS to serch  grph for  no
de 5. How cn you find shortest pth between two nodes in  grph by Dijkstrs l
gorithm, explin by suitble digrms nd lgorithm. 6. Describe Wrshlls lgori
thm to find shortest pth between two nodes in  grph nd explin it by suitbl
e digrm nd lgorithm.

Chpter 12 SORTING
12.1 Definition
Sorting cn be defined s rrnging n unordered set of comprble dt items in
order. We will concentrte on sorting dt tht is stored in n rry. Let P be
n rry of n elements P1 P2 P3..Pn in memory. Sorting P mens rrnging the con
tents of P in either incresing or decresing order i.e. P1 P2 P3 P4 P5 .. Pn in
sing order P1 P2 P3 P4 P5 .. Pn decresing order In this chpter we will discus
bout different sorting techniques to sort  set of dt in incresing order.
12.2 The fmily of sorting methods
There re two min sorting themes: ddress-bsed sorting nd comprison-bsed so
rting. Sorting
Comprison-bsed Sorting
Address-bsed Sorting
Proxmp Sort
Rdix Sort
Bubble Sort
Insertion Sort
Selection Sort
Merge Sort
Quick Sort
Hep Sort
Shell Sort
12.3 Bubble Sort
Bubble sort cn be defined s  comprison bsed sort by checking ech djcent
pir of items in  list in turn, swpping the items if necessry, nd repeting
the pss through the list until no swps re done. Suppose the list of numbers P
[1], P[2], , P[n] is in memory. The bubble sort lgorithm works s follows: Iterti
on 1: Compre P[1] with P[2] nd rrnge them in scending order such tht P[1]
< P[2]. Then compre P[2] with P[3] nd rrnge such tht P[2] < P[3] nd so on.
Finlly we rrnge P[n-1] nd P[n]. This step involves n-1 comprisons. During
which the lrgest element bubbles up to its finl position. Tht is the reson i
t is clled s bubble sort. Itertion 2: Repet step 1 with one less comprison.
In this cse the second lrgest element will occupy its proper position i.e. we
stop fter we compre nd finlly rerrnge P[n-2] nd P[n-1]. Itertion n-1: Fi
nlly we compre P[1] with P[2] nd rrnge them in such  wy tht P[1] < P[2].
Exmple: P[0] P[1] P[2] P[3] P[4] P[5] P[6] P[7] 33 86 57 92 37 48 25 12

During the first pss, the following comprisons re mde: P[0] with P[1] P[1] w
ith P[2] P[2] with P[3] P[3] with P[4] P[4] with P[5] P[5] with P[6] P[6] with P
[7] 33 with 86 86 with 57 86 with 92 92 with 37 92 with 48 92 with 25 92 with 12
33 < 86 hence no interchnge 86 > 57 hence interchnge 86 < 92 hence no interch
nge 92 > 37 hence interchnge 92 > 48 hence interchnge 92 > 25 hence interchn
ge 92 > 12 hence interchnge 12 92
Thus t the end of first pss rry will look like: 33 57 86 37 48 The complete
set of itertion is depicted below: Itertion originl Itertion=1 Itertion=2 I
tertion=3 Itertion=4 Itertion=5 Itertion=6 Itertion=7 0 3 3 3 3 3 3 3 3 3 3
3 3 2 5 1 2 1 8 6 5 7 5 7 3 7 3 7 2 5 1 2 2 5
25
Arry elements 2 3 4 5 5 9 3 4 7 2 7 8 8 3 4 2 6 7 8 5 3 4 2 1 7 8 5 2 4 2 1 5 8
5 2 7 2 1 4 5 5 2 8 7 1 3 4 5 2 7 8 7 3 3 4 5 3 7 8 7 3 3 4 5 3 7 8 7
6 2 5 1 2 8 6 8 6 8 6 8 6 8 6 8 6
7 12 92 92 92 92 92 92 92
For the implementtion of lgorithm, we hve tken  Boolen vrible swp to in
dicte whether the rry is sorted or not nd this vrible improves the best c
se time complexity of lgorithm from O(n2) to O(n). The initil vlue of swp is
TRUE which mens initilly the rry is not sorted. Before strting of ech ite
rtion, set the vlue of swp to FALSE. During execution of itertion, if t le
st one swp opertion is performed between djcent pir then set swp to true t
o indicte the rry is not sorted till now nd go for next itertion. Algorithm
12.1 1. Algorithm fnBubbleSort(P[],n) 2. //Purpose : This lgorithm sorts  set
of elements using the concept of bubble sort in scending order. 3. //Input : P
[0.n-1] is n rry of n elements. 4. //Output : None. 5. // Comments: Here swp
is  Boolen vrible. After ech itertion, TRUE vlue of swp indictes t le
st one interchnge hs tken plce nd FALSE vlue of swp signifies the rry i
s now sorted. 6. { 7. swp = TRUE; 8. for(Itertion = 1; Itertion < n && swp =
= TRUE; Itertion++) 9. { 10. swp = FALSE; //Set swp to FALSE before strting
of ech itertion.

11. for(j = 0; j < n- Itertion; j++) 12. { 13. if(P[j] > P[j+1]) 14. { 15. swp
= TRUE; 16. temp = P[j]; 17. P[j] = P[j+1]; 18. P[j+1] = temp; 19. } 20. } 21.
} 22. } // End of lgorithm Time complexity: 1. Best cse: The rry is in sorte
d order. Hence swp will remin flse fter first itertion nd so the process e
nds. Therefore the totl number of comprisons mde will be decided by the inner
loop for the first itertion which is n-1. Tb(n) = O(n) Averge cse: On the v
erge the comprison mde in the inner loop is (k-1)/2. f(n) = (n-1)/2 + (n-2)/2
+ .. + 1/2 = n(n-1)/4 Therefore, T(n) = O(n2) 3. Worst cse: The rry P[] is in
reverse order. So for the first itertion n-1 comprisons re needed, for the se
cond itertion n-2 comprisons re needed nd so on. Hence in the worst cse f(n
) = (n-1) + (n-2) + + 1 = n(n-1)/2 Therefore, Tw(n) = O(n2) Spce Complexity: The sp
ce-complexity is O(1), just  few sclr vribles. Here we do not count the si
ze of the rry being sorted becuse tht is given, not creted specificlly for
this lgorithm.

12.4 Insertion Sort


Suppose n rry P[] with n elements P[1], P[2], , P[n] is in memory. The insertio
n sort lgorithm scns P from P[1] to P[n], inserting ech element P[k] into its
proper position in the previously sorted sub-rry P[1], P[2], .., P[k-1]. Iterti
on 1:P[1] by itself is trivilly sorted. Itertion 2:P[2] is inserted either bef
ore or fter P[1] so tht P[1] nd P[2] is sorted. .
., P[n-1] so tht P[1], P[2], ., P[n] is sorted. Itertion originl Itertion=1 It
ertion=2 Itertion=3 temp=86. temp > P[0], No interchnge. temp=57. temp<P[1].
So insert temp t P[1]. temp=92. temp>P[2], No interchnge Comments 0 3 3 3 3 3
3 3 1 8 6 8 6 5 7 5 Arry elements 2 3 4 5 5 92 37 4 7 8 5 92 37 4 7 8 8 92 37 4
6 8 8 92 37 4 6 2 5 2 5 2 5 2 7 12 12 12 12

Itertion=4 Itertion=5 Itertion=6 Itertion=7


temp=37. temp<P[3]<P[2]<P[1]. So insert temp t P[1] temp=48. temp<P[4]<P[3]<P[2
]. So insert temp t P[2] temp=25. temp<P[5]<P[4]<<P[0]. So insert temp t P[0].
temp=12. temp<P[6]<P[5]<<P[0]. So insert temp t P[0].
3 3 3 3 3 2 5 1 2
7 3 7 3 7 3 3 2 5
6 5 7 4 8 3 7 3 3
86 57 48 37
92 86 57 48
8 4 8 9 2 8 6 5 7
5 2 5 2 5 9 2 8 6
12 12 12 92
Algorithm 12.2 1. Algorithm fnInsertionSort(P[], n) 2. //Purpose : This lgorith
m sorts  set of elements using the concept of insertion sort. 3. //Input : P[0.n
-1] is n rry of n elements which is to be sorted in scending order. 4. //Out
put : None. 5. { 6. for(Itertion = 1; Itertion < n; Itertion++) 7. { 8. temp
= P[Itertion]; 9. for(j = Itertion-1; j >= 0 && temp < P[j]; j--) 10. P[j+1] =
P[j]; 11. P[j+1] = temp; 12. } 13. }//End of lgorithm Time complexity: 1. Best
cse: The rry is in sorted order then only one comprison will be mde in the
inner loop. Therefore the totl number of comprisons mde will be decided by t
he outer loop which is n-1. f(n) = (n-1) X 1 Tb(n) = O(n) 2. Averge cse: If we
were given  rndom permuttion, the chnces of the kth insertion requiring 0,
1, 2.k-1 comprisons re equl, nd hence 1/k. The expected number of comprisons
is for the kth insertion is: k

(i-1)/k = k(k-1)/2k = (k-1)/2 i=1 Therefore on the verge, number of comprison


s in the inner loop is (k-1)/2. Hence, f(n) = 1/2 + 2/2 + ..+ (n-1)/2 = n(n-1)/4 There
fore, T(n) = O(n2)
3. Worst cse: The rry is in reverse order. So for the first itertion 1 comp
rison is needed in the inner loop, for the second itertion 2 comprisons re ne
eded nd so on. Hence in the worst cse f(n) = 1 + 2 +.. + (n-1) = n(n-1)/2 Therefore
w(n) = O(n2) Spce Complexity:

The spce-complexity is O(1). Here lso we do not count the size of the rry be
ing sorted becuse tht is given, not creted specificlly for this lgorithm.

12.5 Selection Sort


Find the lest vlue in the rry, swp it into the leftmost component (where it
belongs), nd then forget the leftmost component. Do this repetedly. Suppose 
n rry P[] with n elements P[0], P[1], , P[n-1] is in memory. Itertion 0: Find t
he loction loc of the smllest element in the list nd then interchnge P[loc]
nd P[0] if loc 0. Itertion 1: Find the loction loc of the smllest element in
the sub list of n-1 elements (P[1], P[2],.., P[n-1]) nd then interchnge P[loc]
nd P[1] if loc 1 . Then P[0] nd P[1] is sorted. Itertion 2: Find the loctio
n loc of the smllest element in the sub list of n-2 elements (P[2], P[3],.., P[n
-1]) nd then interchnge P[loc] nd P[2] if loc 2. Then P[0], P[1] nd P[2] is
sorted. ... Itertion n-2: Find the loction l
then interchnge P[loc] nd P[n-2] if loc n-2 . Then P[0], P[1],.. P[n-1] is sor
ted. Itertio n (k) originl k=0 k=1 k=2 k=3 k=4 k=5 k=6 Comments 0 3 3 1 2 1 2
1 2 1 2 1 2 1 2 1 2 1 8 6 8 6 2 5 2 5 2 5 2 5 2 5 2 5 Arry elements 2 3 4 5 5 7
5 7 5 7 3 3 3 3 3 3 3 3 3 3 9 2 9 2 9 2 9 2 3 7 3 7 3 7 3 7 3 7 3 7 3 7 3 7 9 2
4 8 4 8 4 8 4 8 4 8 4 8 4 8 4 8 9 2 5 7 5 7 6 2 5 2 5 8 6 8 6 8 6 8 6 8 6 8 6 7
12 33 33 57 57 57 92 92
Here loc = 7. loc k Interchnge P[loc] nd P[k]. Here loc = 6. loc k Interchnge
P[loc] nd P[k]. Here loc = 7. loc k Interchnge P[loc] nd P[k]. Here loc = 4.
loc k Interchnge P[loc] nd P[k]. Here loc = 5. loc k Interchnge P[loc] nd P
[k]. Here loc = 7. loc k Interchnge P[loc] nd P[k]. Here loc = 6. As loc = k,
no interchnge.
Algorithm 12.3 1. Algorithm fnSelectionSort(P[], n) 2. //Purpose : This lgorith
m sorts  set of elements using the concept of selection sort. 3. //Input : P[0.n
-1] is n rry of n elements which is to be sorted in scending order. 4. //Out
put : None. 5. { 6. for(k = 0; k < n-1; k++) 7. { 8. loc= k; //loc keeps the tr
ck of index of the minimum element in the list. 9. for(j = k+1; j < n; j++) 10.
if(P[j] < P[loc]) 11. loc = j;

12. if(loc != k) 13. { 14. temp = P[k]; 15. P[k] = P[loc]; 16. P[loc] = temp; 17
. } 18. } 19. }//End of lgorithm Time complexity: 1. Best cse: The best occurs
when the list is in desired order. But unfortuntely to get the minimum element
from  set of n-k elements n-k comprisons re required. So for the first iter
tion we hve to go through n-1 elements nd hence n-1 comprisons. Similrly for
the second itertion n-2 comprisons re needed nd so on. Thus, f(n) = (n-1) +
(n-2) + + 1 = n(n-1)/2 Therefore, T(n) = O(n2) 2. Averge cse: Here lso in first
itertion n-1 comprisons re required, in second itertion n-2 comprisons nd
so on. f(n) = (n-1) + (n-2) + + 1 = n(n-1)/2 Therefore, T(n) = O(n2) 3. Worst cse:
Like the best cse nd verge cse here lso, f(n) = (n-1) + (n-2) + + 1 = n(n-1)/2
T(n) = O(n2)
Therefore,
Spce Complexity: The spce-complexity is O(1). Here lso we do not count the si
ze of the rry being sorted becuse tht is given, not creted specificlly for
this lgorithm.
12.6 Merge Sort
Divide nd Conquer Sorting: In terms or lgorithms, this method hs three distin
ct steps: Divide: If the input size is too lrge to del with in  strightforw
rd mnner, divide the dt into two or more disjoint subsets. Recur: Use divide
nd conquer to solve the sub problems ssocited with the dt subsets. Conquer:
Tke the solutions to the sub problems nd merge these solutions into  solution
for the originl problem. Algorithm 12.4 1. Algorithm fnSort(list) 2. { 3. if(th
e list hs length > 1) 4. { 5. Prtition the list into two lists First hlf nd
Second hlf 6. fnSort(First hlf) 7. fnSort(Second hlf) 8. fnCombine(First hlf
nd Second hlf) 9. }

10. }//End of lgorithm Divide: If S hs t les two elements (nothing needs to
be done if S hs zero or one elements), remove ll the elements from S nd put t
hem into two sequences, S1 nd S2, ech contining bout hlf of the elements of
S. (i.e. S1 contins the first n/2 elements nd S2 contins the remining
n/2 ele
ments. Recur: Recursive sort sequences S1 nd S2. Conquer: Put bck the elements
into S by merging the sorted sequences S1 nd S2 into  unique sorted sequence.
Algorithm 12.5 1. Algorithm fnMsort(low, high) 2. //Purpose : This lgorithm so
rts  set of elements using the concept of merge sort. 3. //Input : P[low.high] i
s n rry of (high-low+1) elements which is to be sorted in scending order. lo
w is the lower index nd high is the upper index of the rry. 4. //Output : Non
e. 5. { 6. if(low < high) 7. { 8. mid = (lo + high)/2; 9. fnMsort(lo, mid); 10.
fnMsort(mid+1, high); 11. fnMerge(lo, mid, high); 12. } 13. }//End of algorithm
Algorithm 12.6 1. Algorithm fnMerge(lo, mid, high) 2. //Purpose : This algorit
hm merges to sorted sub arrays. 3. //Input : The loer index and upper index of
to sub arrays are lo to mid and mid+1 to high respectively. 4. //Output : Non
e. 5. { 6. h = lo; 7. k = lo; 8. j = mid + 1; 9. hile(h <= mid && j <= high)
10. { 11. if(P[h] <= P[j]) 12. { 13. B[k] = P[h]; 14. h = h + 1; 15. } 16. else
17. { 18. B[k] = P[j]; 19. j = j+1; 20. } 21. k = k + 1; 22. } 23. if(h < mid) 2
4. {

25. for(i = h ; i <= mid; i++) 26. { 27. B[k] = P[i]; 28. k = k + 1; 29. } 30. }
31. else 32. { 33. for(i = j; i <= high; i++) 34. { 35. B[k] = P[i]; 36. k = k+
1; 37. } 38. } 39. for(i = lo; i <= high; i++) 40. P[i] = B[i]; 41. }//End of a
lgorithm Consider the folloing array of 10 elements hich is to be sorted using
merge sortP[0] P[1] P[2] P[3] P[4] P[5] P[6] P[7] P[8] P[9] 33 86 57 92 37 48 2
5 12 50 76 The tree of calls of merge sort (0, 9) is depicted in the figure 12.1
.
33 fnMsort(0,0) fnMsort(0,1) fnMsort(0,2) 57 fnMsort(2,2) fnMsort(0,4) 92 fnMsor
t(3,3) fnMsort(3,4) 86 fnMsort(1,1)
37 fnMsort(4,4) 48
fnMsort(0,9) fnMsort(5,6)
fnMsort(5,5)

25 fnMsort(5,7) 12 fnMsort(7,7) fnMsort(5,9) fnMsort(6,6)


50 fnMsort(8,8) fnMsort(8,9) 76 fnMsort(9,9)
Figure 12.1: A tree of call of merge sort
The tree of calls of merging is shon in figure 12.2:33 86 fnMerge(0,1,1) 33 57
86 fnMerge(0,2,2) 33 37 57 86 92 fnMerge(0,3,4) 37 92 fnMerge(3,4,4) 25 48 fnMer
ge(5,6,6) 12 25 48 fnMerge(5,7,7) 12 25 48 50 76 50 76 fnMerge(8,9,9) Figure 12.
2: A tree of call of merging node (a, b, c) represents the merging of the arrays
(a, b-1) and (b, c). e.g. (0, 5, 9) means merging of (0, 5) and (6, 9). fnMerge
(5,8,9) 12 25 33 37 48 50 57 76 86 92 fnMerge(0,5,9)

Example of merging: Merging can be performed on to sorted sub arrays. Here lo
= 0 mid = 5 high = 9 and k = 0 Iteratio n Pass = 1 Pass = 2 Pass = 3 Pass = 4 33
Pass = 5 33 Pass = 6 33 Pass = 7 33 Pass = 8 33 37 57 B[0 ] 12 37 37 37 P[0] h=
0 33 h=0 33 h=0 33 P[1] 37 37 37 h=1 37 P[2] 57 57 57 57 h=2 57 h=2 57 h=2 57 Ar
ray elements P[3] P[4] P[5] P[6] j=5 86 92 12 25 j=6 86 92 12 25 86 86 86 86 86
h=3 86 B[1 ] 25 B[2 ] 33 92 92 92 92 92 92 B[3 ] 37 12 12 12 12 12 12 B[4 ] 48 2
5 25 25 25 25 25 B[5 ] 50 Comments P[7] 48 48 j=7 48 j=7 48 j=7 48 48 48 48 B[6
] 57 P[8] 50 50 50 50 50 j=8 50 50 50 B[7 ] 76 P[9] 76 76 76 76 76 76 j=9 76 j=9
76 B[8 ] P[j] < P[h]. So, B[k] = P[j] j = j + 1 = 6, k = k + 1 = 1 P[j] < P[h].
So, B[k] = P[j] j = j + 1 = 7, k = k + 1 = 2 P[h] < P[j]. So, B[k] = P[h] h = h
+ 1 = 1, k = k + 1 = 3 P[h] < P[j]. So, B[k] = P[h] h = h + 1 = 2, k = k + 1 =
4 P[j] < P[h]. So, B[k] = P[j] j = j + 1 = 8, k = k + 1 = 5 P[j] < P[h]. So, B[k
] = P[j] j = j + 1 = 9, k = k + 1 = 6 P[h] < P[j]. So, B[k] = P[h] h = h + 1 = 3
, k = k + 1 = 7 P[j] < P[h]. So, B[k] = P[j] j = j + 1 = 10, k = k + 1 = 8
B[9]
No j(value
oop. And as
B[]. B[0 ]
8 ] 86 B[9]

= 10) > high(value = 9), so program control goes outside the hile l
h(value =3) < mid(value = 5), P[h,.., mid] ill be copied into array
12 B[1 ] 25 B[2 ] 33 B[3 ] 37 B[4 ] 48 B[5 ] 50 B[6 ] 57 B[7 ] 76 B[
92

Finally the contents of array B[] ill be copied into array P[]. P[0] P[1] P[2]
P[3] P[4] P[5] P[6] P[7] P[8] P[9] 12 25 33 37 48 50 57 76 86 92 Time complexity
: Best case, Average case and Worst case: In the merge sort, the call of merge s
ort and merging does not depend on the order of the elements in the array. So th
e best case, average case and orst case time complexity are same in case of mer
ge sort. No let total T(n) time is needed to sort the array. That is the functi
on fnMsort(lo,high) takes T(n) time here n is the total number of elements in
the array. So the statement fnMsort(lo,mid) takes T(n/2) time to finish its exe
cution as here e are dividing the array into to equal halves each having n/2 e
lements. Similarly fnMsort(mid+1,high) also needs T(n/2) time. Again the stateme
nt fnMerge(lo,mid,high) for merge operation takes O(n) time. Hence the recurren
ce relation to compute the time complexity for the merge sort is: T(n) = 2T(n/2)
+ c*n c = some positive constant

= 2[2T(n/22) + c*n/2] + c*n = 22T(n/22) + 2c*n = = = 2kT(n/2k) + kcn


So, k = logn] = n + cnlogn [ for n = 1, T(1) = 1] Therefore, T(n) = O(n logn) Sp
ace complexity: The space complexity of the recursive algorithm for merge sort i
s O(n+logn), n for the extra array B[] and log(n) for the stack space. Character
istics: 1. It is based on divide and conquer method. 2. Algorithms complexity il
l remain O(n logn) in the best, average and orst case. 3. To execute the algori
thm, extra space required is equal to the number of elements in the array i.e. s
pace complexity = O(n). 4. Time complexity of algorithm merge is O(n) here n =
number of records being merged.

12.7 Quick Sort


It follos the Divide and Conquer method. It as devised by C.A.R. Hoare in 1962
. Here the division into sub files is made such that the sorted sub files dont la
ter to be merged. This is accomplished by rearranging the elements P[0:n-1] such
that P[i] P[j] for all i, 0 i m and all j, m + 1 j n 1 for some m, 0 m n 1.
the elements in P[0:m-1] and P[m + 1 : n-1] may be independently sorted. The re
arrangement of the elements is done by picking some element of P[], say t = P[s]
, and then reordering the other elements, so that all elements appearing before
t in P[0:n-1] are less than or equal to t and all elements appearing after t are
greater than or equal to t. This rearranging is referred to as partitioning. Ex
ample: Given array is:P[0] P[1] P[2] P[3] P[4] P[5] P[6] 33 37 57 86 92 27 25 It
eratio n Initial Step = 1 33 Step = 2 33 Step = 3 33 Step = 4 27 25 33 86 92 57
Sub list 1 P[0] P[1] 37 + Now the two sub lists re: 25 25 P[0] I=0 33 P[1] 37 I=
1 37 P[2] 57 57 I=2 57 J=2 27 Arry elements P[3] P[4] P[5] 86 86 86 I=3 86 92 9
2 92 92 27 12 J=5 27 57 Comments P[6] 25 J=6 25 37 37 P[7] J=7 + + 33 + 33 + 33 V 33
33 I<J interchnge P[I] nd P[J] I<J interchnge P[I] nd P[J] I>J interchnge
V nd P[J] Now 33 hs got its finl position

27
25
Sub list 2 P[3] P[4] P[5] P[6] 86 92 57 37 The sme process will be continued fo
r sub lists nd t the end ll the elements of list will be t its proper positi
on. Algorithm 12.7 1. Algorithm fnQsort(p, q) 2. //Purpose : This lgorithm sort
s n rry using quick sort. 3. //Input : The lower index nd upper index of the
rry re p nd q respectively. 4. //Output : None. 5. { 6. if(p < q) 7. { 8. j
= fnPrtition(p, q+1); 9. fnQsort(p, j-1); 10. fnQsort(j+1, q); 11. } 12. }//En
d of lgorithm Algorithm 12.8 1. Algorithm fnPrtition(m, n) 2. //Purpose : This
lgorithm finds the proper plce of the pivot element. 3. //Input : The lower i
ndex nd upper index of the rry re m nd n respectively. 4. //Output : None.
5. { 6. P[n] = ; //Assign  lrge vlue t the end of the rry. 7. v = P[m]; //
v is the pivot element. 8. i = m; 9. j = n; 10. do 11. { 12. do 13. { 14. i = i+
1; 15. } while(P[i] < v); 16. do 17. { 18. j = j-1; 19. }while(P[j] > v); 20. if
(i < j) 21. fnInterchnge (i, j); 22. }while(i < j); 23. P[m] = P[j]; 24. P[j] =
v; 25. return j; //j is the ctul position of the pivot element in the sorted
rry. 26. }//End of lgorithm Algorithm 12.9

1. Algorithm fnInterchnge(i, j) 2. { 3. temp = P[i]; 4. P[i] = P[j]; 5. P[j] =


temp; 6. }//End of lgorithm Time complexity: The time complexity of the bove 
lgorithm is given by :T(n) = P(n) + T(j LB) + T(UB j) where P(n) = time to prti
tion the given sub file. T(j LB) = time to sort left sub file. T(UB j) = time to
sort right sub file. 1. Best cse: The best cse occurs when the file is lwys
prtitioned in hlf i.e. j = (LB + UB)/2 Then the analysis becomes T(n) = P(n) +
2T(n/2) = cn + 2[2T(n/22) + c(n/2)] = 2cn + 22T(n/22) = = = kcn + 2kT
k = n. So, k = logn] = cnlogn + n [for n = 1, T(1) = 1] Therefore, T(n) = O(n lo
gn) 2. Average case: For the average case analysis, e make the folloing assump
tions: The n elements to be sorted are distinct. The partitioning element is cho
sen using a random selection process. If RANDOM(i, j) is a function that generat
es a random integer in the interval [i, j], then the selection element is chosen
by replacing the statements v = P[m] and i = m by i = RANDOM(LB, UB) and v = P[
i]. Since the partitioning element v has an equal probability of being the ith s
mallest element 1 i (UB LB + 1) in P[LB, UB], hence the to sub files remaining
to be sorted ill be P[LB, j] and P[j + 1, UB] ith probability 1/(UB LB + 1); L
B j UB. Form this e obtain the recurrence:T(n) = (n + 1) + 1/n (k = 1..n)[T(k 1
) + T(n k)] --------------------(1) Where n + 1 = number of comparisons required
to partition the hole list by first time. Multiplying both sides of equation (
1) by n e get nT(n) = n(n + 1) + 2[ T(0) + T(1) + + T(n 1)] --------------------(2
) Replacing n by n-1 in equation (2) e get (n 1)T(n 1) = (n 1)n + 2[T(0) + T(1)
+ + T(n 2)] ---------(3) Subtracting equation (3) from equation (2) e get nT(n) (
n 1)T(n 1) = 2n + 2T(n 1) or, nT(n) = 2n + (n + 1)T(n 1) or, T(n)/(n + 1) = 2/(n
+ 1) + T(n 1)/n -------------------------------- (4) Equation (4) is the requir
ed recurrence relation in average case. T(n)/(n + 1) = T(n 2)/(n 1) + 2/n + 2/(n
+ 1) = T(n 3)/(n 2) + 2/(n 1) + 2/n + 2/(n + 1) = =
0, T(0) = 0]

n+1 2 1 Therefore, T(n) 2(n + 1) log(n + 1) Hence, T(n) = O(n logn) 3. Worst case
: The orst case occurs hen, at each invocation of the routine, the current fil
e is partitioned into to sub files ith one of them being empty(j = LB or j = U
B) or key element being smallest or largest one. Then the analysis becomes T(n)
= P(n) + T(0) + T(n 1) = cn + T(n 1) [ for n = 0, T(0) = 0] = cn + c(n 1) + T(n
2) = cn + c(n 1) + c(n 2) + T(n 3) = = = c(k = 1.. n) K + T(0)
dx/x = 2[log(n + 1) log1]
Space complexity: The space complexity of the recursive algorithm for quick sort
is O(logn), log(n) for the stack space.
12.8 Heap Sort
Algorithm 12.10 1. Algorithm fnHeap_sort(length) 2. // Purpose : This algorithm
sorts a set of element in ascending order using heap sort. 3. // Input : The ele
ments are stored in the array P[1length]. 4. // Output : None. 5. { 6. heap_size
= length; 7. fnBuild_max_heap(length); 8. for(i = length; i>=2; i--) 9. { 10. in
terchange(1, i); 11. heap_size--; 12. max_heapify(1, heap_size); 13. } 14. }//En
d of algorithm Algorithm 12.11 1. Algorithm fnBuild_max_heap(length) 2. //Purpos
e : This algorithm builds the max heap ith the given data. 3. // Input : length
of the array. 4. //Output : None. 5. { 6. for(i = length/2; i >=1; i--)

7. max_heapify(i, length); 8. }//End of algorithm Algorithm 12.12 1. Algorithm m


ax_heapify(i, length) 2. // Purpose : This algorithm adjust the heap ith size l
ength in respect to the array position i. 3. // Input : i array position and len
gth is the size. 4. //Output : None. 5. { 6. l = left(i); // index of the left c
hild of i. 7. r = right(i); // index of the right child of i. 8. if(l heap_size)
9. { 10. if(l <= heap_size && P[l] >= P[i]) 11. largest = l; 12. else 13. large
st = i; 14. if(r <= heap_size && P[r] > P[largest]) 15. largest = r; 16. if(larg
est != i) 17. { 18. interchange(i, largest); 19. max_heapify(largest, heap_size)
; 20. } 21. } 22. }//End of Algorithm Algorithm 12.13 1. Algorithm left( i) 2. /
/ This algorithm calculates the index of the left child of i 3. { 4. return(2*i)
; 5. }//End of algorithm Algorithm 12.14 1. Algorithm right( i) 2. // This algor
ithm calculates the index of the right child of i. 3. { 4. return(2*i+1); 5. }//
End of Algorithm Example: Consider the folloing arrayP[1] P[2] P[3] P[4] P[5] P
[6] P[7] P[8] P[9] 54 56 46 29 72 65 32 64 48 Steps to create the heap: 1
5 6 5 4
4 6

2 i=4 8 5 9 6
3 7
2 9
7 2
6 5
3 2
6 4
4 8
Step 1:-max_heapify(4, 9) max_heapify(8, 9) 1 2 4 8
5 6 5 4
4 6
i=3 7
6 4
5 9
7 2
6 5
6
3 2
2 9
4 8
Step 2:-max_heapify(3, 9) max_heapify(6, 9) 1 i=2 4 8
5 6 5 4
6 5
3 7
6 4
5 9
7 2
4 5
6
3 2
2 9

4 8
Step 3:-max_heapify(2, 9) max_heapify(5,9) i= 1 2 4 8
7 2 5 4
6 5
3 7
6 4
5 9
5 6
4 5
6
3 2
2 9
4 8

Step 4:-max_heapify(1, 9) max_heapify(2,9) max_heapify(4, 9) 1 2 4 8


6 4 7 2
6 5
3 7
5 4
5 9
5 6
4 5
6
3 2
2 9
4 8
Step 5: Max heap is created Array elements P[1] P[2] P[3] P[4] P[5] P[6] P[7] P[
8] P[9] Original 64 56 46 29 72 65 32 54 48 After creation of heap 72 64 65 54 5
6 45 32 29 48 Steps to delete the root and create the sorted array in ascending
order: Step 1: Interchange P[1] and P[9] Array elements P[1] P[2] P[3] P[4] P[5]
P[6] P[7] P[8] P[9] Step 1 48 64 65 54 56 45 32 29 72 No heapify. 1 2 4 8
6 4 4 8
1 max_heapify(1, 8)
6 5
6 5
3 7 8 4
2
6 4
3 5 6
4 8
5 4
5
5 6
6
4 5
3 2
5 4
5 6

4 5
7
3 2
2 9
2 9
Step 2: Interchange P[1] and P[8] Array elements P[1] P[2] P[3] P[4] P[5] P[6] P
[7] P[8] P[9] Step 2 29 64 48 54 56 45 32 65 72 No heapify. 1
2 9
1
6 4

max_heapify(1, 7) max_heapify(2, 7) 2 4
6 4 4 8
3
2 max_heapify(5, 7)
3 2
5 6
3 5 6
4 8
5 4
5
5 6
6
4 5
7
4
5 4
2 9
4 5
7
3 2
Step 3: Interchange P[1] and P[7] Array elements P[1] P[2] P[3] P[4] P[5] P[6] P
[7] P[8] P[9] Step 3 32 56 48 54 29 45 64 65 72 No heapify. 1 2 4
5 6 3 2
1 max_heapify(1, 6) max_heapify(2, 6)
4 8
5 6
3
2 max_heapify(4, 6) 4
3 2
5 4
3 5 6
4 8
5 4

5
2 9
6
4 5
2 9
4 5
Step 4: Interchange P[1] and P[6] Array elements P[1] P[2] P[3] P[4] P[5] P[6] P
[7] P[8] P[9] Step 4 45 54 48 32 29 56 64 65 72 No heapify. 1 4 1 5 5 4 max_hea
pify(1, 5) max_heapify(2, 5) 2 4
5 4 4 8
3 4
2
4 5
3 5
4 8
3 2
5
2 9
3 2
2 9
Step 5: Interchange P[1] and P[5] Array elements P[1] P[2] P[3] P[4] P[5] P[6] P
[7] P[8] P[9] Step 5 29 45 48 32 54 56 64 65 72 No heapify. 1 2 1 4 9 8 max_hea
pify(1, 4) max_heapify(3, 4) 2
4 5 4 8
3
2
4 5
3
2 9

4
3 2
4
3 2
Step 6: Interchange P[1] and P[4] Array elements P[1] P[2] P[3] P[4] P[5] P[6] P
[7] P[8] P[9] Step 6 32 45 29 48 54 56 64 65 72 No heapify. 1 3 1 4 2 5 max_hea
pify(1, 3) max_heapify(3, 3) 2
4 5 2 9
3
2
3 2
3
2 9
Step 7: Interchange P[1] and P[3] Array elements P[1] P[2] P[3] P[4] P[5] P[6] P
[7] P[8] P[9] Step 7 29 32 45 48 54 56 64 65 72
No heapify. 1 2
3 2
2 9
1 max_heapify(1, 2) max_heapify(2, 2) 2
2 9
3 2
Step 8: Interchange P[1] and P[2] Array elements P[1] P[2] P[3] P[4] P[5] P[6] P
[7] P[8] P[9] Step 8 29 32 45 48 54 56 64 65 72 No heapify. 1 max_heapify(1, 1)
1
2 9 2 9
No, the sorted array isArray elements P[1] P[2] P[3] P[4] P[5] P[6] P[7] P[8] P
[9] Finally 29 32 45 48 54 56 64 65 72
12.10 Radix Sort
Bucket sort or radix sort can be used to sort a list of elements. In case of dec
imal numbers, the base or radix is 10.

First of all the list of elements is sorted according to the first digit thus th
e elements are arranged in 10 buckets. In second pass, elements are arranged acc
ording to the second digit and so on. This process depends on the number of digi
ts of the largest number. E.g. if the largest number is 1234 then 4 passes are n
eeded. Example: Given array is:P[0] P[1] P[2] P[3] P[4] P[5] P[6] P[7] P[8] P[9]
P[10] 348 143 361 423 538 128 600 858 12 274 999 Pass 1: Elements 0 348 143 361
423 538 128 600 855 12 274 999 Pass 2: Elements 600 361 12 143 423 274 855 85 5
12 14 3 42 3 27 4 0 60 0 1 2 3 Buckets 4 5 6 36 1 7 8 9 1 2 27 4 999 60 0 85 5
36 1 42 3 53 8 12 8 14 3 1 2 3 Buckets 4 5 6 7 8 34 8 9

348 538 128 999 Pass 3: Elements 0 600 12 128 423 538 143 348 855 361 274 999 Th
erefore the sorted array is:27 4 36 1 14 3 34 8 1 2 12 8 1 2 3 12 8 53 8
34 8
999 Buckets 4 5
6 60 0
7
8
9
42 3 53 8
85 5
999
P[0] P[1] P[2] P[3] P[4] P[5] P[6] P[7] P[8] P[9] P[10] 12 128 143 274 348 361 4
23 538 600 855 999
Algorithm 12.15 1. Algorithm radix(P, n) 2. // Purpose : This algorithm sorts a
set of elements in ascending order using radix sort. 3. // Input : P[0.n-1] is an
array of n decimal numbers hich is to be sorted in ascending order. 4. // Outp
ut : None. 5. //Comment: The one dimensional array buck[j] keeps the track of th
e index of the elements in jth bucket[j][]. 6. { 7. div = 1; 8. num = number of
digits in the largest number of the array P[]. 9. for( pass = 1; pass num; pass+
+) 10. { 11. for(k = 0; k < 10; k++) 12. buck[k] = 0;

13. for(i = 0; i < n; i++) 14. { 15. j = (P[i]/div)%10; 16. bucket[j][buck[j]++]


= P[i]; 17. } 18. i=0; 19. for(k = 0; k < 10; k++) 20. { 21. for(j = 0; j < buc
k[k]; j++) 22. P[i++] = bucket[k][j]; 23. } 24. div*=10; 25. } 26. }// End of Al
gorithm Time complexity: Radix sort is dependent on three things:
R = Radix (10
for decimal, 26 for alphabets, and 2 for binary). D = Number of digits in the la
rgest element. N = Size of array of elements. Therefore, the maximum number of c
omparisons ill be F(N) = R * D * N 1. Best case: In best case the number of dig
its in largest element (D) ill be logR N. So the maximum number of comparisons
= R * logR N * N Which is of O(N log N). 2. Worst case: Suppose the number of di
gits in the largest element (D) is equal to number of elements in array(N). Whic
h is of O(N2).
12.11 Comparison study of different sorting
Sorting Technique Best Case Average Case Worst Case Bubble O(n) O(n2) O(n2) Inse
rtion O(n) O(n2) O(n2) 2 2 Selection O(n ) O(n ) O(n2) Merge O(nlogn) O(nlogn) O
(nlogn) Quick O(n2) O(nlogn) O(nlogn) 2 Radix O(n ) O(nlogn) O(nlogn) Heap O(nlo
gn) O(nlogn) O(nlogn) /* Sorting using Bubble Sort*/ /* File Name: BUBBLE.C */ #
include<stdio.h> #include<conio.h> #define TRUE 1 #define FALSE 0 void fnBubbleS
ort(int P[],int n)

//Purpose : This algorithm sorts a set of elements using the concept of bubble s
ort in ascending order. //Input : P[0...n-1] is an array of n elements. //Output
: None. //Comments: Here sap is a Boolean variable. After each iteration, TRUE
value of sap indicates at least one interchange has taken place and FALSE valu
e of sap signifies the array is no sorted. { int sap,Iteration,j,temp; sap =
TRUE; for(Iteration = 1; Iteration < n && sap == TRUE; Iteration++) { sap = F
ALSE; //Set sap to FALSE before starting of each iteration. for(j = 0; j < n- I
teration; j++) { if(P[j] > P[j+1]) { sap = TRUE; temp = P[j]; P[j] = P[j+1]; P[
j+1] = temp; } } } } // End of algorithm void main(void) { int n,P[50],i; clrscr
(); printf("Enter number of elements in the array\n"); scanf("%d",&n); printf("E
nter the elements no\n"); for(i=0;i<n;i++) scanf("%d",&P[i]); fnBubbleSort(P,n)
; printf("After sorting:\n"); for(i=0;i<n;i++) printf("%d\t",P[i]); printf("\n")
; getch(); } /*Sorting using insertion Sort*/ /* File Name: INSERTION.C */ #incl
ude<stdio.h> #include<conio.h> void fnInsertionSort(int P[], int n) //Purpose :
This algorithm sorts a set of elements using the concept of insertion sort. //In
put : P[0.n-1] is an array of n elements hich is to be sorted in ascending order
. //Output : None. { int Iteration,temp,j; for(Iteration = 1; Iteration < n; Ite
ration++) {

temp = P[Iteration]; for(j = Iteration-1; j >= 0 && temp < P[j]; j--) P[j+1] = P
[j]; P[j+1] = temp; } }//End of algorithm void main(void) { int n,P[50],i; clrsc
r(); printf("Enter number of elements in the array\n"); scanf("%d",&n); printf("
Enter the elements no\n"); for(i=0;i<n;i++) scanf("%d",&P[i]); fnInsertionSort(
P,n); printf("After sorting:\n"); for(i=0;i<n;i++) printf("%d\t",P[i]); printf("
\n"); getch(); } /* Sorting using Selection Sort*/ /* File Name: SELECTION.C */
#include<stdio.h> #include<conio.h> #define TRUE 1 #define FALSE 0 void fnSelect
ionSort(int P[], int n) //Purpose : This algorithm sorts a set of elements using
the concept of selection sort. //Input : P[0.n-1] is an array of n elements hic
h is to be sorted in ascending order. //Output : None. { int k,loc,j,temp; for(k
= 0; k < n-1; k++) { loc= k; //loc keeps the track of index of the minimum elem
ent in the list. for(j = k+1; j < n; j++) if(P[j] < P[loc]) loc = j; if(loc != k
) { temp = P[k]; P[k] = P[loc]; P[loc] = temp; } } }//End of algorithm void main
(void) {

int n,P[50],i; clrscr(); printf("Enter number of elements in the array\n"); scan


f("%d",&n); printf("Enter the elements no\n"); for(i=0;i<n;i++) scanf("%d",&P[i
]); fnSelectionSort(P,n); printf("After sorting:\n"); for(i=0;i<n;i++) printf("%
d\t",P[i]); printf("\n"); getch(); } /*Sorting using Merge Sort*/ /* File Name:
MERGE.C */ #include<stdio.h> #include<conio.h> void fnMsort(int[],int,int); void
fnMerge(int[],int,int,int); void fnMsort(int P[], int lo, int high) //Purpose
: This algorithm sorts a set of elements using the concept of merge sort. //Inpu
t : P[lo.high] is an array of (high-lo+1) elements hich is to be sorted in asc
ending order. lo is the loer index and high is the upper index of the array. /
/Output : None. { int mid; if(lo < high) { mid = (lo + high)/2; fnMsort(P,lo,
mid); fnMsort(P,mid+1, high); fnMerge(P,lo, mid, high); } }//End of algoritm v
oid fnMerge(int P[], int lo, int mid, int high) //Purpose : This algorithm merg
es to sorted sub arrays. //Input : The loer index and upper index of to sub a
rrays are lo to mid and mid+1 to high respectively. //Output : None. { int h,k,
j,i,B[50]; h = lo; k = lo; j = mid + 1; hile(h <= mid && j <= high) { if(P[h]
<= P[j]) {

B[k] = P[h]; h = h + 1; } else { B[k] = P[j]; j = j+1; } k = k + 1; } if(h < mid


) { for(i = h ; i <= mid; i++) { B[k] = P[i]; k = k + 1; } } else { for(i = j; i
<= high; i++) { B[k] = P[i]; k = k+1; } } for(i = lo; i <= high; i++) P[i] = B
[i]; }//End of algorithm void main(void) { int n,P[50],i; clrscr(); printf("Ente
r number of elements in the array\n"); scanf("%d",&n); printf("Enter the element
s no\n"); for(i=0;i<n;i++) scanf("%d",&P[i]); fnMsort(P,0,n-1); printf("After s
orting:\n"); for(i=0;i<n;i++) printf("%d\t",P[i]); printf("\n"); getch(); } /*So
rting using Quick Sort*/ /* File Name: QUICK.C */ #include<stdio.h> #include<con
io.h> void fnQsort(int[],int,int);

int fnPartition(int[],int,int); void fnInterchange(int[],int,int); void fnQsort(


int P[], int p, int q) //Purpose : This algorithm sorts an array using quick sor
t. //Input : The loer index and upper index of the array are p and q respective
ly. //Output : None. { int j; if(p < q) { j = fnPartition(P,p, q+1); fnQsort(P,
p, j-1); fnQsort(P, j+1, q); } }//End of algorithm int fnPartition(int P[], int
m, int n) //Purpose : This algorithm finds the proper place of the pivot element
. //Input : The loer index and upper index of the array are m and n respectivel
y. //Output : None. { int v,i,j; P[n] = 32767; //Assign a large value at the end
of the array. v = P[m]; // v is the pivot element. i = m; j = n; do { do { i =
i+1; } hile(P[i] < v); do { j = j-1; }hile(P[j] > v); if(i < j) fnInterchange
(P,i, j); }hile(i < j); P[m] = P[j]; P[j] = v; return j; //j is the actual posi
tion of the pivot element in the sorted array. }//End of algorithm void fnInterc
hange(int P[],int i,int j) { int temp; temp = P[j]; P[j] = P[i]; P[i]=temp; }

void main(void) { int n,P[50],i; clrscr(); printf("Enter number of elements in t


he array\n"); scanf("%d",&n); printf("Enter the elements no\n"); for(i=0;i<n;i+
+) scanf("%d",&P[i]); fnQsort(P,0,n-1); printf("After sorting:\n"); for(i=0;i<n;
i++) printf("%d\t",P[i]); printf("\n"); getch(); } /*Sorting using Heap Sort*/ /
* File Name: HEAP.C */ #include<stdio.h> #include<conio.h> void fnHeap_sort(int[
],int); void fnBuild_Max_Heap(int[],int); void fnMax_heapify(int[],int,int); voi
d interchange(int[],int,int); void fnHeap_sort(int P[], int length) // Purpose :
This algorithm sorts a set of element in ascending order using heap sort. // In
put: The elements are stored in the array P[1length]. // Output : None. { int hea
p_size,i; heap_size = length; fnBuild_Max_Heap(P, length); for(i = length; i>=2;
i--) { interchange(P, 1, i); heap_size--; fnMax_heapify(P, 1, heap_size); } } v
oid fnBuild_Max_Heap(int P[], int length) //Purpose : This algorithm builds the
max heap ith the given data. //Input : length of the array. //Output : None. {
int i; for(i = length/2; i >=1; i--) fnMax_heapify(P, i, length); }

void fnMax_heapify(int P[], int i, int heap_size) // Purpose : This algorithm ad


just the heap ith size length in respect to the array position i. // Input: i a
rray position and length is the size. //Output : None. { int l,r,largest; l = le
ft(i); // index of the left child of i. r = right(i); // index of the right chil
d of i. if(l <= heap_size) { if(l <= heap_size && P[l] >= P[i]) largest = l; els
e largest = i; if(r <= heap_size && P[r] > P[largest]) largest = r; if(largest !
= i) { interchange(P,i, largest); fnMax_heapify(P, largest, heap_size); } } } in
t left(int i) { return(2*i); } int right(int i) { return(2*i+1); } void intercha
nge(int P[],int i,int j) { int temp; temp = P[j]; P[j] = P[i]; P[i]=temp; } void
main(void) { int n,P[50],i; clrscr(); printf("Enter number of elements in the a
rray\n"); scanf("%d",&n); printf("Enter the elements no\n"); for(i=1;i<=n;i++)
scanf("%d",&P[i]);

fnHeap_sort(P,n); printf("After sorting:\n"); for(i=1;i<=n;i++) printf("%d\t",P[


i]); printf("\n"); getch(); } /* C CODE TO IMPLEMENT THE RADIX SORT*/ /* File Na
me: RADIX.C */ #include<stdio.h> #include<conio.h> void radix_sort(int); int P[1
00]; void radix_sort(int n) // Purpose : This algorithm sorts a set of elements
in ascending order using radix sort. // Input: P[0.n-1] is an array of n decimal
numbers hich is to be sorted in ascending order. // Output : None. //Comment: T
he one dimensional array buck[j] keeps the track of the index of the elements in
jth bucket[j][]. { int bucket[10][5],buck[10],b[10]; int i, j, k, l, num, div,
large, passes; div=1; num=0; large=P[0]; for(i=1;i<n;i++) { if(P[i] > large) lar
ge=P[i]; } hile(large > 0) { num++; large=large/10; } for(passes=0;passes < num
; passes++) { for(k=0;k<10;k++) buck[k]=0; for(i=0;i<n;i++) { j=(P[i]/div)%10; b
ucket[j][buck[j]++]=P[i]; } i=0; for(k=0;k<10;k++) { for(j=0;j<buck[k];j++) P[i+
+]=bucket[k][j]; } div*=10; }

}//End of Function void main() { int n, i; clrscr(); printf("Enter number of ele


ments"); scanf("%d",&n); printf("Enter the elements no"); for(i=0;i<=n-1;i++) s
canf("%d",&P[i]); radix_sort(n); printf("After sorting\n"); for(i=0;i<=n-1;i++)
printf("%d\t",P[i]); printf("\n"); getch(); }
12.12 MCQ Chapter 12
1. Name the sort for hich time is not proportional to n2: (a) Selection sort (b
) Bubble sort (c) Quick sort (d) None of these 2. The element at the root of the
heap is (a) largest (b) smallest (c) depending on type of heap it may smallest
or largest. (d) None of these 3. This sort does not use divide and conquer metho
dology (a) Merge sort (b) Quick sort (c) Bubble sort (d) None of these 4. Name t
he sort in hich array to be sorted is partitioned again & again in such a ay t
hat all elements less than or equal to partitioning element appear before it and
those hich are greater appear after it (a) Merge sort (b) Quick sort (c) Selec
tion sort (d) None of these. 5. This sort inserts each elements A (K) into prope
r position in the previously sorted sub array A (1) ...A (K-1). (a) Insertion so
rt (b) Radix sort (c) Merge sort (d) bubble sort 6. This sort finds location LOC
of smallest element in A (K), ..., A (N) and then interchange A (LOC) ith A (K
) for K = 1, ..., N - 1.

(a) Shuffle sort (c) Heap sort


(b) Quick sort (d) None of these
7. In this sort, file is divided into subfiles hich are to be independently sor
ted and then merged. (a) quick sort (b) heap sort (c) Bubble sort (d) None of th
ese 8. This searching method requires that all keys must reside in internal memo
ry (a) Binary search (b) sequential search (c) Hashing (d) None of these 9. Aver
age case time complexity of the quick sort algorithm is more than (a) O(N log2 N
) (b) O(N ln N) 2 (c) O(N ) (d) O(N3) 10. Worst case time complexity of the heap
sort algorithm is (a) O(N log2 N) (b) O(N ln N) (c) O(N2) (d) O(N3) 11. For sor
ting contiguous list of records quicksort may be preferred over merge sort becau
se: (a) it requires less time alays (b) it does not require extra space for an
auxiliary storage. (c) it requires less programming effort (d) some programming
languages does not support recursion 12. In quicksort, a desirable choice for th
e partitioning element ill be : (a) first element of the list (b) last element
of the list (c) median of the list (d) a randomly chosen element of the list 13.
Stability of a sorting algorithm is important for (a) sorting records on the ba
sis of multiple keys (b) orst case performance of the sorting algorithm (c) sor
ting alphanumeric keys because they are likely to be same. (d) None of the above
. 14. the heap (represented by an array) constructed from the list of numbers 30
, 10, 80, 60, 15, 55, 17 is: (a) 60, 80, 55, 30, 10, 17, 15 (b) 80, 55, 60, 15,
10, 30, 17 (c) 80, 60, 30, 17, 55, 15, 10 (d) None of the above 15. Which of the
folloing sorting algorithms has a orst case time complexity of 0 (n2) to sort
n records? (a) Quick sort (b) Merge sort

(c) Heap sort (d) None of the above 16. The complexity of the comparison based s
orting algorithm is: (a) (n log n) (b) (n) 2 (c) (n ) (d) (n n) 17. Merge sort uses
(a) Divide and con uer strategy (b) Backtracking approach (c) Heuristic Search (
d) Greedy approach 18. For merging two sorted lists of sizes m and n into a sort
ed list of size m + n, we re uire comparisons of (a) O(m) (b) O(n) (c) O(m+n) (d
) O(log m + log n) 19. The minimum number of interchanges needed to convert the
array 89, 19, 40, 17, 12, 10, 2, 5, 7, 11, 6, 9, 70 into a heap with the maximum
element at the root is (a) 0 (b) 1 (c) 2 (d) 3 20. A sorting techni ue is calle
d stable if: (a) It takes O(n log n) time . (b) It maintains the relative order
of occurrences of non-distinct elements (c) It uses divide and con uer paradigm
(d) It takes O(n) space (GATE-1990)
(GATE-1995)
(GATE-1996)
(GATE-1999)
21. Suppose we want to arrange the n numbers sorted in an array such that all ne
gative values occur before all positive ones. Minimum number of exchanges re uir
ed in the worst case is (GATE-1999) (a) n - 1 (b) n (c) n + 1 (d) None of the ab
ove 22. If one uses straight two-way merge sort algorithm to sort the following
elements in ascending order 20, 47, 15, 8, 4, 40, 9, 30, 12, 17, then the order
of these elements after the second pass of the algorithm is: (GATE-1999) (a) 8,
9, 15, 20, 47, 4, 12, 17, 30, 40 (b) 8, 15, 20, 47, 4, 9, 30, 40, 12, 17 (c) 15,
20, 47, 4, 8, 9, 12, 30, 40, 17 (d) 4, 8, 9, 15, 20, 47, 12, 17, 30, 40 23. Let
s be a sorted array of n integers. Let t(n) denote the time taken for the most
efficient algorithm to determine if there are two elements with sum less than 10
00 in s. Which of the following statements is true? (GATE-2000)

(a) t (n) is O(1) (b) n t (n) n log2 n (c) n log2 n t (n) < n C2 (d) t (n) = nC2
24. The number of swappings needed to sort the numbers 8, 22, 7, 9, 31, 19, 5,
13 in ascending order, using bubble sort is (a) 11 (b) 12 (c) 13 (d) 14
25. Given two sorted list of size m and n respectively. The number of comparison
s needed in the worst case by the merge sort algorithm will be (a) m x n (b) max
imum of m, n (c) minimum of m, n (d) m + n - 1 26. Sorting is not useful for (a)
report generation (b) minimizing the storage needed (c) responding to ueries e
asily (c) making searching easier and efficient 27. Choose the correct statement
s. (a) Internal sorting is used if the number of items to be sorted is very larg
e. (b) External sorting is used if the number of items to be sorted is very larg
e. (c) External sorting needs auxiliary storage. (d) Internal sorting needs auxi
liary storage. 28. A sorting techni ue that guarantees, that records with the sa
me primary key occurs iti the same order in the sorted list as in the original u
nsorted list is said to be (a) stable (b) consistent (c) external (d) linear 29.
The way a card game player arranges his cards as he picks them up one by one, i
s an example of (a) bubble sort (b) selection sort (c) insertion sort (d) merge
sort 30. You want to check whether a given set of items is sorted. Which of the
following sorting methods will be the most efficient if it is already in sorted
order? (a) Bubble sort (b) Selection sort (c) Insertion sort (d) Merge sort 31.
The average number of comparisons performed by the merge sort algorithm, in merg
ing two sorted lists of length 2 is (a) 8/3 (b) 8/5 (c) 11/7 (d) 11/6 32. Which
of the following sorting methods will be the best if number of swappings done, i
s the only measure of efficiency? (a) Bubble sort (b) Selection sort (c) Inserti
on sort (d) Quick sort 33. You are asked to sort 15 randomly generated numbers.
You should prefer (a) bubb1esort (b) uick sort (c) merge sort (d) heap sort 34.
As part of the maintenance work, you are entrusted with the work of rearranging
the library books in a shelf in proper order, at the end of each day. The ideal
choice will be (a) bubble sort (b) insertion sort (c) selection sort (d) heap s
ort

35. The maximum number of comparisons needed to sort 7 items using radix sort is
(assume each item is a 4 digit decimal number) (a) 280 (b) 40 (c) 47 (d) 38 36.
Which of the following algorithms exhibits the unnatural behavior that, minimum
number of comparisons are needed if the list to be sorted is in the reverse ord
er and maximum number of comparisons are needed if they are already in sorted or
der? (a) Heap sort (b) Radix sort (c) Binary insertion sort (d) There can't be a
ny such sorting method 37. Which of the following sorting algorithm has the wors
t time complexity of nlog (n)? (a) Heap sort (b) Quick sort (c) Insertion sort (
d) Selection sort 38. Which of the following sorting methods sorts a given set o
f items that is already in sorted order or in reverse sorted order with e ual sp
eed? (a) Heap sort (b) Quick sort (c) Insertion sort (d) Selection sort 39. Merg
e sort uses (a) divide and con uer strategy (b) backtracking approach (c) heuris
tic search (d) greedy approach 40. For merging two sorted lists of sizes m and n
into a sorted list of size m+n, we re uire comparisons of (a) O(m) (b) O(n) (c)
O(m+n) (d) O(log(m) + log(n)) 41. A machine needs a minimum of 100 see to sort
1000 names by uick sort. The minimum time needed to sort 100 names will be appr
oximately (a) 50.2 see (b) 6.7 see (c) 72.7 see (d) 11.2 see 42. A machine took
200 see to sort 200 names, using bubble sort. In 800 see, it can approximately s
ort . (a) 400 names (b) 800 names (c) 750 names (d) 800 names 43. The correct or
der of arrangement of the names Bradman, Lamb, May, Boon, Border, Underwood and
Boycott, so that the uicksort algorithm makes the least number of comparisons i
s (a) Bradman, Border, Boon, Boycott, May, Lamb, Underwood (b) Bradman, Border,
Boycott, Boon, May, Underwood, Lamb (c) Underwood, Border, Boon Boycott, May, La
mb, Bradman (d) Bradman, May, Lamb, Border, Boon, Boycott, Underwood 44. Which o
f the following is useful in implementing uick sort? (a) Stack (b) Set (c) List
(d) Queue
45. Which of the following algorithm design techni ue is used in the uick sort
algorithm? (a) Dynamic programming (b) Backtracking (c) Divide and con uer (d) G
reedy method 46. Assume 5 buffer pages are available to sort a file of 105 pages
. The cost of sorting using m-way merge sort is (a) 206 (b) 618 (c) 840 (d) 926

47. A sorting procedure is called to sort a list of 100 integers that have been
read from a file. If all 100 values are zero, what would the execution re uireme
nts (in terms of Big-O) be if the sort used was MergeSort? (a) O(N) (b) O(N2) (c
) O(N log2 N) (d) None of these. 48. A list is ordered from smallest to largest
when a sort is called. Which sort would take the longest time to execute? (a) He
apSort (b) Bubble sort . (c) QuickSort (with the first element as the split valu
e) (d) SelectionSort. 49. A list is ordered from smallest to largest when a sort
is called. Which sort would take the shortest time to execute? (a) Heapsort (b)
ShortBubble (c) QuickSort (d) SelectionSort. 50. Identify one or more correct a
nswers: Sorting an array of pointers to list elements, rather than sorting the e
lements themselves, is a good idea when (a) the number of elements is vary large
(b) the individual elements are large in size (c) the sort is recursive (d) the
re are multiple keys on which to sort the elements.
Solutions:
1. b 16. a 31. a
34. b 49. d 5. a
38. b 9. b 24. d
5. a 27. b,c 28.

46. c
20. b
39. a
a 29.

2. c 17. a 32. b 47. c 3. c 18. c 33. a 48. c 4. b 19. b


35. a 50. b 6. d 21. a 36. c 7. d 22. b 37. a 8. a 23. b
10. a 25. d 40. c 11. b 26. b 41. b 12. c 13. c 14. b,c 1
c 30. c 42. a 43. a,b 44. a 45. c

12.13 Exercise Chapter 12


1. What is a sorting? State different types of sorting method and compare betwee
n them. 2. Write down the algorithm for bubble sort and explain how you can sort
a unsorted array of integers by using bubble sort. Find out the time complexity
of your algorithm. 3. Write down the algorithm for bubble sort and explain how
you can sort a unsorted array of integers by using insertion sort. Find out the
time complexity of your algorithm. 4. Write down the algorithm for bubble sort a
nd explain how you can sort a unsorted array of integers by using selection sort
. Find out the time complexity of your algorithm. 5. Write down the algorithm fo
r bubble sort and explain how you can sort a unsorted array of integers by using
merge sort. Find out the time complexity of your algorithm. 6. Write down the a
lgorithm for bubble sort and explain how you can sort a unsorted array of intege
rs by using uick sort. Find out the time complexity of your algorithm. 7. Write
down the algorithm for bubble sort and explain how you can sort a unsorted arra
y of integers by using heap sort. Find out the time complexity of your algorithm
. 8. Write down the algorithm for bubble sort and explain how you can sort a uns
orted array of integers by using radix sort. Find out the time complexity of you
r algorithm.

Chapter - 13 SEARCHING
13.1 INTRODUCTION
Searching is a process to find an element from a set of elements stored in an or
der or randomly. In this chapter we will discuss about two popular searching tec
hni ues 1) Linear/Se uential search and 2) Binary search. 13.2 SEQUENTIAL SEARCH
Se uential search is nothing but searching an element in linear way. This can b
e in array or in linked list. The array or linked list may be in sorted or unsor
ted order. We have a need to start the search from beginning and scan the elemen
ts one by one until the end of array or linked list. For successful search it re
turns the location of the element, otherwise returns the failure notification. 1
. Se uential search in array: Algorithm 13.1 describes the procedure. Algorithm
13.1 1. Algorithm fnSe uential_search_in_Array(arrData, item, n) 2. // Purpose :
This algorithm finds an element from an array of elements. 3. // Input : n is t
he number of elements in the array arrData and item is the data to be searched.
4. // Output : For successful search it returns position of the item in the arra
y, otherwise returns -1. 5. { 6. for(i = 0; i <= n-1; i++) 7. { 8. if(arrData[i]
== item) 9. { 10. return i; 11. break; 12. } 13. } 14. return -1; 15. }// End o
f Algorithm. Consider the following array arrData[0:4]. arrData[0] arrData[1] ar
rData[2] arrData[3] arrData[4] 10 15 8 9 25 If the item = 9 then the above algor
ithm returns 3. If the item be 20 then the above algorithm returns -1. 2. Se uen
tial search in linked list: Algorithm 13.2 describes the procedure. Algorithm 13
.2 1. Algorithm fnSe uential_search_in_LinkedList(ptrStart, item) 2. // Purpose
: This algorithm finds an element from a linked list. 3. // Input : ptrStart is
the starting address of the list and item is the data to be searched. 4. // Outp
ut : For successful search it returns position of the item in the array, otherwi
se returns -1. 5. { 6. SLLNode *ptrTemp;

7. ptrTemp = ptrStart; 8. iPosition = 1; 9. while(ptrTemp != NULL) 10. { 11. if(


ptrTemp->iData == item) 12. return iPosition; 13. ptrTemp = ptrTmp->ptrNext; 14.
iPosition = iPosition + 1; 15. } 16. return -1; 17. }//End of Algorithm. Consid
er the following linked list: ptrStart
10 15 8 9 25 NULL
If item = 9 then the above algorithm returns 4. If item be 20 then the above alg
orithm returns -1. 3. Time complexity 4. Best case: If the desired record is pre
sent in the first position of the search table, then only one comparison is made
. Therefore, Tb(n) = O(1) 5. Average case: The element can be found at any posit
ion in the list and the probability is 1/n. Now if the element is found at first
position then only one comparison is re uired, for the second position two comp
arisons are re uired and so on. Hence, f(n) = 1/n + 2/n + + n/n = (1 + 2 + ...+ n)/n
= n(n + 1)/2n = (n + 1)/2 Therefore, Ta(n) = O(n) 6. Worst case: For an unsucce
ssful search, the search table will be visited till the last record. Therefore,
Tw(n) = O(n)
13.3 BINARY SEARCH
Binary search is performed over a sorted array of elements. The logic behind thi
s techni ue is given below: 1. First find the middle element of the array. 2. Co
mpare the middle element with the item. 3. There are three cases. a) If it is th
e desired element then search is successful. b) If it is less than the desired e
lement then search only the first half of the array. c) If it is greater than th
e desired element search in the second half of the array. Now in linked list ran
dom access is not possible. So first we have to calculate the position of the mi
ddle element and then se uentially we have to traverse to the middle position. T
hats why it is hard to implement the binary search over a linked list.

Example: Consider the following sorted array: arrData[0] arrData [1] arrData [2]
arrData [3] arrData [4] arrData [5] arrData [6] 19 21 27 30 35 40 43 And the it
em to be searched is = 27. Iteratio n original [0] [1 ] Array elements [2] [3 [4
] ] 35 35 35 Comments [5 ] [6] mid = (6+0)/2 = 3. item < arrData[mid] So, now s
earch in arrData[l:mid
1] i.e. arrData[0:2]. mid = (2+0)/2 = 1. item > arrData[m
id] So, now search in arrData[mid+1:h]i.e. arrData[2:2]. mid = (2+2)/2 = 2. item
= arrData[mid]. So, successful search. Return the index of the item in the arra
y i.e. here 2. h=6 40 43 40 40 43 43
l=0 19 21 27 30 Step = 1 l=0 h=2 19 21 27 30 Step = 2 l=h=2 19 21 27 30
Now, let the item = 42 Iteratio n original Step = 1 19 Step = 2 19 Step = 3 19 2
1 27 30 35 21 27 30 35 21 27 [0] [1 ] Array elements [2 [3 [4] [5] ] ] 27 30 35
l=4 30 35 40 Comments [6]
l=0 19 21
h=6 mid = (6+0)/2 = 3. item > arrData[mid] So, now search in arrData[mid+1 : h]
i.e. arrData[4:6]. 43 h=6 mid = (4+6)/2 = 5. item > arrData[mid] So, now search
in arrData[mid+1:h]i.e. arrData[6:6]. 40 43 l=h=6 mid = (6+6)/2 = 6. item < arrD
ata[mid]. So, now search in arrData[l:mid
1]i.e. arrData[6:5]. 40 43 h=5 l=6 As
now l > h the process is stopped and this is an unsuccessful search. So, return

1. 40 43
Algorithm 13.3 1. Algorithm fnBinarySearch_NonRecursive(arrData, low, high, item
) 2. // Purpose : This algorithm finds an element from a sorted array in a non r
ecursive approach. 3. // Input : low and high are the lower and upper index of a
rray arrData and item is the data to be searched. 4. // Output : For successful
search it returns position of the item, otherwise returns
1. 5. { 6. while(low
> high) 7. { 8. mid = (low + high)/2; 9. if(item == arrData[mid]) 10. return mid
; 11. else if(item < arrData[mid]) 12. high = mid 1; 13. else 14. low = mid + 1;
15. } 16. return
1;

17. }// End of Algorithm

Algorithm 12.4 1. Algorithm fnBinarySearch_Recursive(arrData, low, high, item) 2


. // Purpose : This algorithm finds an element from a sorted array in a recursiv
e approach. 3. // Input: low and high are the lower and upper index of array arr
Data and item is the data to be searched. 4. // Output : For successful search i
t returns position of the item, otherwise returns
1. 5. { 6. if(low > high) 7.
return
1; 8. else 9. { 10. mid = (low + high)/2; 11. if(item == arrData[mid]) 1
2. return mid; 13. else if(item < arrData[mid]) 14. fnBinarySearch_Recursive(arr
Data, low, mid 1, item); 15. else 16. fnBinarySearch_Recursive(arrData, mid + 1,
high, item); 17. } 18. }// End of Algorithm Time complexity: 1. Best case: If t
he desired record is present in the mid position of the search table, then only
one comparison is made. Therefore, Tb(n) = O(1) 2. Average case and Worst case:
Suppose T(n) unit of time is required to search the array of n elements. Now in
the second iteration the array is halved. So, in the second iteration T(n/2) tim
e is required and so on. Hence we get the following recurrence relation: T(n) =
c + T(n/2) c = some constant time required to find the middle element. 2 = c + c
+ T(n/2 ) = . = . = kc + T(n/2k) = c logn + T(1) [ Let 2k = n. So, k = logn] The
) = O(log n)
13.4 MCQ Chapter 13
1. Which of the following is not possible as a balance factor of any node of an
AVL tree? (a) 1 (b) 2 (c) 0 (d) none of the above 2. A B
tree of order n is also
called (a) (n
n)
1 tree (c) (n
1)
n tree
(b) n
(n
2) tree (d) none of these

3. A balanced search tree (B


tree) is one in which every node has between: (a) t

1 and 2t
1 children (b) t and 2t children (c) t / 2 and t children (d) None
of these Where t is a constant. 4. What is the maximum number of nodes in a hea
p ith 8 leaf nodes? (a) 15 (b) 16 (c) 17 (d) 31 5. Ho many distinct binary sea
rch tree can be formed hich contains the integers 1, 2, 3 ? (a) 6 (b) 5 (c) 4 (
d) 3 6. Maximum possible height of an AVL Tree ith 7 nodes is : (a) 3 (b) 4 (c)
5 (d) none of the above 7. Which of the folloing is a hash function ? (a) Quad
ratic probing (b) Chaining (c) Open addressing (d) Folding 8. The average number
of key comparisons done in successful sequential search in a list of length n i
s (GATE-1996) (a) log n (b) (n - 1)/2 (c) nl2 (d) (n + 1)/2 9. A binary search t
ree is generated by inserting in order the folloing integers: 50. 15, 62, 5. 20
.. 58, 91. 3. 8, 37. 60. 24 The number of nodes in the left subtree and right su
btree of the root respectively is (a) (4. 7) (b) (7. 4) (c) (8, 3) (d) (3. 8) 10
. An advantage of chained hash table (external sorting) over the open addressing
scheme is (a) Worst case complexity of search operations is less (b) Space used
is less (c) Deletion is easier (d) None of the above
(GATE-1996)
(GATE-1996)
11. Which of the folloing statements is false? (GATE-1998) (a) A tree ith n no
des has n - 1 edges. (b) A labeled rooted binary tree can be uniquely constructe
d given its postorder and preorder results. (c) A complete binary tree ith n in
ternal nodes has (n + 1) leaves. (d) The maximum number of nodes in a binary tre
e of height h is (2h + 1 - 1). 12. A complete n-ary tree is one in hich every n
ode has 0 or n sons. If x is the number of internal nodes of a complete n-ary tr
ee, the number of leaves in it is given by: (a) x (n - 1) + 1 (b) xn - 1 (GATE-1
99B)

(c) xn + 1
(d) x (n + 1) (GATE-1999)
13. Which of the folloing is correct? (a) B-trees are for sorting data on disk
and B+-trees are for main memory (b) Range queries are faster on B+ trees (c) Btrees are primary indexes and B+ trees are for secondary indexes (d) The height
of a B+ tree is independent of the number of records. 14. B+ -trees are preferre
d to binary trees in database because (a) Disk capacities are greater than memor
y capacities (b) Disk access is much sloer than memory access (c) Disk data tra
nsfer rates are much less than memory data transfer rates (d) Disks are more rel
iable than memory. 15. The average successful search time for sequential search
on n items is (a) n / 2 (b) (n-1) / 2 (c) (n+l) / 2 (d) log (n + 1) 16. The or
der of the binary search algorithm is (a) n (b) n2 (c) nlog(n) (d) log(n) 17. Wh
ich is the best? (a) Binary search (b) Sequential search (c) Indexing (d) Cant sa
y as all are best in their on application
18. The element being searched for is not in an array of 100 elements. What is t
he average number of comparisons needed in a sequential search to determine that
the element is not there if the elements are completely unordered? (a) 100 (b)
50 (c) 75 (d) 25 19. The element being searched for is not in an array of 100 el
ements. What is the average number of comparisons needed in a sequential search
to determine that the element is not there if the elements are ordered from smal
lest to largest? (a) 100 (b) 50 (c) 75 (d) 25 20. The element being searched for
is not in an array of 100 elements. What is the average number of comparisons n
eeded in a sequential search to determine that the element is not there if the e
lements are ordered from largest to smallest? (a) 100 (b) 50 (c) 75 (d) 25 21. T
he element being searched for is in an array of 100 elements. What is the averag
e number of comparisons needed in a sequential search to determine the position
of the element if the elements are completely unordered? (a) 100 (b) 50 (c) 75 (
d) 25
Solutions:
1. b 16. d 2. d 17. d 3. a 18. a 4. a 19. b 5. b 20. b 6. b 21. c 7. d 8. d 9. b
10. b 11. b 12. a 13. b 14. a 15. a

13.5 Exercise Chapter 13


1. What is a searching? What are thedifferent types of searching? Briefly descri
be them ith a suitable example. 2. Write an algorithm to find an element in a s
orted array by sequential search and explain it by a suitable example and diagra
m. Find out the time complexity. 3. Write an algorithm to find an element in a s
ingle linked list by sequential search and explain it by a suitable example and
diagram. Find out the time complexity. 4. Write an algorithm to find an element
in a double linked list by sequential search and explain it by a suitable exampl
e and diagram. Find out the time complexity. 5. Write an algorithm to find an el
ement in a sorted array by binary search and explain it by a suitable example an
d diagram. Find out the time complexity. 6. Write an algorithm to find an elemen
t in a single linked list by binary search and explain it by a suitable example
and diagram. Find out the time complexity. 7. Write an algorithm to find an elem
ent in a double linked list by binary search and explain it by a suitable exampl
e and diagram. Find out the time complexity.

CHAPTER 14 HASHING
14.1 Introduction
In this chapter e examine data structures hich are designed specifically ith
the objective of providing efficient insertion and find operations. In order to
meet the design objective, certain concessions are made. Specifically, e do not
require that there be any specific ordering of the items in the list. In additi
on, hile e still require the ability to remove items from the list, it is not
our primary objective to make removal as efficient as the insertion and find ope
rations. Ideally e ould build a data structure for hich both the insertion an
d find operations are O(1) in the orst case. In the case of an ordered list, th
e cost of an insertion is O(1) and the cost of the find operation using linear s
earch is O(n). For a sorted list, the cost of insertion is O(n) and the cost of
the find operation using binary search is O(n logn) for the array implementation
. In order to meet the performance objective of constant time insert and find op
erations, e need a ay to do them ithout performing a search. I.e., given an i
tem k, e need to be able to determine directly from k the array position here
it is to be stored. Therefore, hashing is a searching technique hich takes cons
tant time (O(1)) to find an item from a list.
14.2 Hash table
A hash table is an array of m buckets,
ranslates each key k to a bucket index
slots and each slot is capable to hold
Hash function key k1 k2 k3 k4 value 2

together ith a hash function H(k) that t


(in the range 0m1). A bucket has number of
one record. Hash table (array of buckets)
m-2 2 5 0 1 2 3 4 5

kn
4 Hashing (translating keys to bucket indices)
m2 m1
Figure 14.1 Principles of Hash tables: 1. Each key k has a home bucket in the ha
sh table, namely the bucket ith index H(k). 2. To insert a ne entry ith key k
into the hash table, assign that entry to ks home bucket. 3. To search for an en
try ith key k in the hash table, look in ks home bucket. 4. To delete an entry 
ith key k from the hash table, look in ks home bucket. 5. The hash function must
be consistent:

k1 = k2 => H(k1) = H(k2). 6. In general, the hash function is many-to-one. 7. Al


ays prefer a hash function that makes collisions relatively infrequent.
14.3 Hash functions
In this section e ill discuss about several hashing functions. No e assume t
hat e are dealing ith integer valued keys. A hash function can be defined as a
function hich takes key (k) as input and produces a bucket index as output. H(
k) = L Where,H is a hash function. k is a set of keys. L is bucket indices (or s
et of memory addresses). Some of the popular hash functions are described belo:
1. Division method: Perhaps the simplest of all the methods of hashing a key k
is to divide k by M and then to use the remainder as the bucket index. This is c
alled the division method of hashing. In this case, the hash function is H(k) =
k mod M In certain situations, some extra care is needed in the selection of a s
uitable value for M. For example, it is often convenient to make M an even numbe
r. But this means that H(k) is even if k is even; and H(k) is odd if k is odd. I
f all possible keys are equiprobable, then this is not a problem. Hoever if, sa
y, even keys are more likely than odd keys, the function H(k) = k mod M ill not
spread the hashed values of those keys evenly. Similar problem may occur for od
d value of M. Similarly, it is often tempting to let M be a poer of to. E.g.,
M = 2q for some integer q>1. In this case, the hash function H(k) = k mod M simp
ly extracts the bottom q bits of the binary representation of k. While this hash
function is quite easy to compute, it is not a desirable function because it do
es not depend on all the bits in the binary representation of k. For these reaso
ns M is often chosen to be a prime number. For example, suppose there is a bias
in the ay the keys are created that makes it more likely for a key to be a mult
iple of some small constant, say to or three. Then making M a prime increases t
he likelihood that those keys are spread out evenly. Also, if M is a prime numbe
r, the division of k by that prime number depends on all the bits of k, not just
the bottom q bits, for some small constant q. Example 14.1: Consider a hash tab
le ith 7 slots and the keys are 49, 123, 68, and 90. Suppose e are taking the
value of M = 7. Then, H(49) = 49 mod 7 = 0 H(123) = 123 mod 7 = 4 H(68) = 68 mod
7 = 5 H(90) = 90 mod 7 = 6 The hash table ill look like:

Division method key 49 123 68 90 value 0 4 5 6


Hash table (array of buckets) 49
0 1 2 3 4 5 6
123 68 90
Algorithm 14.1 describes an algorithm hich creates a bucket index according to
division method. Algorithm 14.1 1. Algorithm fnDivision(k, M) 2. // Purpose : Th
is algorithm produces the bucket index for a key using division method. 3. // In
put : The key k and the prime number M. 4. // Output : The bucket address L. 5.
{ 6. L = k%M; //Get the remainder. 7. return L; 8. }// End of algorithm Disadvan
tages: A potential disadvantage of the division method is due to the property th
at consecutive keys map to consecutive hash values. While this ensures that cons
ecutive keys do not collide, it does mean that consecutive array locations ill
be occupied. In certain implementations this can lead to degradation in performa
nce. In the folloing sections e consider hashing methods that tend to scatter
consecutive keys. 2. Middle square method: In middle square method the key k is
squared and then some particulars bits from the middle of k2 (for example 3rd an
d 4th LSB) are extracted to get the desired key. The positions of these particul
ar bits are same for all the keys. For example, if the 3rd and 4th LSB are consi
dered for the square of key k1, then for k2 also 3rd and 4th LSB are considered.
Therefore the hash function is: H(k) = some bits of (k2) Example 14.2: Consider
a hash table ith 10 slots and the keys are 49, 123, 68, and 100. Here e are t
aking the 3rd LSB from the square of each key. Then, H(49) = 3rd LSB(2401) = 4 H
(123) = 3rd LSB(15129) = 1 H(68) = 3rd LSB(4624) = 6 H(100) = 3rd LSB(10000) = 0
The hash table looks like:

Middle square method key 49 123 68 100 value 4 1 6 0


Hash table (array of buckets) 100 123
0 1 2 3 4 5 6 7 8 9
49
68
Algorithm 14.2 describes an algorithm hich creates a bucket index according to
middle square method. Algorithm 14.2 1. Algorithm fnMidSquare(k, b1, b2) 2. // P
urpose : This algorithm produces the bucket index for a key using middle square
method. 3. // Input : k is the key and from b1 to b2 bits are to be extracted fr
om k2. 4. // Output : The bucket index L. 5. { 6. k1 = k*k/ 10(b1-1); //Discard
the left most bits and store the number in k1. (b2-b1+1) 7. L = k1 % 10 ; //Extr
act leftmost (b2-b1) bits from k1. 8. return L; 9. }// End of algorithm 3. Foldi
ng method: In folding method the key k is partitioned into a number of parts k1,
k2, k3.kr, here each part except possibly the last has the same number of digit
s as the required address. Then the parts are added together ignoring the last c
arry. Therefore the hash function is: H(k) = k1 + k2 + k3 + . + kr here the carr
y is ignored. Example 14.3: Consider a hash table ith 10 slots and the keys are
49, 123, 68, and 90. Here e are partitioning the key ith size one. Then, H(49
) = 4 + 9 = 3 ignoring the carry. H(123) = 1 + 2 + 3 = 6 H(68) = 6 + 8 = 4 ignor
ing the carry. H(90) = 9 + 0 = 9 The hash table looks like:

Folding method key 49 123 68 90 value 3 6 4 9


Hash table (array of buckets)
0 1 2 3 4 5 6 7 8 9 90 123 49 68
The algorithm 14.3 illustrates the folding method of hashing: Algorithm 14.3 1.
Algorithm fnFolding(k) 2. // Purpose : This algorithm produces the bucket index
for a key using folding method. 3. // Input : The key k. 4. // Output : The buck
et address L. 5. { 6. q = 1; 7. p = 0; 8. L = 0; 9. hile(k!=0) 10. { 11. p = p
+ 10q * (k%10); 12. k = k/10; 13. q=q+1; 14. if(q=size of each partition) 15. {
16. L = L + p; 17. p = 0; 18. q = 0; 19. } 20. } 21. if(length of L > size of ea
ch partition) 22. Discard the MSB from L. 23. return L 24. }// End of algorithm

14.4 Collision
If to keys k1 and k2 produce same bucket index L for some hash function, then i
t is called collision. To resolute the collision different collision resolution
techniques are available. The collision resolution techniques can be classified
into to broad categories: 1. Open addressing 2. Chaining They are discussed in
next section in details.
14.5 Clustering
Clustering occurs hen keys group together in the hash table and many collisions
. Clustering causes collision and collisions make the clustering problem orse.
14.6 Collision resolution techniques
1. Open addressing: The general procedure for open addressing can be stated as:
i) All keys are stored in hash table only. ii) When collisions occur, use a syst
ematic (consistent) procedure to store elements in free slots of the hash table.
Depending on the systematic procedure open addressing can be of the folloing t
ypes: A) Linear probing: Suppose to keys k1 and k2 yield same memory location (
or bucket index) L. H(k1) = L and H(k2) = L No to resolve this collision, searc
h the memory for an available place like: L, L+1 L + i . Store the key in the first
available place. Example 14.4: Consider a hash table ith 7 slots and the keys
are 49, 123, 68, and 90. Suppose e are using division method to produce bucket
index and e are taking the value of M = 7. The hash table is circular i.e. buck
et index 0 comes after bucket index 6. Collision resolution technique is linear
probing. No, H(49) = 0 Store 49 at 0th location in hash table. H(123) = 5 Store
124 at 5th location in hash table. H(68) = 5 Cell 5 in hash table is already oc
cupied. So check next cell. Cell 6 is empty. Store 68 in 6th cell. H(90) = 5 Cel
l 5, 6 and 0 are already occupied. So store 90 at cell 1 in the hash table. The
hash table ill look like:

Division method key 49 123 68 90 value 0 5 5 5


Hash table (array of buckets) 49 90
0 1 2 3 4 5 6
123 68
B) Quadratic probing: Suppose to keys k1 and k2 yield same memory location (or
bucket index) L. H(k1) = L and H(k2) = L No to resolve this collision, search t
he memory for an available place like: L, L+12, L+22 L + i2 . Store the key in the
first available place. Example 14.4: Consider a hash table ith 7 slots and the
keys are 49, 123, 68, and 90. Suppose e are using division method to produce bu
cket index and e are taking the value of M = 7. The hash table is circular i.e.
bucket index 0 comes after bucket index 6. Collision resolution technique is qu
adratic probing. No, H(49) = 0 Store 49 at 0th location in hash table. H(123) =
5 Store 124 at 5th location in hash table. H(68) = 5 Cell 5 in hash table is al
ready occupied. So check 5+12 cell. Cell 6 is empty. Store 68 in 6th cell H(90)
= 5 Cell 5 and 5 + 12 are already occupied. No check cell 5 + 22. As the list i
s circular 5+ 22 or 9 is interpreted as cell 2 (9%7). Cell 2 is empty. So store
90 at cell 2 in the hash table. The hash table ill look like: Division method k
ey 49 123 68 90 value 0 5 5 5 Hash table (array of buckets) 49
0 1 2 3 4 5 6
90
123 68

C) Double hashing: Here a second hash function is used to resolve the collisions
. If to keys k1 and k2 yield the same memory location, then search the memory l
inearly for an available place like: L, L+H, L+2H..L + iH Store the key at the first a
ailable memory location. D) Rehashing: If at any stage the hash table becomes fu
ll or overflo then it ill be very difficult to find the free slot for ne key.
In such a situation create a ne hash table hich is double in length than the
previous one. Then scan the previous hash table and for each key calculate the n
e bucket index and store them into nely created hash table. 2. Chaining: The g
eneral procedure for chaining is: i) Store all elements that hash to the same sl
ot in a linked list. ii) Store a pointer to the head of the linked list in the h
ash table slot. Example 14.5: Consider a hash table ith 7 slots and the keys ar
e 49, 123, 68, and 87. Suppose e are using division method to produce bucket in
dex and e are taking the value of M = 7. The hash table is circular i.e. bucket
index 0 comes after bucket index 6. Collision resolution technique is chaining.
No, H(49) = 0 Store 49 at 0th location in hash table. H(123) = 5 Store 124 at
5th location in hash table. H(68) = 5 Cell 5 in hash table is already occupied.
So check 5+12 cell. Cell 6 is empty. Store 68 in 6th cell. H(87) = 3 Cell 5 and
5 + 12 are already occupied. No check cell 5 + 22. As the list is circular 5+ 2
2 or 9 is interpreted as cell 2 (9%7). Cell 2 is empty. So store 90 at cell 2 in
the hash table. The hash table ill look like: Division method key 49 123 68 87
value 0 5 5 3 Hash table (array of addresses) 49 N
0 1 2 3 4 5 6
87
N
123
68
N
Comparison study of open addressing and chaining: Collision resolution technique
Open addressing Advantages 1. Save space since e dont have pointers. 2. Fast re
hashing. 3. Fast access through use of main Disadvantages 1. Clustering problem.
2. Priory knoledge is required about maximum number of elements.

Chaining
1. 2. 3. 4.
table space. Unlimited number of elements Unlimited number of collisions No clus
tering problem. Deletion is simpler
3. Multiple collisions may occur. Overhead of multiple linked lists.
14.7 Load factor
Suppose there are n items in the bucket and bucket size is m. Then the load fact
or can be defined as Load factor = occupied space/total space = n/m. =0 indicats
an mpty buckt. = 0.5 signifis that th buckt is haf fu. imiary =1 man
s fu buckt. For opn addrssing can nvr xcd 1, but for chaining thr is
no bar on th vau of .
14.8 Anaysis of opn addrssing and chaining
In our anaysis, w wi count th numbr of probs (or sarch) rquird for a s
uccssfu sarch and th numbr of probs (or sarch) rquird for an unsuccssf
u sarch. U() = numbr of probs rquird for an unsuccssfu sarch. () = numb
r of probs rquird for a succssfu sarch. Th probabiity (P(h)) that a prob
 hits an occupid spac is and th probabiity (P(m)) that a prob hits an mpt
y spac is 1- . P(h) = and P(m) = 1- Now th probabiity that on prob is rquir
d for an unsuccssfu sarch is (1- ). Th probabiity that th unsuccssfu sa
rch trminats aftr two probs is (1- ). imiary th probabiity that th xact
y k probs ar rquird for an unsuccssfu sarch is k-1(1- ). For inar probin
g, th avrag numbr of prob rquird for an unsuccssfu sarch is: U() = 1/2(
1+1/(1- )2) And for a succssfu sarch, avrag numbr of prob is: () = 1/2(1+1
/(1- )) For chaining, th avrag numbrs of probs rquird for an unsuccssfu
sarch and for a succssfu sarch ar approximaty: U() = - + and () = 1 + /2
/* Program to impmnt som hash functions */ /* Fi Nam: Hash_Function.C */
#incud<stdio.h> #incud<conio.h> #incud<math.h> int fnDivision(int k, int M
) // Purpos : This agorithm producs th buckt indx for a ky using division
mthod. // Input: Th ky k and th prim numbr M. // Output : Th buckt addr
ss L. { int L; L = k%M; //Gt th rmaindr. rturn L; }// End of agorithm int
fnMidquar(int k, int b1, int b2)

// Purpos : This agorithm producs th buckt indx for a ky using midd squ
ar mthod. // Input: k is th ky and from b1 to b2 bits ar to b xtractd fr
om k2. // Output : Th buckt indx L. { int k1,L; k1 = (k*k)/ fnpow(10,(b1)); /
/Discard th ft most bits and stor th numbr in k1. L = k1 % fnpow(10,(b2-b1
+1)); //Extract ftmost (b2-b1) bits from k1. rturn L; }// End of agorithm in
t fnpow(int x, int y) { int i,x1=1; for(i=1;i<=y;i++) x1=x1*x; rturn x1; } void
main(void) { crscr(); printf("Division Mthod = %d",fnDivision(20,9)); printf(
"Mid quar of %d = %d",99*99,fnMidquar(99,2,2)); gtch(); }
14.9 MC Chaptr 14
1. Considr th figur bow 0 7 1 1 2 3 4 4 2 5 6 5 7 8 6 9 3 A hash tab
 with 10 buckts with on sot pr buckt is dpictd in th abov Fig. Th sy
mbos,  1 to 7 ar initiay ntrd using a hashing function with inar prob
ing. Th maximum numbr of comparisons ndd in sarching an itm that is not p
rsnt is (a) 4 (b) 5 (c) 6 (d) 3 2. A hash function f dfind as f (ky) = ky
mod 7, with inar probing, is usd to insrt th kys 37, 38, 72, 48, 98 , 11,
56, into a tab indxd from 0 to 6. What wi b th ocation of ky II? (a) 3
(b) 4 (c) 5 (d) 6

3. Th avrag sarch tim of hashing, with inar probing wi b ss if th 
oad factor (a) is far ss than on (b) quas on (c) is far gratr than on (
d) non of th abov 4. A hash tab can stor a maximum of 10 rcords. Currnt
y thr ar rcords in ocations 1,3, 4, 7, 8, 9, 10. Th probabiity of a nw r
cord going into ocation 2, with a hash function rsoving coisions by inar
probing is (a) 0.6 (b) 0.1 (c) 0.2 (d) 0.5 5. Considr a hashing function that
rsovs coision by quadratic probing. Assum th addrss spac is indxd fro
m 1 to 8. Which of th foowing ocations wi nvr b probd if a coision o
ccurs at position 4? (a) 4 (b) 5 (c) 8 (d) 2 6. A hash tab has spac for 100 r
cords. What is th probabiity of coision bfor th tab is 10% fu? (a) 0
.45 (b) 0.5 (c) 0.3 (d) 0.34 (approximaty) 7. A hash function randomy distrib
uts rcords on by on in a spac that can hod x numbr of rcords. Th probab
iity that th mth rcord is th first rcord to rsut in coision is (a) (x-1
) (x-2)...(x-(m-2))(m-) / xm- (b) (x-1) (x-2)... (x-(m-))(m-) / xm- (c) (x1) (x-2)... (x-(m-2))(m-) / xm (d) (x-1) (x-2)... (x-(m-))(m-) / xm 8. If th
hashing function is th rmaindr on division, thn custring is mor iky t
o occur if th storag spac is dividd into 40 sctors rathr than 41. This con
cusion is (a) mor iky to b fas (b) mor iky to b tru (c) is aways
fas (d) non of th abov

outions:
1. b 2. c 3. a 4. a 5. d 6. a 7. a 8. b
14.5 Exrcis Chaptr 14
1. What is hashing? Dfin hash tab and xpain by a suitab diagram. tat t
h princips of hash tab. 2. Dfin hash function. tat diffrnt typs of h
ash functions, giv thir agorithms and xpain thm by suitab diagrams. 3. W
hat ar coision and custring? What is coision rsoution tchniqu? Compar
 btwn diffrnt typs of coision rsoution tchniqu. 4. Discuss diffrn
t typs of coision rsoution tchniqu with suitab diagrams. 5. What is oa
d factor? Anays diffrnt typs of coision rsoution tchniqu with hp of
oad factor.

CHAPTER 15 FILE
Introduction
In our prsnt banking systms ony ATM card is sufficint to oprat a oprat
ions of an account ik (i) To s th baanc (ii) To withdraw amount (iii) To
gnrat mini statmnt to s prvious transactions both dposit and withdrawa
tc. . But on can hav accss if ATM card is pacd on an ATM machin and with
typing th propr password. Thus no papr, no chqu book tc ar rquird and
at th sam tim no intrvntion and prmission of bank officias ar aso rqui
rd for oprating a bank account. This is possib ony bcaus a data ar sto
rd ctronicay in non voati ( Tap, Disk, Drum, CD, DVD tc.) dvics wit
h th hp of computrs and brought back th sam whn ncssary. Not ony in ba
nking but a most a sphrs of if nowadays hav bn drivn by computrs, w
hr storing of data, program tc. ar vry ssntia for futur and rpatd us
ag, which ads to vov various aras of computr sc. ik Data Bas Managm
nt ystm, Data Mining, Imag Procssing, Bio-Informatics tc. In contxt of dat
a structur w wi discuss vry imitid typs of fis and mchanism how to ha
nd ths fis for various oprations.
15.2 Dfinition
(1) Coction of data in non-voati mmory of a computr. (2) Coction of r
atd rcords in non-voati mmory of a computr. Th dfinition (1) suggsts
to put any charactrs, numbrs and symbos to put togthr and to stor in sco
ndary storag dvic with a spcific nam. To rtriv back th sam in futur wi
th suppy of th

spcifid nam th computr wi dispay th contnt i.. what was stord in th
scondary storag for th sam. This typ of fi is cad non-structurd fi
, i.. no particuar structur or th format is rquird to stor data in such t
yp of fi. Th usag of such fi is gnray in th ara of txt procssing,
imag procssing and in program dvopmnt. But th ssntia aras of computi
ng ik Banking, Hospitas, Insuranc and Univrsistis nd data to b stord i
n scondary storag dvic in th structurd format for procssing. Whr th ba
sic format is rcord, i.. ach data shoud bong to a particuar hading trm
d as fids and whn a group of hadings ar dfind togthr for a particuar 
ntity or things a rcord structur is cratd. Whnvr a th rvant data ar
 writtn undr th corrsponding hadings or fids a rcord is cratd and wh
n a th possib rcords ar coctd togthr a structurd fi is formd. 
.g. an account of any bank is rprsntd as 100100 ourav Ganguy 25000
whr th first numbr is account numbr, th scond on is nam and th third o
n is baanc, ik wis a th accounts of th bank coud b rprsntd as Fi
: Account Account Numbr 100100 100101 100102 Nam ourav Ganguy Ashok Mukh
rj uman Gupta Baanc 25000 12000 13000
15.3 Fi Cassification:
Non tructurd fi:
Txt Fi A txt fi is a kind of computr fi that is structurd as a squnc
 of ins. A txt fi xists within a computr fi systm. Th nd of a txt
fi is dnotd by pacing on or mor spcia charactrs, known as an nd-of-fi
 markr, aftr th ast in in a txt fi. (.txt) is a finam xtnsion fo
r fis consisting of txt usuay contain vry itt formatting (x: ony bod
ing or itaics). Th prcis dfinition of th .txt format is not spcifid, but
typicay matchs th format accptd by th systm trmina or simp txt di
tor. Fis with th .txt xtnsion can asiy b rad or opnd by any program t
hat rads txt and, for that rason, ar considrd univrsa (or patform indp
ndnt).

Th ACII charactr st is th most common format for Engish-anguag txt fi
s, and is gnray assumd to b th dfaut fi format in many situations. Fo
r accntd and othr non-ACII charactrs, it is ncssary to choos a charactr
ncoding. In many systms, this is chosn on th basis of th dfaut oca s
tting on th computr it is rad on. Common charactr ncodings incud IO 8859
-1 for many Europan anguags. Bcaus many ncodings hav ony a imitd rpr
toir of charactrs, thy ar oftn ony usab to rprsnt txt in a imitd s
ubst of human anguags. Unicod is an attmpt to crat a common standard for
rprsnting a known anguags, and most known charactr sts ar substs of t
h vry arg Unicod charactr st. Athough thr ar mutip charactr ncod
ings avaiab for Unicod, th most common is UTF-8, which has th advantag of
bing backwards-compatib with ACII: that is, vry ACII txt fi is aso a
UTF-8 txt fi with idntica maning. ystm Fi A systm fi is a computr
fi important to th oprating systm. Mor spcificay, it rfrs to th fi
s which ar usd to buid th oprating systm unning on a computr systm. Exa
mps of systm fis ar: command fi, Excutab fi, Dynamic Link aborator
y fi tc. Command Fi (.COM): Th command fi having fi nam xtnsion (.c
om) has bn usd in various computr systms for diffrnt purposs. Originay
, th trm stood for "Command fi" and was a txt fi containing commands to b
 issud to th oprating systm. In M-DO and compatib DOs, and in 8-bit C
P/M, a COM fi is a simp typ of xcutab fi. Th COM format is prhaps t
h simpst xcutab format of a; it contains no mtadata, ony cod and dat
a, and is oadd at offst 0x0100 of som sgmnt of mmory and xcutd. Bcaus
 of how th sgmntation mod works, thr is no nd for rocation. In Int
86(Eary vrsion of x86) CPU architctur, ony 65,536 byts of mmory coud b
addrssd (addrss rang 0x0000 to 0xFFFF). Undr CP/M, th first pag of this
mmory, from 0x0000 to 0x00FF was rsrvd for systm us, and any usr program
had to b oadd at xacty 0x0100 to b xcutd. COM fis fit this mod prf
cty. Not that thr was no possibiity of running mor than on program or co
mmand at a tim: th program oadd at 0x0100 was run, and no othr. Athough th
 fi format is th sam in M-DO and CP/M, this dos not man that CP/M progr
ams can b dircty xcutd undr M-DO or vic vrsa; M-DO COM fis contai
n x86 instructions, whi CP/M COM fis contain 8080, 8085 or Z80 instructions.
Additionay, M-DO COM fis oftn dpnd on oprating systm traps suppid
xcusivy by M-DO via intrrupt 21h. It is possib to construct a fat COM f
i which both procssor famiis can xcut. Fis may hav nams nding in .C
OM, but not b in th simp format dscribd abov; this is indicatd by a magi
c numbr at th start of th fi. For xamp, th COMMAND.COM fi in DR-DO 6
is actuay in DO xcutab format, indicatd by th first two byts bing MZ
(0x4D 0x5A). Undr CP/M 3, if th first byt of a COM fi is 0xC9 thn this in
dicats th prsnc of a 256-byt hadr; sinc 0xC9 corrsponds to th 8080 in
struction RET, this mans that th COM fi wi immdiaty trminat if run on
an arir vrsion of CP/M that dos not support this xtnsion. Excutab Fi
 (.EXE) EXE is th common finam xtnsion dnoting an xcutab fi (a pro
gram) in th OpnVM, DO, Microsoft Windows, RactO, and O/2 oprating systm
s. Bsids th xcutab program itsf, many EXE fis contain othr componnt
s cad rsourcs, such as bitmaps and icons which th xcutab program may u
s for its graphica usr intrfac. Th DO xcutab fi format diffrs from
th COM xcutab, which is imitd to sighty ss than 64 KB in siz and si
nc it acks rocation information, can ony contain on cod sgmnt. Th DO
xcutab hadr contains such rocation information, which aows mutip s
gmnts to b oadd at arbitrary mmory addrsss, and support xcutabs arg
r than 64 KB. Thr ar svra main EXE fi formats. (i) DO xcutab: Ths
can ony b idntifid by th ACII string "MZ" or th hxadcima 4D 5A at th
bginning of th fi (th "magic numbr"), athough, in fact, "ZM" or th hxa
dcima 5A 4D works as w.

Ths xcutabs can b run from DO, and most Windows vrsions can xcut th
m using a sort of muation. (ii) 16-bit Nw Excutab: Introducd with Mutita
sking M-DO 4.0, ths can b idntifid by th "NE" in ACII. Ths cannot b
run by any othr vrsion of DO but can b run by a Windows and O/2 vrsions.
(iii) Mixd 16/32-bit Linar Excutab: Introducd with O/2 2.0, ths can b
idntifid by th "LE" in ACII. This format is not usd for O/2 appications
anymor, but instad for VxD drivrs undr Windows 3.x and Windows 9x, and by so
m DO xtndrs. (iv) 32-bit Linar Excutab: Introducd with O/2 2.0, ths
can b idntifid by th "LX" in ACII. Ths can ony b run by O/2 2.0 and h
ighr. Thy ar aso usd by som DO xtndrs. (v) 32-bit Portab Excutab:
Introducd with Windows NT, ths ar th most compx and can b idntifid by
th "PE" in ACII. Ths can b run by a vrsions of Windows NT, and aso Win
dows 95 and highr, partiay aso in DO using HX DO Extndr. Thy ar aso u
sd in BO R3, howvr th format usd by BO somwhat vioats th PE spcifi
cation as it dosn't spcify a corrct subsystm. (vi) 64-bit Portab Excutab
: Introducd by 64-bit vrsions of Windows, ths ar PE fis with a CPU typ
corrsponding to a 64-bit instruction st such as x86-64 or IA-64. Ths can on
y b run by 64-bit ditions of Microsoft Windows, such as Windows XP 64-Bit Edit
ion or Windows rvr 2003 64-Bit Edition, running on machins with th CPU typ
spcifid in th fi. Dynamic Link Laboratory Fi(.DLL, .OCX, .DRV) Dynamic-
ink ibrary fi or DLL fi, is Microsoft's impmntation of th shard ibrar
y concpt in th Microsoft Windows and O/2 oprating systms. Ths ibraris u
suay hav th fi xtnsion DLL, OCX (for ibraris containing ActivX contro
s), or DRV (for gacy systm drivrs). Th fi formats for DLLs ar th sam
as for Windows EXE fis that is, Portab Excutab (PE) for 32-bit Windows, a
nd Nw Excutab (NE) for 16-bit Windows. As with EXEs, DLLs can contain cod,
data, and rsourcs, in any combination. It can aso hav icon ibraris, somti
ms having th xtnsion ICL, and font fis, having th xtnsions FON and FOT.

tructurd Fi
quntia Fi Dfinition: Whn rcords ar stord in scondary storag mdia
as pr th ordring of a sarch ky fid of vry rcords. Examp: fi: Cass
Grad Ro No. 001 002 003 Nam ourav Ganguy Ashok Mukhrj uman Gupta Grad
 A B B
Th fi CassGrad is a squntia fi whr ach rcord is ordrd on Ro No
. Raization of quntia fi in Computr: Though to crat and to accss any
data fi programming is rquird in any anguag but th undrying oprating
systm(O) has ony th ow v systm cas to crat and to accss fis in
scondary storag dvics, sinc O maintains bocks, custrs, sctors tc. in
fi aocation tab for providing spacs to crat any data fi. Thr ar fo
owing things to b rmmbrd aways to work with fi. 1) First of a a fi
must b opnd in workspac for ithr putting data into it or to rtriv data
out from th fi. Thr ar foowing mods on which a fi can b opnd. i)
Mod: Output: Which is ssntia to opn a fi at first tim cration.

ii) iii)
Mod: Input: Which is ssntia to opn a fi for rtriva of data. Mod: Inpu
t/Output : Which is ssntia for updation purpos.
Onc a data fi has bn cratd with Output mod and dumping of rords on it h
av bn don th fi must b cosd. Aftr cosing th fi if by mistak th
fi is ropnd in Output mod a th data writtn arir wi b ost. Thus,
to accss nxt th Input mod is ssntia. In C language the modes are represent
ed as: (i) Output: R (Read only) (ii) Input: A (Append only), W (Write only) (iii) Inp
ut/ Output:W+ (Read and write), R+ (Read and write), A+ (Append and write) Secondly, i
n C language File Pointer is very essential to keep track of positions of records as
bellow: Address 2200 2201 2202 2203 Record A A D T Pointer 2203 EOF 2200 2201
File pointer Start(BOF)
Index Sequential File The retrieval of a record from a sequential file, on avera
ge, requires traverse of half of the total file. This makes the enquiries not on
ly inefficientbut very time consuming for a large file. To improve this, a type
of indexing technique ia added to sequential file and is named as index sequenti
al file. Definition: A sequential file that is indexed for faster search is call
ed index sequential file. Example: Index for starting page numbers of a dictiona
ry file Words Starting with letters A B C D X Y Z Page # 3 42 86 158 807 809 812
An index is a set of <key, address> pairs. Indexing associates a set of objects
to a set of ordered quantities, which are usually smaller in number, giving us a
mechanism to search faster.Indexes are created from a sequential or sorted set
of primary keys from a sequential file. The indexes provides random access to th
e record fields of the file, while the sequential nature of the file provides ea
sy access to the subsequent records as well as sequential processing. Index can
be of three types: (iv) Implicit Index: (v) Limit Index (vi) Multilevel Index

15.4 Example Programs:


15.4.1 Non Structured file (Read and Write a Text File) #include<stdio.h> #inclu
de<conio.h> void fnReadFile(FILE*); void fnWriteFile(FILE*); void main(void) { F
ILE *fp1,*fp2; int Choice; clrscr(); while(1) { printf("\nMENU"); printf("\n1. R
ead from file"); printf("\n2. Write into file"); printf("\n3. Exit"); printf("\n
Enter your choise"); scanf("%d",&Choice); switch(Choice) { case 1: fp1=fopen("te
st1.txt","r"); fnReadFile(fp1); fclose(fp1); break; case 2: fp1=fopen("test1.txt
","a+"); fnWriteFile(fp1); fclose(fp1); break; case 3: exit(); } } getch(); } vo
id fnReadFile(FILE *Source) { char c; while((c=getc(Source))!=EOF) printf("%c",c
); } void fnWriteFile(FILE *Source) { char c; while((c=getche())!=q) putc(c,So
urce);

} Structured File (Read and Write a Sequential File) #include<stdio.h> #include<


conio.h> struct student { int iRoll; char cName[50]; char cStream[20]; }; typede
f struct student student; void fnReadFile(FILE*); void fnWriteFile(FILE*); void
main(void) { FILE *fp1,*fp2; int Choice; clrscr(); while(1) { printf("\nMENU");
printf("\n1. Read from file"); printf("\n2. Write into file"); printf("\n3. Exit
"); printf("\nEnter your choise"); scanf("%d",&Choice); switch(Choice) { case 1:
fp1=fopen("test1.txt","r"); fnReadFile(fp1); fclose(fp1); break; case 2: fp1=fo
pen("test1.txt","a+"); fnWriteFile(fp1); fclose(fp1); break; case 3: exit(); } }
} void fnReadFile(FILE *Source) { student s; while(fread(&s,sizeof(student),1,S
ource)) printf("\n%d\t%s\t%s",s.iRoll,s.cName,s.cStream); } void fnWriteFile(FIL
E *Source)

{ student s; printf("\nEnter Students roll, name and stream"); fflush(stdin); s


canf("%d",&s.iRoll); fflush(stdin); gets(s.cName); fflush(stdin); gets(s.cStream
); fwrite(&s,sizeof(student),1,Source); }
15.4 MCQ Chapter 15
1. Six files F1, F2, F3 , F4, F5 and F6 have 100, 200, 50, SO, 120, 150 number o
f records respectively. In what order should they be stored so as to optimize ac
cess time? Assume each file is accessed with the same frequency. (a) F3, F4, F1,
F5, F6, F2 (b) F2, F.6, F5, F1, F4, F3 (c) F1, F2, F3, F4, F5, F6 (d) Ordering
is immaterial as all files are accessed with the same frequency. 2. Pick the cor
rect statements. (a) Sequential file organization is suitable for batch processi
ng. (b) Sequential file organization is suitable for interactive processing. (c)
Indexed sequential file organization supports both batch and interactive proces
sing. (d) Relative file cant be accessed sequentially. 3. Which of the followin
g file organizations is preferred for secondary key processing? (a) Indexed sequ
ential file organization (b) Two
way linked list (c) Inverted file organization
(d) Sequential file organization
Solutions:
1. a 2. a,c 3. c
Exercise Chapter 15
1. Discuss the differences between the following file organizations: (a) (i) Seq
uential (ii) Index sequential (b) (i) Text (ii) System (c) (i) Command file (ii)
Executable file Compare their storage and access efficiencies. State one applic
ations o each file organisations. 2. What is index sequential file organisations
? What are the advantages and disadvantages of index sequential files?

3. Write a C program to append some text after rhe contents of a simple text fil
e text.txt. 4. Give algorithms for insertion and deletion records from a Sequentia
l file. 5. What is index? What are the various types of indexing? State the adva
ntages of using indexing over a sequential file. Can this indexing be used in no
n structured file?
VARIOUS QUESTIONS ON DATA STRUCTURE AND ALGORITHM

(As because size of interger datatype in different C compiler is different, we h


ave used size_t instead of int datatype. For simplicity Let size_t as int dataty
pe with 4 byte size wherever mentioned) 1. Describe one good method for precisel
y specifying what a function must do, without indicating how the function accomp
lishes its work. Provide an example, using a small function. 2. What is a precon
dition? What is a postcondition? 3. Its recommended that the precondition be ch
ecked at the start of a function. Whats a good approach if a function discovers
that its precondition is not true? 4. Is it always possible for a function to c
heck that its precondition is true? 5. Suppose that you accidently call a correc
tly implemented function, but the precondition is false. Is the function guarant
eed to halt with a nice message? Is the function allowed to erase everything on
your hard drive? 6. Write the first few lines of this function so that it uses t
he assert facility to check its precondition: void exam(int i) // Precondition:
i is not equal to 42. ... 7. Give a concise formula that gives the approximate n
umber of digits in a positive integer. The integer is written in base 10. 8. Why
is the order of an algorithm generally more important than the speed of the pro
cessor? 9. Convert each time formula to the best possible big
O notation. Do not
include any spurious constants in your big
O answer. Time Formula 10n 2n 3 times
log (base 2) of n 2n + 10n 10. Write the simplest big
O expression to describe t
he number of operations required for the following algorithm: for (i = 1; i < N;
++i) { ...statements that require exactly i operations... } 11. You are at a co
mputer science cocktail party and you meet a student who has just started workin
g with a debugger. With about three or four sentences, explain the basic feature
s of your debugger and how they help you find bugs. 12. Suppose that p is an int
variable. Write several lines of code that will make p point to an array of 100
integers, place the numbers 0 through 99 into the array components, and return
the array to the heap. Do not use malloc. 13. What happens if you call new but t
he heap is out of memory?

14. Draw a picture of memory after these statements: int i = 42; int k = 80; int
* p1; int* p2; p1 = &i; p2 = &k; 15. Suppose that we execute the statements from
the previous question, and then we execute these statements: *p1 = *p2; Draw a
picture of memory after this additional statement. 16. Draw a picture of memory
after these statements: int i = 42; int k = 80; int* p1; int* p2; p1 = &i; p2 =
&k; p1 = p2; 17. Here is a function prototype: void exam(const double data[]); W
rite two or three sentences to tell all the information that you know about the
parameter. 18. Consider the following prototype: function foo (const int * p); W
hat restriction does the const keyword provide within the implementation of foo?
18. Consider a bag structure that stores the items in a dynamic array. Use an e
xample with pictures to explain what goes wrong if the automatic assignment oper
ator is used for this bag. 19. Consider the bag from Question no 18 (using a dyn
amic array). If the insert function is activated, and the bag is full, then the
bag is resized with the statement: reserve(used + 1); Describe a problem with th
is approach, and provide a better solution. 20. Consider the bag from Question n
o 18 (using a dynamic array). The pointer to the dynamic array is called data, a
nd the size of the dynamic array is stored in a private member variable called c
apacity. Write the following new member function: void bag::triple_capacity( ) /
/ Postcondition: The capacity of the bags dynamic array has been // tripled. Th
e bag still contains the same items that it previously // had. Do not use the re
serve function, do not use realloc, and do not cause a heap leak. Do make sure t
hat both data and capacity have new values that correctly indicate the new large
r array. 21. Implement functions to meet the following specificaions. In each ca
se, you should make an appropriate choice for the kind of parameter to use A. A
void function with one parameter (a polynomial p). The function prints the value
of p evaluated at x=1, x=2, x=3,..., up to x=10.

B. A void function with one parameter (a polynomial p). The function deletes the
largest term in p, and this change should affect the actual argument. 22. This
question is relevant if you implemented the polynomial class with a dynamic arra
y. Which of the polynomial operators needed a nested loop in its implementation?
23. This question is relevant if you implemented the polynomial class with a dy
namic array. Draw a picture of the values in the first five elements of your dyn
amic array and tell me the value of the current degree after these statements: p
olynomial p(3); p.assign_coef(4.1, 4); p.assign_coef(2.1, 2); 24. Suppose that a
main function has executed the three statements shown in the previous problem.
Give an example of one statement that can now be executed by the main function,
causing the degree of p to drop to 2. 25. This question is relevant if you imple
mented a polynomial that included some calculus
based operations such as derivat
ive and integral. Write a new function that meets the following specification: d
ouble slope(const polynomial& p, double x) // POSTCONDITION: The return value is
equal to the slope of the // polynomial p, evaluated at the point x. 26. What i
s the one statement that can be used to insert a new node at the head of a linke
d list. Assume that the lists head_pointer is called head_ptr and the that the
data for the new node is called entry. 27. Suppose that p is a pointer to a node
in a linked list, and *p is not the tail node. What are the steps to removing t
he node after *p? Use one short English sentence for each step. 28. Suppose we a
re using the usual node definition (with member functions called data and link).
Your program is using a node* variable called head_ptr to point to the first no
de of a linked list (or head_ptr == NULL for the empty list). Write a few lines
of C++ code that will print all the double numbers on the list. 29. Suppose we a
re using the usual node definition (with member functions called data and link),
and that locate_ptr is pointing to a node in a linked list. Write a statement t
hat will make locate_ptr point to the next node in the list (if there is one). I
f there is no next node, then your statement should set locate_ptr to NULL. 30.
Implement the following function as a new function for the linked list toolkit.
(Use the usual node definition with member variables called data and link.) size
_t count_42s(const node* head_ptr); // Precondition: head_ptr is the head pointe
r of a linked list. // The list might be empty or it might be non
empty. // Post
condition: The return value is the number of occurrences // of 42 in the data fi
eld of a node on the linked list. // The list itself is unchanged. 31. Implement
the following function as a new function for the linked list toolkit. (Use the
usual node definition with member variables called data and link.) bool has_42(c
onst node* head_ptr); // Precondition: head_ptr is the head pointer of a linked
list. // The list might be empty or it might be non
empty. // Postcondition: The
return value is true if the list has at least // one occurrence of the number 4
2 in the data part of a node.

32. Implement the following function as a new function for the linked list toolk
it. (Use the usual node definition with member variables called data and link.)
bool all_42s(const node* head_ptr); // Precondition: head_ptr is the head pointe
r of a linked list. // The list might be empty or it might be non
empty. // Post
condition: The return value is true if every node in the // list contains 42 in
the data part. NOTE: If the list is empty, // then the function returns true. 33
. Implement the following function as a new function for the linked list toolkit
. (Use the usual node definition with member variables called data and link. The
data field is an int.) int sum(const node* head_ptr); // Precondition: head_ptr
is the head pointer of a linked list. // The list might be empty or it might be
non
empty. // Postcondition: The return value is the sum of all the data compon
ents // of all the nodes. NOTE: If the list is empty, the function returns 0. 34
. Implement the following function as a new function for the linked list toolkit
. (Use the usual node definition with member variables called data and link. The
data field is an int.) int product(const node* head_ptr); // Precondition: head
_ptr is the head pointer of a linked list. // The list might be empty or it migh
t be non
empty. // Postcondition: The return value is the product of all the dat
a components // of all the nodes. NOTE: If the list is empty, the function retur
ns 1. 35. Implement the following function as a new function for the linked list
toolkit. (Use the usual node definition with member variables called data and l
ink.) void list_tail_insert(node* head_ptr, const node::value_type& entry); // P
recondition: head_ptr is the head pointer of a non
empty // linked list. // Post
condition: A new node has been added at the tail end // of the list. The data in
the new node is taken from the // parameter called entry. 36. Implement the fol
lowing function as a new function for the linked list toolkit. (Use the usual no
de definition with member variables called data and link.) bool data_is_on(const
node* head_ptr, const node* p); // Precondition: head_ptr is the head pointer o
f a linked list // (which might be empty, or might be non
empty). The pointer p
// is a non
NULL pointer to some node on some linked list. // Postcondition: The
return value is true if the data in *p // appears somewhere in a data field of
a node in head_ptrs // linked list. Otherwise the return value is false. // Non
e of the nodes on any lists are changed. 37. Implement the following function as
a new function for the linked list toolkit. (Use the usual node definition with
member variables called data and link.) bool is_on(const node* head_ptr, const
node* p); // Precondition: head_ptr is the head pointer of a linked list // (whi
ch might be empty, or might be non
empty). The pointer p // is a non
NULL pointe
r to some node on some linked list.

// Postcondition: The return value is true if p actually points to // one of the


nodes in the head_ptrs linked list. For example, // p might point to the head
node of this list, or the second node, // or the third node, and so on. Otherwis
e the return value is // false. None of the nodes on any lists are changed. 38.
Implement the following function as a new function for the linked list toolkit.
Do not call any of the other toolkit functions from within your implementation.
(Use the usual node definition with member variables called data and link.) void
list_insert_zero(node* previous_ptr); // Precondition: previous_ptr is a pointe
r to a node on a linked list. // Postcondition: A new node has been added to the
list after // the node that previous_ptr points to. The new node contains 0. 39
. Suppose that p, q, and r are all pointers to nodes in a linked list with 15 no
des. The pointer p points to the first node, q points to the 8th node, and r poi
nts to the last node. Write a few lines of code that will make a new copy of the
list. You code should set THREE new pointers called x, y, and z so that: x poin
ts to the first node of the copy, y points to the 8th node of the copy, and z po
ints to the last node of the copy. Your code may NOT contain any loops, but it c
an use the toolkit functions. 40. Suppose that a_ptr and b_ptr are node pointers
. Write one clear sentence to tell me when the expression (a_ptr==b_ptr) will be
true. 41. Compare the worst
case big
O time analysis for these two functions: T
he insert function for the bag that is implemented using a fixed
sized array, an
d the insert function for the bag that is implemented using a linked list. 42. C
ompare the worst
case big
O time analysis for these two functions: The erase_one
function for the bag that is implemented using a fixed
sized array, and the era
se_one function for the bag that is implemented using a linked list. 43. Tell ab
out one of the sequence operations that is more efficient because the class keep
s a tail pointer as a private member variable. Provide a specific example showin
g why the operation would be less efficient without the tail pointer. 44. Tell a
bout one of the sequence operations that is easier to program because the class
keeps a precursor (rather than just a cursor). Provide a specific example showin
g why the operation would be harder to program without the precursor. 45. Compar
e the worst
case big
O time analysis for these two functions: The insert functio
n for the sequence that is implemented using a fixed
sized array, and the insert
function for the sequence that is implemented using a linked list. 46. Compare
the worst
case big
O time analysis for these two functions: The remove function
for the sequence that is implemented using a fixed
sized array, and the remove f
unction for the sequence that is implemented using a linked list. 47. Describe a
situation where storing items in an array is clearly better than storing items
on a linked list. 48. Consider the code below which is supposed to shift the val
ues from data[0] through data[n
1] rightward one position (so these values now r
eside in data[1] through data[n]).

size_t i; for (i = 0; i < n; ++i) data[i+1] = data[i]; There is a bug in the abo
ve code. Write one sentence to describe the bug and write new code that does the
job correctly. 49. Explain what modifications would be needed to make the paren
thesis matching algorithm check expressions with different kinds of parentheses
such as (), [] and {}s. 50. Complete the body of this function. You do not need
to check the precondition. You may use the stack template class. bool balanced(
const char p[ ], size_t n) // Precondition: p[0]...p[n
1] contains n characters,
each of which // is (, ), { or }. // Postcondition: The function return
s true if the characters form a // sequence of correctly balanced parentheses wi
th each ( matching // a ) and each { matching a }. Note that a sequence
such as // ( { ) } is NOT balanced because when we draw lines to match the // pa
rentheses to their partners, the lines cross each other. On the // other hand, (
{ } ) amd { ( ) } are both balanced. 51. The following code is going to be exec
uted with THREE pushes and ONE pop: stack<int> s; s.push(1); s.push(2); s.push(3
); s.pop( ); Suppose that s is represented by a partially filled array. Draw the
state of the elements of s after the above code: 52. Suppose that s in te above
question is represented by a linked list. Draw the state of the private member
variables of s after the above code: 53. Implement the following function. You m
ay use the stack template class and the stack operations of push, pop, peek, is_
empty, and size. You may also use cin.peek( ) and use "cin>>i" to read an intege
r. int evaluate_postfix_from_cin( ) // Precondition (Which is not checked): The
next input line of cin is a // properly formed postfix expression consisting of
integers, // the binary operations + and
, and spaces. // Postcondition: The fu
nction has read the next input line (including // the newline) and returned the
value of the postfix expression. { int i; stack<int> s; 54. Complete the body of
this function. Use a queue of characters to store the input line as it is being
read. size_t counter( ) // Precondition: There is a line of input waiting to be
read from cin.

// Postcondition: A line of input has been read from cin, up to but not // inclu
ding the newline character. The return value of the function // is the number of
times that the LAST character of the line appeared // somewhere in this line. /
/ EXAMPLE Input: ABBXDXXZX // The value returned by counter would be 4 for this
input since there // are 4 Xs in the input line. { size_t answer = 0; queue q;
55. I am going to execute this code with THREE inserts and ONE get_front: queue<
int> s; s.insert(1); s.insert(2); s.insert(3); s.get_front( ); Suppose that s is
represented by a circular array. Draw the state of the elemets of s after the a
bove code: 56. I am going to execute this code with THREE insert and ONE get_fro
nt: queue<int> s; s.insert(1); s.insert(2); s.insert(3); s.get_front( ); Suppose
that s is represented by a linked list. Draw the state of the elemets of s afte
r the above code: 57. Describe why it is a bad idea to implement a linked list v
ersion a queue which uses the head of the list as the rear of the queue. 58. Wri
te a recursive function that has one parameter which is a size_t value called x.
The function prints x asterisks, followed by x exclamation points. Do NOT use a
ny loops. Do NOT use any variables other than x. 59. Implement the following fun
ction. Do not use any local variables or loops. void pattern(unsigned int n) //
Precondition: n > 0; // Postcondition: The output consists of lines of integers.
The first line // is the number n. The next line is the number 2n. The next lin
e is // the number 4n, and so on until you reach a number that is larger than //
4242. This list of numbers is then repeated backward until you get back // to n
. /* Example output with n = 840: 840 1680 3360 6720 6720 3360 1680 840

60. Write a recursive function with two unsigned int parameters, m and n. The pr
econdition requires 0 <= m and m <= n. The function prints a line of m asterisks
, then a line of m+1 asterisks, and so on up to a line of n asterisks. Then the
same pattern is repeated backward: a line of n asterisks, then n
1, and so on do
wn to n. The only loop allowed in your implementation is a loop to print a line
of m asterisks. You may have two copies of this loop in different places of the
implementation. 61. This question involves a game with teddy bears. The game sta
rts when I give you some bears. You can then give back some bears, but you must
follow these rules (where n is the number of bears that you have): If n is even,
then you may give back exactly n/2 bears. If n is divisible by 3 or 4, then you
may multiply the last two digits of n and give back this many bears. (By the wa
y, the last digit of n is n%10, and the next
to
last digit is ((n%100)/10). If n
is divisible by 5, then you may give back exactly 42 bears. The goal of the gam
e is to end up with EXACTLY 42 bears. For example, suppose that you start with 2
50 bears. Then you could make these moves:

Start with 250 bears.

Since 250 i
s divisible by 5, you may return 42 of the bears, leaving you with 208 bears.

Since 208 is even, you may return half of the bears, leaving you with 104 bears.

Since 104 is even, you may return half of the bears, leaving you with 52 bear
s.

Since 52 is divisible by 4, you may multiply the last two digits (resulting
in 10) and return these 10 bears. This leaves you with 42 bears.

You have rea


ched the goal! 62. Write a recursive function to meet this specification: bool b
ears(int n) // Postcondition: A true return value means that it is possible to w
in // the bear game by starting with n bears. A false return value means that //
it is not possible to win the bear game by starting with n bears. // Examples:
// bear(250) is true (as shown above) // bear(42) is true // bear(84) is true //
bear(53) is false // bear(41) is false // Hint: To test whether n is even, use
the expression ((n % 2) == 0). 63. Write a recursive function with this prototyp
e: void permute(string first, string second) // Postcondition: The output consis
ts of lines of Strings. Each String // is made by writing some rearrangement of
first followed by all // of second. // For example, if first is "CAT" and second
is "MAN", then there will // be six lines of output: // CATMAN // ACTMAN // TCA
MAN // CTAMAN // ATCMAN // TACMAN Hints: The stopping case occurs when the lengt
h of first is zero (in which case the function prints second). Some string membe
r functions that will help you for a String s:

s[s.length( )
1] is a copy of the last character of s. s.length( ) is the leng
th of s. cout << s << endl; will print s. s = c + s; will insert the character c
at the front of s. s += c; will append the character c to the end of s. s.erase
(0, 1); will remove one character from the front of s. s.erase(s.length( )
1, 1)
will remove the last character from s. 64. Write a function with this prototype
: void numbers(ostream& outs, const string& prefix, unsigned int levels); The fu
nction prints output to the ostream outs. The output consists of the string pref
ix followed by "section numbers" of the form 1.1., 1.2., 1.3., and so on. The le
vels argument determines how may levels the section numbers have. For example, i
f levels is 2, then the section numbers have the form x.y. If levels is 3, then
section numbers have the form x.y.z. The digits permitted in each level are alwa
ys 1 through 9. As an example, if prefix is the string "THERBLIG" and levels
is 2, then the function would print 81 strings. In this case, the function star
ts by printing: THERBLIG1.1. THERBLIG1.2. THERBLIG1.3. and ends by printing: THE
RBLIG9.7. THERBLIG9.8. THERBLIG9.9. The stopping case occurs when levels reaches
zero (in which case the prefix is printed once by itself followed by nothing el
se). 65. Write a function with one positive int parameter called n. The function
will write 2^n
1 integers (where ^ is the exponentiation operation). Here are t
he patterns of output for various values of n: n=1: Output is: 1 n=2: Output is:
1 2 1 n=3: Output is: 1 2 1 3 1 2 1 n=4: Output is: 1 2 1 3 1 2 1 4 1 2 1 3 1 2
1 And so on. Note that the output for n always consists of the output for n
1,
followed by n itself, followed by a second copy of the output for n
1. 66. The f
irst step of the maze search algorithm was to step forward and write your name o
n the ground. What is the importance of writing your name on the ground? 67. Con
sider the following function: bool dead_end() // Postcondition: The return value
is true if the direction directly // in front is a dead end (i.e., a direction
that cannot contain the // tapestry). // Library facilities used: useful.h (from
Appendix 1). { return inquire("Are you facing a wall?") || inquire("Is your nam
e written in front of you?"); } Explain why the function dead_end sometimes asks
2 questions and sometimes asks only 1. 68. What two properties must a variant e
xpression have to guarantee that a recursive function terminates?

Here is a small binary tree: 14 / \ 2 11 /\ /\ 1 3 10 30 / / 7 40 Circle all the


leaves. Put a square box around the root. Draw a star around each ancestor of t
he node that contains 10. Put a big X through every descendant of the node the c
ontains 10. 69. Draw a full binary tree with at least 6 nodes. 70. Draw a comple
te binary tree with exactly six nodes. Put a different value in each node. Then
draw an array with six components and show where each of the six node values wou
ld be placed in the array (using the usual array representation of a complete bi
nary tree). 71. Write the structure for a new node definition that could be used
for a node in a tree where: (1) Each node contains int data, (2) Each node has
up to four children, and (3) Each node also has a pointer to its parent. Store t
he pointers to the children in an array of four pointers. 72. Draw a binary taxo
nomy tree that can be used for these four animals: Rabbit, Horse, Whale, Snake.
73. Using the binary_tree_node from the above example, write a function to meet
the following specification. Check as much of the precondition as possible. No r
ecursion is needed. void subswap(binary_tree_node<Item>* root_ptr) // Preconditi
on: root_ptr is the root pointer of a non
empty binary tree. // Postcondition: T
he original left subtree has been moved and is now the right // subtree, and the
original right subtree is now the left subtree. // Example original tree: Examp
le new tree: // 1 1 // /\ /\ // 2 3 3 2 // /\ /\ // 4 5 4 5 74. Here is a small
binary tree: 14 / \ 2 11 /\ /\ 1 3 10 30 / / 7 40 Write the order of the nodes v
isited in: A. An in
order traversal: B. A pre
order traversal: C. A post
order t
raversal: 75. Using the binary_tree_node from above example, Write a recursive f
unction to meet the following specification. You do not need to check the precon
dition.

void increase(binary_tree_node<Item>* root_ptr) // Precondition: root_ptr is the


root pointer of a binary tree. // Postcondition: Every node of the tree has had
its data increased by one. 76. Using the binary_tree_node from the above exampl
e, write a recursive function to meet the following specification. You do not ne
ed to check the precondition. size_t many_nodes(binary_tree_node<Item>* root_ptr
) // Precondition: root_ptr is the root pointer of a binary tree. // Postconditi
on: The return value is the number of nodes in the tree. // NOTES: The empty tre
e has 0 nodes, and a tree with just a root has // 1 node. 77. Using the binary_t
ree_node from the above example, write a recursive function to meet the followin
g specification. You do not need to check the precondition. int tree_depth(binar
y_tree_node<Item>* root_ptr) // Precondition: root_ptr is the root pointer of a
binary tree. // Postcondition: The return value is the depth of the binary tree.
// NOTES: The empty tree has a depth of
1 and a tree with just a root // has a
depth of 0. 78. Using the binary_tree_node from the above example, write a func
tion to meet the following specification. You do not need to check the precondit
ion. size_t count42(binary_tree_node<Item>* root_ptr) // Precondition: root_ptr
is the root pointer of a binary tree (but // NOT NECESSARILY a search tree). //
Postcondition: The return value indicates how many times 42 appears // in the tr
ee. NOTE: If the tree is empty, the function returns zero. 79. Using the binary_
tree_node from the above example, write a function to meet the following specifi
cation. You do not need to check the precondition. bool has_42(binary_tree_node<
Item>* root_ptr) // Precondition: root_ptr is the root pointer of a binary tree
(but // NOT NECESSARILY a search tree). // Postcondition: The return value indic
ates whether 42 appears somewhere // in the tree. NOTE: If the tree is empty, th
e function returns false. 80. Using the binary_tree_node from the above example,
write a function to meet the following specification. You do not need to check
the precondition. bool all_42(binary_tree_node<Item>* root_ptr) // Precondition:
root_ptr is the root pointer of a binary tree (but // NOT NECESSARILY a search
tree). // Postcondition: The return value is true if every node in the tree // c
ontains 42. NOTE: If the tree is empty, the function returns true. 81. Using the
binary_tree_node from the above example, write a recursive function to meet the
following specification. You do not need to check the precondition. int sum_all
(binary_tree_node<Item>* root_ptr) // Precondition: root_ptr is the root pointer
of a binary tree. // Postcondition: The return value is the sum of all the data
in all the nodes. // NOTES: The return value for the empty tree is zero.

82. Suppose that we want to create a binary search tree where each node contains
information of some data type called Item (which has a default constructor and
a correct value semantics). What additional factor is required for the Item data
type? 83. Suppose that a binary search tree contains the number 42 at a node wi
th two children. Write two or three clear sentences to describe the process requ
ired to delete the 42 from the tree. 84. Using the binary_tree_node from page 46
5, write a function to meet the following specification. You do not need to chec
k the precondition. Make the function as efficient as possible (do not visit nod
es unnecessarily): size_t count42(binary_tree_node<Item>* root_ptr) // Precondit
ion: root_ptr is the root pointer of a binary SEARCH tree. // Postcondition: The
return value indicates how many times 42 appears // in the tree. 85. Using the
binary_tree_node from the above example, write a function to meet the following
specification. You do not need to check the precondition. Make the function as e
fficient as possible (do not visit nodes unnecessarily): int max(binary_tree_nod
e<Item>* root_ptr) // Precondition: root_ptr is the root pointer of a nonempty b
inary SEARCH // tree. // Postcondition: The return value is the largest value in
the tree. 86. Using the binary_tree_node from the above example, write a functi
on to meet the following specification. You do not need to check the preconditio
n. void insert_one_42(binary_tree_node<Item>*& root_ptr) // Precondition: root_p
tr is the root pointer of a binary SEARCH tree. // Postcondition: One copy of th
e number 42 has been added to the binary // search tree. 87. Suppose that we wan
t to create a heap where each node contains information of some data type called
Item (which has a default constructor and a correct value semantics). What addi
tional factor is required for the Item data type? 88. A heap is a binary tree wh
ere the entries can be compared using the usual six comparison operations (that
form a total order semantics). Write the two rules that the binary tree must fol
low in order for the structure to actually be a heap. 89. Give two different rea
sons to explain why the following binary tree is not a heap: 91 / \ 77 46 / \ \
68 81 11
90. Draw a new heap that is created by inserting 82 into the following heap: 91
/ \ 77 66 / \ / \

68
1 3
11
91. Draw a new heap that is created by removing one item from the following heap
: 91 / \ 77 66 / \ / \ 68 1 3 11 92. Suppose that you are performing a reheapifi
cation downward. Write a precise condition that describes the situation that cau
ses the reheapification to stop. 93. Suppose that you are performing a reheapifi
cation upward. Write a precise condition that describes the situation that cause
s the reheapification to stop. 94. Suppose that a non
leaf node in a B
tree cont
ains 42 entries. How many children does the node have? 95. Draw an example of a
B
tree with four nodes and seven integer entries. The value of MINIMUM is 1 for
this tree. 96. Draw a new B
tree that is created by inserting 82 into the follow
ing B
tree. For this example, the minimum number of items in each node is 1. Not
e that the rightmost leaf starts with two entries, 71 and 93. 56 / \ 7 66 / \ /
\ 2 8 63 71 and 93 97. Draw a new B
tree that is created by deleting 63 from the
following B
tree. For this example, the minimum number of items in each node is
1. Note that the rightmost leaf starts with two entries, 71 and 93. 56 / \ 7 66
/ \ / \ 2 8 63 71 and 93 98. Suppose that a B
tree is declared so that MAXIMUM
(the maximum number of items in a node) is 84. What is the value of MINIMUM (the
minimum number of items in a non
root node)? Suppose that a B
tree is declared
so that MAXIMUM (the maximum number of items in a node) is 84. Write one clear s
entence to describe why each nodes data array is set up to hold up to 85 items
(one more than MAXIMUM). 99. Suppose that a and b are two positive integers and
n is some non
negative number. Write an equation to show the relationship betwee
n log base a of n and log base b of n. Give a derivation to show that the relati
onship is valid. 100. Here is an array with exactly 15 elements: 1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 Suppose that we are doing a serial search for an element. C
ircle any elements that will be found by examining two or fewer numbers from the
array.

101. Here is an array with exactly 15 elements: 1 2 3 4 5 6 7 8 9 10 11 12 13 14


15 Suppose that we are doing a binary search for an element. Circle any element
s that will be found by examining two or fewer numbers from the array. 102. Impl
ement the body of the following function using a binary search of the array. You
do not need to check the precondition. All your local variables must be size_t
variables. bool has_42(const int data[ ], size_t n) // Precondition: The element
s data[0]...data[n
1] are sorted from smallest // to largest. The value of n mig
ht be zero (indicating an empty // array). // Postcondition: A true return value
indicates that the number 42 appears in // data[0]...data[n
1]. A false return
value indicates that 42 doesnt appear. 103. Draw a hash table with open addressin
g and a size of 9. Use the hash function "k%9". Insert the keys: 5, 29, 20, 0, 2
7 and 18 into your table (in that order). 104. Suppose you are building an open
address hash table with double hashing. The hash table capacity is n, so that th
e valid hash table indexes range from 0 to n. Fill in the blanks: In order to en
sure that every array position is examined, the value returned by the second has
h function must be ________________________ with respect to n. 105. One way to e
nsure this good behavior is to make n be _______________, and have the return va
lue of the second hash function range from _________ to _________ (including the
end points). 106. Draw a hash table with chaining and a size of 9. Use the hash
function "k%9" to insert the keys 5, 29, 20, 0, and 18 into your table. 107. Su
ppose that I have the following record_type definition for a record in a hash ta
ble: struct record_type { int key; ... other stuff may also appear here ... }; T
he hash table uses open addressing with linear probing. The table size is a glob
al constant called CAPACITY. Locations of the table that have NEVER been used wi
ll contain the key
1. Locations of the table that were once used but are now va
cant will contain the key
2. All valid keys will be non
negative, and the hash
function is: size_t hash(int key) { return (key % CAPACITY); } Complete the impl
ementation of the following function. There is no need to check the precondition
, but your code must be as efficient as possible. bool key_occurs(const record_t
ype data[ ], int search_key) // Precondition: data[0]...data[CAPACITY
1] is an o
pen address hash table // as described above. // Postcondition: If search_key oc
curs as a key of a record in the table, then // the function returns true; other
wise the function returns false. 108. Suppose that an open
address hash table ha
s a capacity of 81 and it contains 81 elements. What is the tables load factor?
(An appoximation is fine.)

109. I plan to put 1000 items in a hash table, and I want the average number of
accesses in a successful search to be about 2.0 A. About how big should the arra
y be if I use open addressing with linear probing? NOTE: For a load factor of A,
the average number of accesses is generally (1+1/(1
A)). B. About how big should
the array be if I use chained hashing? NOTE: For a load factor of A, the averag
e number of accesses is generally (1+A/2). 110. Here is an array of ten integers
: 5 3 8 9 1 7 0 2 6 4 Draw this array after the FIRST iteration of the large loo
p in a selection sort (sorting from smallest to largest). 111. Here is an array
of ten integers: 5 3 8 9 1 7 0 2 6 4 Draw this array after the FIRST iteration o
f the large loop in an insertion sort (sorting from smallest to largest). This i
teration has shifted at least one item in the array! 112. Suppose that you are w
riting a program that has the usual selectionsort function available: void selec
tionsort(int data[ ], size_t n); Your program also has an integer array called x
, with 10 elements. Write two function calls: The first call uses selectionsort
to sort all of x; the second call uses selectionsort to sort x[3]..x[9]. 113. De
scribe a case where quicksort will result in quadratic behavior. 114. Here is an
array which has just been partitioned by the first step of quicksort: 3, 0, 2,
4, 5, 8, 7, 6, 9 Which of these elements could be the pivot? (There may be more
than one possibility!) 115. Give a concise accurate description of a good way fo
r quicksort to choose a pivot element. Your approach should be better than "use
the entry at location [0]". 116. Give a concise accurate description of a good w
ay for quicksort to improve its performance by using insertionsort. 117. Here is
an array of ten integers: 5 3 8 9 1 7 0 2 6 4 Suppose we partition this array u
sing quicksorts partition function and using 5 for the pivot. Draw the resultin
g array after the partition finishes. 118. Here is an array of ten integers: 5 3
8 9 1 7 0 2 6 4 Draw this array after the TWO recursive calls of merge sort are
completed, and before the final merge step has occured. 119. Write two or three
clear sentences to describe how a heapsort works. 120. Suppose that you are wri
ting a program that has these two functions available: int compare_ints(const vo
id* p1, const void* p2); // Precondition: p1 and p2 are really pointers to integ
ers. // Postcondition: The return value is: // (a) negative if *p1 < *p2 // (b)
zero if *p1 == *p2 // (c) positive if *p1 > *p2

void qsort( void* base, size_t n, size_t bytes, int compar(const void*, const vo
id*) ); // Same specification as the standard library qsort function. Your progr
am also has an integer array called x, with 10 elements. Write two function call
s: The first call uses qsort to sort all of x; the second call uses qsort to sor
t x[3]..x[9]. 121. Suppose that you implement quicksort nonrecursively using a s
tack, as in your last programming assignment. You use your algorithm to sort an
array of 100 items, and at the start of the final iteration of the while loop, t
he stack contains just two numbers: 10 (on top) and 90 (on bottom). Write one or
two clear sentences to describe which parts of the array are sorted at this poi
nt, and which parts of the array remain to be sorted. 122. Draw a directed graph
with five vertices and seven edges. Exactly one of the edges should be a loop,
and do not have any multiple edges. 123. Draw an undirected graph with five edge
s and four vertices. The vertices should be called v1, v2, v3 and v4

and there
must be a path of length three from v1 to v4. Draw a squiggly line along this pa
th from v1 to v4. 124. Draw the directed graph that corresponds to this adjacenc
y matrix: 0 1 2 3 0 | true false true false | 1 | true false false false | 2 | f
alse false false true | 3 | true false true false | 125. Draw the edge lists tha
t correspond to the graph from the previous question. 126. What are the benefits
of using an external iterator as opposed to an internal iterator? 127. How may
Djikstras algorithm be modified to determine if it is possible to get from a gi
ven vertex to all other vertices in the graph? 128. In Djikstras shortest path
algorithm, what technique is used to choose the next vertex to process?

You might also like