0% found this document useful (0 votes)
121 views

Bca 2 Sem Data Structure Notes

Uploaded by

mangeshdeo32
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
121 views

Bca 2 Sem Data Structure Notes

Uploaded by

mangeshdeo32
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 97

DATASTRUCTURES

Class Notes

BCA2nd SEM

SCHOOL OF COMPUTER SCIENCE

GYANVEERUNIVERSITY, SAGAR
DATASTRUCTURES
OBJECTIVES:
Thecourseshouldenablethestudentsto:
1. Demonstratefamiliaritywithmajoralgorithmsanddatastructures.
2. Choosetheappropriatedatastructureandalgorithmdesignmethodforapplication. aspecified
3. Determinewhichalgorithmordatastructuretouseindifferentscenarios.
4. Toimprovethelogicalability.

INTRODUCTIONTOALGORITHMSANDDATA
STRUCTURES
Algorithms:Definition,Properties,PerformanceAnalysis-SpaceComplexity,TimeComplexity,
AsymptoticNotations.Datastructures:Introduction, DataStructurestypes, DS Operations.
STACKSANDQUEUES
Stacks:Introduction,StackOperations,Applications:InfixtoPostfixConversion,Evaluationof
PostfixExpression.ueues:Introduction,Operationsonqueues,Circularqueues,Priorityqueues.
LINKEDLISTSAND APPLICATIONS
Linkedlists:Introduction,Singlylinkedlists,Circularlinkedlists,Doublylinkedlists,Multiply linked
lists, Applications: PolynomialRepresentation.ImplementationofStack and Queue using
linkedlist.
SORTINGANDSEARCHING
Sorting:Introduction,Selectionsort,Bubblesort,Insertionsort,Mergesort,Quicksort,Heap
Sort.Searching:Introduction,Linearsearch,Binarysearch,Fibonaccisearch.
TREESANDBINARYTREES
Trees:Introduction,Definitionandbasicterminologies,Representationoftrees.
BinaryTrees: BasicTerminologiesandTypes, BinaryTreeTraversals,BinarySearchTrees.
TextBooks:
1. G.A.VPAI,DataStructuresandAlgorithms,Concepts,TechniquesandApplications,
Volume1, 1stEdition, Tata McGraw-Hill, 2008.
2. RichardF.Gilberg&BehrouzA. Forouzan,DataStructures,PseudocodeApproachwith
C,2ndEdition,CengageLearningIndiaEdition,2007.
ReferenceBooks:
1. Langsam,M.J.Augenstein,A.M.Tanenbaum,DatastructuresusingCandC++,2nd
Edition, PHI Education, 2008.
2. SartajSahni,EllisHorowitz,Fundamentalsofat StructuresinC,2nd Edition,
Orientblackswan,2010.
WebReferences:
1. https://www.geeksforgeeks.org/data-structures/
2. https://www.programiz.com/dsa
3. https://www.w3schools.in/data-structures-tutorial/intro/
Outcomes:
At theendofthecoursestudentsableto
1. ApplyConceptsofStacks,Queues,LinkedLists.
2. DevelopProgramsfor SearchingandSorting, Trees.
3. Interpretconceptsoftrees.
4. DevelopprogramsforSortingandSearching.
INTRODUCTIONTOALGORITHMSANDDATASTRUCTURES
Definition: - An algorithm is a Step By Step process to solve a problem, where each step
indicates an intermediate task. Algorithm contains finite number of steps that leads to the
solution of the problem.
Properties/CharacteristicsofanAlgorithm:-
Algorithm has the following basic properties
 Input-Output:- Algorithm takes ‘0’ or more input and produces the required output.
This is the basic characteristic of an algorithm.
 Finiteness:-Analgorithmmustterminateincountablenumberofsteps.
 Definiteness:Each stepofanalgorithmmustbestatedclearlyandunambiguously.
 Effectiveness:Eachandeverystepinanalgorithmcanbeconvertedinto programming
language statement.
 Generality: Algorithm is generalized one. It works on all set of inputs and
providesthe required output. In other words it is not restricted to a single input
value.

CategoriesofAlgorithm:
Based on the different types of steps in an Algorithm, it can be divided into three
categories, namely
 Sequence
 Selectionand
 Iteration
Sequence: The steps described in an algorithm are performed successively one by one
without skipping any step.The sequence of steps defined in an algorithm should be simple
and easy to understand. Each instruction of such an algorithm is executed, because no
selection procedure or conditional branching exists in a sequence algorithm.
Example:
//addingtwonumbers
Step 1: start
Step 2: read a,b
Step 3: Sum=a+b
Step4:writeSum
Step 5: stop
Selection: The sequence type of algorithms are not sufficient to solve the problems, which
involves decision and conditions. In order to solve the problem which involve decision
making or option selection, we go for Selection type of algorithm. The general format of
Selection type of statement is as shown below:
if(condition)
Statement-1;
else
Statement-2;
The above syntax specifies that if the condition is true, statement-1 will be executed
otherwise statement-2 will be executed. In case the operation is unsuccessful. Then
sequence of algorithm should be changed/ corrected in such a way that the system will re-
execute until the operation is successful.

1
Iteration: Iteration type algorithms are used in solving the problems which involves
repetition of statement. In this type of algorithms, a particular number of statements are
repeated ‘n’ no. of times.
Example1:

Step 1 : start
Step2:readn
Step3:repeatstep4untiln>0 Step
4 : (a)r=n mod 10
(b) s=s+r
(c) n=n/10
Step 5 : write s
Step6: stop
PerformanceAnalysisanAlgorithm:
TheEfficiencyofanAlgorithmcanbemeasured bythefollowing metrics.
i. Time Complexity and
ii. SpaceComplexity.
i.Time Complexity:
The amount of time required for an algorithm to complete its execution is its time
complexity. An algorithm is saidto be efficient if it takes the minimum (reasonable) amount
of time to complete its execution.
ii. SpaceComplexity:
The amount of space occupied by an algorithm is known as Space Complexity. An algorithm
is said to be efficient if it occupies less space and required the minimum amount of time to
complete its execution.

1. WriteanalgorithmforrootsofaQuadraticEquation?
//RootsofaquadraticEquation
Step 1 : start
Step2: reada,b,c
Step3:if(a=0)thenstep4elsestep5
Step4:Write“Givenequationisa linearequation“ Step 5
:d=(b * b) _ (4 *a *c)
Step6:if (d>0)thenstep7 elsestep8
Step7:Write“RootsarerealandDistinct” Step
8:if(d=0) then step 9 else step 10
Step9:Write“Rootsarerealandequal”
Step 10: Write “ Roots are Imaginary”
Step 11: stop

2
2. Writeanalgorithmtofindthelargestamongthreedifferentnumbersenteredbyuser
Step1:Start
Step2:Declarevariablesa,bandc. Step
3: Read variables a,b and c.
Step4:Ifa>b
Ifa>c
Displayaisthelargestnumber. Else
Displayc isthelargest number.
Else
Ifb>c
Displaybisthelargestnumber. Else
Displaycisthegreatest number.
Step5:Stop

3. Writeanalgorithmtofindthe factorialofanumberenteredby user.


Step1:Start
Step2:Declarevariablesn,factorialandi.
Step3:Initializevariables
factorial←1
i←1
Step4:Readvalueofn
Step5:Repeatthe stepsuntili=n
:factorial←factorial*i
:i←i+1
Step6:Displayfactorial
Step 7: Stop

4. WriteanalgorithmtofindtheSimpleInterestforgivenTimeandRateofInterest.
Step1:Start
Step2:Read P,R,S,T.
Step3:CalculateS=(PTR)/100 Step
4: Print S
Step5:Stop

ASYMPTOTICNOTATIONS
Asymptotic analysis of an algorithm refers to defining the mathematical
boundation/framing of its run-time performance. Using asymptotic analysis, we can very
well conclude the best case, average case, and worst case scenario of an algorithm.
Asymptotic analysis is input bound i.e., if there's no input to the algorithm, it is concluded
to work in a constant time. Other than the "input" all other factors are consideredconstant.
Asymptoticanalysisreferstocomputing the runningtime ofanyoperationinmathematical
units of computation. For example, the running time of one operation is computed as f(n)
and may be for another operation it is computed as g(n2). This means the first operation
running time will increase linearly with theincrease in nand the running time of thesecond
operation will increase exponentially when nincreases. Similarly, the running time of both
operations will be nearly the same if n is significantly small.

3
Thetime requiredbyanalgorithm fallsunderthreetypes−
 BestCase−Minimumtimerequiredforprogramexecution.
 AverageCase−Averagetimerequired forprogramexecution.
 WorstCase−Maximumtimerequiredforprogramexecution.
AsymptoticNotations
Followingarethecommonlyusedasymptoticnotationstocalculatetherunningtime complexity
of an algorithm.
 Ο Notation
 ΩNotation
 θ Notation
BigOhNotation,Ο
The notation Ο(n) is the formal way to express the upper bound of an algorithm's running
time. It measures the worst case time complexity or the longest amount of time an
algorithm can possibly take to complete.

Forexample,forafunctionf(n)
Ο(f(n))={g(n):thereexistsc>0andn0suchthatf(n)≤c.g(n)foralln >n0.}
OmegaNotation,Ω
The notation Ω(n) is the formal way to express the lower bound of an algorithm's running
time. It measures the best case time complexity or the best amount of time an algorithm
can possibly take to complete.

Forexample,forafunctionf(n)
Ω(f(n))≥{g(n):thereexistsc>0andn0suchthatg(n)≤c.f(n)foralln >n0.}
ThetaNotation,θ
The notation θ(n) is the formal way to express both the lower bound and the upper bound
of an algorithm's running time. It is represented as follows −

4
θ(f(n))={g(n)ifand onlyifg(n)=Ο(f(n))andg(n)=Ω(f(n))foralln>n0.}

DATASTRUCTURES
Data may be organized in many different ways logical or mathematical model of a program
particularly organization of data. This organized data is called “Data Structure”.
Or
Theorganizedcollectionofdataiscalleda‘DataStructure’.

DataStructure=Organizeddata+Allowedoperations

Data Structure involves two complementary goals. The first goal is to identify and develop
useful, mathematical entities and operations and to determine what class of problems can
be solved by using these entities and operations. The second goal is to determine
representationforthoseabstractentities toimplementabstractoperations onthis concrete
representation.

Primitive Data structures are directly supported by the language ie;any operation is directly
performed in these data items.
Ex:integer,Character,Realnumbersetc.
Non-primitivedatatypesarenot definedbytheprogramminglanguage,butareinstead created
by the programmer.

5
Linear data structures organize their data elements in a linear fashion, where data
elements are attached one after the other. Linear data structures are very easy to
implement, since the memory of the computer is also organized in a linear fashion. Some
commonly used linear data structures are arrays, linked lists, stacks and queues.
In nonlinear data structures, data elements are not organized in a sequential
fashion. Data structures like multidimensional arrays, trees, graphs, tables and sets aresome
examples of widely used nonlinear data structures.
OperationsontheData Structures:
Followingoperationscanbe performedonthedatastructures:
1. Traversing
2. Searching
3. Inserting
4. Deleting
5. Sorting
6. Merging
1. Traversing-Itisusedtoaccesseachdataitemexactlyoncesothatitcanbeprocessed.
2. Searching-Itisusedtofindoutthelocationofthedataitemifitexistsinthegiven collection of data
items.
3. Inserting-Itisusedtoadd anewdataitemin thegivencollectionof dataitems.
4. Deleting-Itisusedtodeleteanexistingdataitemfromthegivencollectionofdataitems.
5. Sorting-It is used to arrange the data items in some order i.e. in ascending or descending
order in case of numerical data and in dictionary order in case of alphanumeric data.
6. Merging-Itisusedtocombinethedataitemsoftwosortedfilesintosinglefileinthe sorted form.

6
STACKS AND
QUEUES

STACKS
A Stack is linear data structure. A stack is a list of elements in which an element may be
inserted or deleted only at one end, called the top of the stack. Stack principle is LIFO (last
in,firstout). Whichelementinserted lastonto thestackthatelementdeletedfirstfromthe stack.

As the items can be added or removed only from the top i.e. the last item to be added to a
stack is the first item to be removed.

Reallifeexamplesofstacksare:

Operationson stack:

Thetwobasic operationsassociatedwithstacksare:
1. Push
2. Pop

Whileperformingpushandpopoperationsthefollowingtestmustbeconductedonthe stack.
a) Stackisemptyornot b)stackisfullor not

1. Push: Push operation is used to add new elements in to the stack. At the time of addition
first check the stack is full or not. If the stack is full it generates an error message "stack
overflow".

2. Pop:Pop operation is usedto deleteelementsfromthe stack.Atthe time of deletion first


check the stack is empty or not. If the stack is empty it generates an error message "stack
underflow".

All insertions and deletions take place at the same end, sothe last element added to
the stack will be the first element removed from the stack. When a stack is created, thestack
base remains fixed while the stack top changes as elements are added and removed.
Themostaccessibleelement isthe topandthe leastaccessibleelement isthe bottom ofthe
stack.

7
RepresentationofStack(or)Implementationofstack:
Thestackshouldbe representedintwoways:
1. Stackusing array
2. Stackusinglinkedlist

1. Stackusing array:
Let us consider a stack with 6 elements capacity. This is called as the size of the stack. The
number of elements to be added should not exceed the maximum size of the stack. If we
attempt toaddnew element beyond the maximum size,we will encountera stack overflow
condition. Similarly, you cannot remove elements beyond the base of the stack. If such isthe
case, we will reach a stack underflow condition.

1. push():When an element is added to a stack, the operation is performed by push(). Below


Figure shows the creation of a stack and addition of elements using push().

Initially top=-1, we can insert an element in to the stack, increment the top value i.e
top=top+1. We can insert an element in to the stack first check the condition is stack is full
or not. i.e top>=size-1. Otherwise add the element in to the stack.

voidpush() Algorithm:Procedureforpush():
{
intx; Step1:START
if(top>=n-1) Step2:iftop>=size-1then
{ Write“StackisOverflow” Step
printf("\n\nStack 3: Otherwise
Overflow.."); :readdatavalue‘x’
return; :top=top+1;
} :stack[top]=x;
else Step4: END
{
printf("\n\nEnterdata:");
scanf("%d", &x);
stack[top] = x;
top = top + 1;
printf("\n\nDataPushedinto
the stack");
}
}

8
2. Pop(): When an element is taken off from the stack, the operation is performed by pop().
Below figure shows a stack initially withthree elements andshows the deletion of elements
using pop().

Wecaninsertanelementfromthestack,decrementthetopvaluei.etop=top-1.
Wecan deleteanelementfromthestackfirstchecktheconditionisstackisemptyornot.
i.etop==-1.Otherwiseremovetheelementfrom thestack.

Voidpop() Algorithm:procedurepop():
{ Step1:START
If(top==-1) Step2:iftop==-1then
{ Write“StackisUnderflow” Step
Printf(“StackisUnderflow”); 3: otherwise
} :print“deletedelement”
else :top=top-1;
{ Step4: END
printf(“Deletedata%d”,stack[top]);
top=top-1;
}
}

3. display(): This operation performed display the elements in the stack. We display the
element in the stack check the condition is stack is empty or not i.e top==-1.Otherwise
display the list of elements in the stack.

9
voiddisplay() Algorithm:procedurepop():
{ Step1:START
If(top==-1) Step2:iftop==-1then
{ Write“StackisUnderflow” Step
Printf(“StackisUnderflow”); 3: otherwise
} :print“Displayelementsare”
else : for top to 0
{ Print‘stack[i]’
printf(“Displayelementsare:); Step4: END
for(i=top;i>=0;i--)
printf(“%d”,stack[i]);
}
}

Sourcecodeforstackoperations,usingarray:

#include<stdio.h>
#inlcude<conio.h>
intstack[100],choice,n,top,x,i;
void push(void);
void pop(void);
voiddisplay(void);
int main()
{
//clrscr();
top=-1;
printf("\nEnterthesizeofSTACK[MAX=100]:");
scanf("%d",&n);
printf("\n\tSTACKOPERATIONSUSING ARRAY");
printf("\n\t ");
printf("\n\t1.PUSH\n\t2.POP\n\t3.DISPLAY\n\t4.EXIT"); do
{
printf("\nEntertheChoice:");
scanf("%d",&choice);
switch(choice)
{
case1:
{
push();
break;
}
case2:
{
pop();
break;
}
case3:
{

10
display();
break;
}
case4:
{
printf("\n\tEXITPOINT");
break;
}
default:
{
printf("\n\tPleaseEnteraValidChoice(1/2/3/4)");
}

}
}
while(choice!=4);
return 0;
}
voidpush()
{
if(top>=n-1)
{
printf("\n\tSTACKisoverflow");

}
else
{
printf("Enteravaluetobepushed:");
scanf("%d",&x);
top++;
stack[top]=x;
}
}
voidpop()
{
if(top<=-1)
{
printf("\n\tStackisunder flow");
}
else
{
printf("\n\tThepoppedelementsis%d",stack[top]);
top--;
}
}
voiddisplay()
{
if(top>=0)
{

11
printf("\nTheelementsinSTACK\n");
for(i=top; i>=0; i--)
printf("\n%d",stack[i]);
printf("\nPressNextChoice");
}
else
{
printf("\nTheSTACKis empty");
}

2. StackusingLinkedList:
We can represent a stack as a linked list. In a stack push and pop operations are performed
at one end called top. We can perform similar operations at one end of list usingtop pointer.
The linked stack looks as shown in figure.

Applicationsofstack:
1. Stackisusedbycompilerstocheckforbalancingofparentheses,bracketsandbraces.
2. Stackisusedtoevaluateapostfixexpression.
3. Stackisusedtoconvertaninfixexpressionintopostfix/prefixform.
4. In recursion, all intermediate arguments and return values are stored on the processor’s
stack.
5. During a function call the return address and arguments are pushed onto a stack and on
return they are popped off.

ConvertingandevaluatingAlgebraicexpressions:
An algebraic expression is a legal combination of operators and operands. Operand is the
quantityonwhichamathematicaloperationis performed.Operandmaybe avariable likex, y, z
or a constant like 5, 4, 6 etc. Operator is a symbol which signifies a mathematical or logical
operation between the operands. Examples of familiar operators include +, -, *, /, ^ etc.

12
An algebraic expression can be represented using three different notations. They are infix,
postfix and prefix notations:
Infix:Itistheformofanarithmeticexpressioninwhichwefix(place)thearithmetic operator in
between the two operands.
Example:A+B
Prefix:Itistheformofanarithmeticnotationinwhichwefix(place)thearithmeticoperator before
(pre) its two operands. The prefix notation is called as polish notation.
Example:+AB

Postfix: It is the form of an arithmetic expression in which we fix (place) the arithmetic
operator after(post) its twooperands. The postfix notation is calledas suffix notation andis
also referred to reverse polish notation.
Example:AB+
Conversionfrominfixtopostfix:
Proceduretoconvertfrominfixexpressiontopostfixexpressionisasfollows:
1. Scanthe infixexpressionfromleftto right.
2. a)Ifthescanned symbolisleftparenthesis,pushitontothestack.
b) If the scanned symbol is an operand, then place directly in the postfix expression
(output).
c) If the symbol scanned is a right parenthesis, then go on popping all the items from the
stack and place them in the postfix expression till we get the matching left parenthesis.
d) If the scanned symbol is an operator, then go on removing all the operators from the
stack and place them in the postfix expression, if and only if the precedence of the
operator which is on the top of the stack is greater than (or greater than or equal) to the
precedence of the scanned operator and push the scanned operator onto the stack
otherwise, push the scanned operator onto the stack.
Thethreeimportantfeaturesofpostfixexpressionare:
1. Theoperandsmaintainthesameorderasintheequivalentinfixexpression.
2. Theparenthesesarenot neededtodesignatetheexpressionunambiguously.
3. Whileevaluatingthepostfixexpressionthepriorityoftheoperatorsisnolonger relevant.

We consider five binary operations: +, -, *, / and $ or ↑ (exponentiation). For these binary


operations, the following in the order of precedence (highest to lowest):

13
Evaluationofpostfixexpression:
Thepostfixexpressionisevaluated easilybythe useofastack.
1. Whenanumberisseen,itispushedontothestack;
2. Whenanoperatorisseen,theoperatorisappliedtothetwonumbersthatare popped from
the stack and the result is pushed onto the stack.
3. Whenanexpressionisgiveninpostfixnotation,thereisnoneedtoknowany precedence
rules; this is our obvious advantage.

14
15
QUEUE
A queue is linear data structure and collection of elements. A queue is another special kind
of list, where items are inserted at one end called the rear and deleted at the other end
called the front. The principle of queue is a “FIFO” or “First-in-first-out”.
Queue is anabstract data structure. A queue is a useful data structure in programming. It is
similarto the ticketqueueoutside acinemahall,wherethe firstpersonenteringthe queue is
the first person who gets the ticket.
A real-world example of queue can be a single-lane one-way road, where the vehicle enters
first, exits first.

More real-world examples can be seen as queues at the ticket windows and bus-stops and
our college library.

The operations for a queue are analogues to those for a stack; the difference is that the
insertions go at the end of the list, rather than the beginning.
Operationson QUEUE:
Aqueueisanobjectormorespecificallyanabstractdatastructure(ADT)thatallowsthe following
operations:
 Enqueueorinsertion: whichinsertsanelementattheendofthequeue.
 Dequeueordeletion:whichdeletesanelementatthestartofthequeue.
Queue operations work as follows:
1. Twopointerscalled FRONTand REAR areusedtokeeptrackofthefirstandlast elements in
the queue.
2. Wheninitializingthequeue,wesetthevalueof FRONTandREARto 0.
3. Onenqueinganelement,weincreasethevalueof REAR indexandplacethenew element
in the position pointed to by REAR.
4. On dequeueing an element, we return the value pointed to by FRONTand increase
the FRONT index.
5. Beforeenqueing,wecheckifqueueisalready full.
6. Beforedequeuing,wecheck ifqueueisalreadyempty.
7. Whenenqueingthefirstelement,wesetthevalueof FRONTto 1.
8. Whendequeingthelastelement,weresetthevaluesofFRONTandREARto0.

16
RepresentationofQueue(or)ImplementationofQueue:
Thequeue canberepresentedintwoways:
1. Queueusing Array
2. QueueusingLinkedList
1. QueueusingArray:
Letusconsideraqueue,whichcanholdmaximumoffiveelements.Initiallythequeueis empty.

Now,insert11tothe queue.Thenqueuestatuswillbe:

Next,insert22tothequeue.Thenthe queuestatusis:

Againinsertanotherelement33tothequeue.Thestatusofthequeueis:

Now, delete an element. The element deleted is the element at the front of the
queue.Sothe status of the queue is:

Again,deleteanelement.The elementtobedeletedisalways pointedtobytheFRONT pointer. So,


22 is deleted. The queue status is as follows:

Now,insertnewelements44and55intothequeue.Thequeuestatusis:

17
Next insert another element, say 66 to the queue. We cannot insert 66 to the queue as the
rear crossed the maximum size of the queue (i.e., 5). There will be queue full signal. The
queue status is as follows:

Now it is not possible toinsert an element 66eventhoughthere are twovacant positions in


the linear queue. To overcome this problem the elements of the queue are to be shifted
towards the beginning of the queue so that it creates vacant position at the rear end. Then
the FRONT and REAR are to be adjusted properly. The element 66 can be inserted at therear
end. After this operation, the queue status is as follows:

This difficulty canovercome ifwe treat queue positionwithindex 0as a positionthat comes
after position with index 4 i.e., we treat the queue as a circular queue.

Queueoperationsusingarray:
a.enqueue()orinsertion():whichinsertsanelementattheendofthequeue.
voidinsertion() Algorithm:Procedureforinsertion():
{ Step-1:START
if(rear==max) Step-2:ifrear==maxthen
printf("\nQueueisFull"); else Write‘Queueisfull’
{ Step-3: otherwise
printf("\nEnterno%d:",j++); 3.1:readelement‘queue[rear]’
scanf("%d",&queue[rear++]); Step-4:STOP
}
}

b.dequeue()ordeletion():whichdeletesanelementatthestartofthequeue.
voiddeletion() Algorithm:procedurefordeletion():
{ Step-1:START
if(front==rear) Step-2: if front==rear then
{ Write’Queueisempty’
printf("\nQueueisempty"); Step-3:otherwise
} 3.1:printdeletedelement
else Step-4:STOP
{
printf("\nDeletedElement is
%d",queue[front++]);
x++;
}}

18
c.dispaly():whichdisplaysanelementsinthe queue.
voiddeletion() Algorithm:procedurefordeletion():
{ Step-1:START
if(front==rear) Step-2: if front==rear then
{ Write’Queueisempty’
printf("\nQueueisempty"); Step-3:otherwise
} :fori=fronttorearthen
else :print‘queue[i]’
{ Step-4:STOP
for(i=front;i<rear;i++)
{
printf("%d",queue[i]);
printf("\n");
}
}
}

2. QueueusingLinked list:
We can represent a queue as a linked list. Ina queue data is deleted from the front endand
insertedatthe rearend.We canperformsimilaroperations onthe twoends ofalist.Weuse two
pointers front and rear for our linked queue implementation.
Thelinkedqueue looksasshowninfigure:

ApplicationsofQueue:
1. ItisusedtoschedulethejobstobeprocessedbytheCPU.
2. When multiple users send print jobs to a printer, each printing job is kept in the printing
queue. Then the printer prints those jobs according to first in first out (FIFO) basis.
3. Breadthfirstsearchusesaqueuedatastructuretofindan elementfromagraph.

19
CIRCULARQUEUE
A more efficient queue representation is obtained by regarding the array Q[MAX] ascircular.
Any number of items could be placed on the queue. This implementation of aqueue is called
a circular queue because it uses its storage array as if it were a circle instead of a linear list.
Thereare twoproblemsassociatedwithlinearqueue.Theyare:

 Time consuming: linear time to be spent in shifting the elements to the beginning of
the queue.
 Signalingqueuefull:evenifthequeueishavingvacantposition. For
example, let us consider a linear queue status as follows:

Next insert another element, say 66 to the queue. We cannot insert 66 to the queue as the
rear crossed the maximum size of the queue (i.e., 5). There will be queue full signal. The
queue status is as follows:

This difficulty can be overcome if we treat queue position with index zero as a position that
comes after position with index four then we treat the queue as a circular queue.
In circular queue if we reach the end for inserting elements to it, it is possible to insert new
elements if the slots at the beginning of the circular queue are empty.
RepresentationofCircularQueue:
Let us consider a circular queue, which can hold maximum (MAX) of six elements.
Initiallythe queue is empty.

Now,insert11tothecircularqueue.Thencircularqueuestatuswillbe:

20
Insertnewelements22,33,44and55intothecircularqueue.Thecircularqueuestatusis:

Now,deleteanelement.Theelementdeletedistheelementatthefrontofthecircular queue. So,


11 is deleted. The circular queue status is as follows:

Again,deleteanelement.TheelementtobedeletedisalwayspointedtobytheFRONT pointer. So,


22 is deleted. The circular queue status is as follows:

Again,insertanotherelement66tothecircularqueue.Thestatusofthecircularqueueis:

21
Now,insertnewelements77and88intothecircularqueue.Thecircularqueuestatusis:

Now,ifweinsertanelementtothecircularqueue,asCOUNT=MAXwecannotaddthe element to
circular queue. So, the circular queue is full.

OperationsonCircularqueue:

a.enqueue() orinsertion():This functionis usedto insert anelement intothecircularqueue. In a


circular queue, the new element is always inserted at Rear position.

voidinsertCQ() Algorithm:procedureofinsertCQ():
{
int Step-1:START
data;if(count== Step-2:ifcount==MAXthen
MAX) Write“Circularqueueisfull”
{ Step-3:otherwise
printf("\nCircularQueueisFull"); :readthedataelement
} :CQ[rear]=data
else :rear=(rear+1)%MAX
{ :count=count+1
printf("\nEnterdata:"); Step-4:STOP
scanf("%d", &data);
CQ[rear] = data;
rear=(rear+1)%MAX; count
++;
printf("\nDataInsertedintheCircular Queue
");
}
}

22
b.dequeue()ordeletion():Thisfunctionisusedtodeleteanelementfromthecircular queue. In a
circular queue, the element is always deleted from front position.
voiddeleteCQ() Algorithm:procedureofdeleteCQ():
{
if(count==0) Step-1:START
{ Step-2:ifcount==0then
printf("\n\nCircularQueueisEmpty.."); Write“Circularqueueisempty”
} Step-3:otherwise
else :printthe deletedelement
{ :front=(front+1)%MAX
printf("\nDeletedelementfromCircular :count=count-1
Queue is %d ", CQ[front]); Step-4:STOP
front=(front+1)%MAX; count --
;
}
}

c.dispaly():Thisfunctionisusedtodisplaythelistofelementsinthecircular queue.
voiddisplayCQ() Algorithm:procedureofdisplayCQ():
{
int i, j; Step-1:START
if(count==0) Step-2:ifcount==0then
{ Write“Circularqueueisempty”
printf("\n\n\tCircularQueueisEmpty"); Step-3:otherwise
} :printthelistofelements
else :fori=fronttoj!=0
{ :printCQ[i]
printf("\nElementsinCircularQueueare: "); :i=(i+1)%MAX
j=count; Step-4:STOP
for(i=front;j!=0; j--)
{
printf("%d\t",CQ[i]);
i = (i + 1) % MAX;
}
}
}

Deque:
Inthe preceding sectionwe saw that a queue in whichwe insert items at one endand from
which we remove items at the other end. In this section we examine an extension of the
queue, which provides a means to insert and remove items at both ends of the queue. This
datastructure isadeque.Theworddequeisanacronymderivedfrom double-endedqueue. Below
figure shows the representation of a deque.

23
dequeprovidesfouroperations.BelowFigure showsthebasicoperationsonadeque.
• enqueue_front:insertanelementatfront.
• dequeue_front:deleteanelementatfront.
• enqueue_rear:insertelementatrear.
• dequeue_rear:deleteelementat rear.

Therearetwovariationsofdeque.Theyare:
• Inputrestricteddeque(IRD)
• Outputrestricteddeque (ORD)
An Input restricted deque is a deque, which allows insertions at one end but allowsdeletions
at both ends of the list.
An output restricted deque is a deque, which allows deletions at one end but allows
insertions at both ends of the list.
PriorityQueue:
A priority queue is a collection of elements such that each element has been assigned a
priority. We can insert an element in priority queue at the rare position. We can delete an
element from the priority queue based on the elements priority and such that the order in
which elements are deleted and processed comes from the following rules:

1. Anelementofhigherpriorityisprocessedbeforeanyelementoflowerpriority.
2. Twoelementswithsame priorityare processedaccordingtothe orderinwhichtheywere
added to the queue. It follows FIFO or FCFS(First ComesFirst serve) rules.

24
We always remove an element with the highest priority, which is given by the minimal
integer priority assigned.

A prototype of a priority queue is time sharing system: programs of high priority are
processed first, and programs with the same priority form a standard queue. An efficient
implementation for the Priority Queue is to use heap, which in turn can be used for sorting
purpose called heap sort

Priorityqueuesaretwotypes:
1. Ascendingorderpriorityqueue
2. Descendingorderpriorityqueue
1. Ascendingorderpriorityqueue: ItisLowerprioritynumbertohighprioritynumber.
Examples: order is 1,2,3,4,5,6,7,8,9,10
2. Descendingorderpriorityqueue: Itishighprioritynumbertolowestprioritynumber.
Examples: Order is 10,9,8,7,6,5,4,3,2,1
ImplementationofPriorityQueue:
Implementationofpriorityqueuesaretwotypes:
1. ThroughQueue(UsingArray)
2. ThroughSortedList(UsingLinkedList)
1. ThroughQueue(UsingArray):Inthiscaseelementissimplyaddedattherearendas usual. For
deletion, the element with highest priority is searched and then deleted.

2. Through sorted List (Using Linked List): In this case insertion is costly because the
element insert at the proper place in the list based on the priority. Here deletion is easy
since the element with highest priority will always be in the beginning of the list.

25
1. DifferencebetweenstacksandQueues?
stacks Queues
1. Astackisalinearlistofelementsinwhich the 1. AQueueisalinerarlistofelementsinwhich the
element may be inserted or deleted at one elements are added at one end and deletes
end. the elements at another end.
2. .InQueuetheelementwhichis inserted
2. Instacks,elementswhichareinserted first is the elementdeleted first.
last is the firstelement to be deleted.
3. QueuesarecalledFIFO(FirstInFirst
3. StacksarecalledLIFO(LastInFirst Out)list.
Out)list
4. InQueueelementsareremovedinthe
4. Instackelementsareremovedinreverse sameorder in which thy are inserted.
order in which thy are inserted.
5. Supposetheelementsa,b,c,d,eareinserted
5. supposetheelementsa,b,c,d,eare inthe Queue,the deletion of elements willbe
inserted in the stack, the deletion of in the sameorder in which thy are inserted.
elements will be e,d,c,b,a.
6. InQueuetherearetwopointersonefor
6. Instackthereisonlyonepointertoinsert and insertion called “Rear” and another for
delete called “Top”. deletioncalled“Front”.

7. Initiallytop=-1indicatesastackisempty. 7. InitiallyRear=Front=-1indicatesaQueueis
empty.
8. Stackisfullrepresentedbythecondition
TOP=MAX-1(if array index starts from ‘0’). 8. Queueisfullrepresentedbythecondition
Rear=Max-1.
9. Topushanelementintoastack,Topis
incremented by one 9. ToinsertanelementintoQueue,Rearis
incremented by one.
10. ToPOPanelementfromstack,topis
decremented by one. 10. TodeleteanelementfromQueue,Frontis

26
incrementedbyone.
11.TheconceptualviewofStackisas follows:
11.TheconceptualviewofQueueisas follows:

27
LINEARLIST
INTRODUCTION
LinearData Structures:
Linear data structures are those data structures in which data elements are accessed (read
and written) in sequential fashion (one by one). Ex: Stacks, Queues, Lists, Arrays
NonLinearDataStructures:
Non Linear Data Structures are those in which data elements are not accessed in sequential
fashion.
Ex:trees,graphs
DifferencebetweenLinearandNonlinearDataStructures
Main difference between linear and nonlinear data structures lie in the way they organize
data elements. In linear data structures, data elements are organized sequentially and
therefore they are easy to implement in the computer’s memory. In nonlinear data
structures, a data element can be attached to several other data elements to represent
specific relationships that exist among them. Due to this nonlinear structure, they might be
difficult to be implemented in computer’s linear memory compared to implementing linear
data structures. Selecting one data structure type over the other should be donecarefullyby
considering the relationship among the data elements that needs to be stored.
LINEARLIST
A data structure is said to be linear if its elements form a sequence. A linear list is a list that
displays the relationship of adjacency between elements.
A Linear list can be defined as a data object whose instances are of the form (e 1,e2, e3…en)
where n is a finite natural number. The eiterms are the elements of the list and n is its
length.Theelementsmaybeviewedasatomicas theirindividualstructure isnot relevantto the
structure ofthe list. Whenn=0,the list is empty. Whenn>0,e 1is the first element andenthe
last. Ie;e1 comes before e2, e2 comes before e3and so on.
SomeexamplesoftheLinearListare
 Analphabetizedlistofstudentsinaclass
 Alistofexamscoresinnondecreasingorder
 AlistofgoldmedalwinnersintheOlympics
 AnalphabetizedlistofmembersofCongress
ThefollowingaretheoperationsthatperformedontheLinearList
 CreateaLinearList
 DestroyaLinearList
 Determinewhetherthelistisempty
 DeterminethesizeoftheList
 Findtheelementwithagiven index
 Findthe indexofagivennumber
 Delete,eraseorremoveanelementgivenitsindex
 Insertanewelementsothatithasagiven index
A Linear List may be specified as an abstract Data type (ADT) in which we provide a
specification of the instance as well as of the operations that are to be performed. The
below abstract data type omitted specifying operations to create and destroy instance ofthe
data type. All ADT specifications implicitly include an operation to create an empty instance
and optionally, an operation to destroy an instance.

28
ArrayRepresentation:(FormulaBasedRepresentation)
A formula based representation uses an array to represent the instance of an object. Each
positionoftheArray iscalled aCellorNodeandis largeenoughtoholdone ofthe elements that
make up an instance, while in other cases one array can represent several instances.
Individual elements of an instance are located in the array using a mathematical formula.
Suppose one array is used for each list to be represented. We need to map the
elements of a list to positions in the array used to represent it. In a formula based
representation, a mathematical formula determines the location of each element. A simple
mapping formulas is
Location(i)=i-1

This equation states that the ithelement of the list is in position i-1 of the array. The below
figure shows a five element list represented in the array element using the mapping of
equation.
To completely specify the list we need to know its current length or size. For this purposewe
use variable length. Length is zero when list is empty. Program gives the resulting C++ class
definition. Since the data type of the list element may vary from application to application,
we have defined a template class in which the user specifies the element data type T. the
data members length, MaxSize and element are private members are private members,
while the remaining members are public. Insert and delete have been defined to return a
reference to a linear list.
InsertionandDeletionofaLinearList:
Suppose we want toremove anelement eifrom the list by moving toits right downby 1.For
example, to remove an element e1=2 from the list,we have to move the elements e 2=4,
e3=8,and e4=1,which are to the right of e1, to positions 1,2 and 3 of the array element. The
below figure shows this result. The shaded elements are moved.

29
To insert an element so that it becomes element I of a list, must move the existing element
eiandallelements toits right one position right andthenput the new element intoposition I of
the array. For example to insert 7 as the second element of the list, we first move elements
e2and e3to the right by 1 and then put 7 in to second position 2 of the array. The below
figure shows this result. The shaded elements were moved.

LinkedRepresentationAndChains
Ina linked list representation eachelement ofan instance ofa data object isrepresented in a
cell or node. The nodes however need not be component of an array and no formula is used
to locate individual elements. Instead of each node keeps explicit information about the
location of other relevant nodes. This explicit information about the location of another
node is called Link or Pointer.
Let L=(e1,e2, e3…en) be a linear List. In one possible linked representation for this list, each
element eiis represented in a separate node. Each node has exactly one link field that is used
to locate the next element in the linear list. So the node for e ilinks to that for ei+1,0<=i<n-1.
The node for en-1 has no need to link to and so its link field is NULL. The pointer variables first
locate the first node in the representation. The below figure shows the linked
representation of a List=(e1,e2, e3…en).

Sinceeach node in the Linked representation of the above figure has exartly one link, the
structure ofthis figure is calleda ‘SingleLinked List’.the nodes are orderedfrom left toright
with each node (other than last one) linking to the next,and the last node has a NULLlink,the
structure is also called a chain.
InsertionandDeletionofaSingleLinkedList:
Insertion Let the list be a Linked list with succesive nodes A and B as shown in below
figure.suppose a node N id to be inserted into the list between the node A and B.

30
IntheNewlisttheNodeA pointstothenew NodeNand thenew node Npointstothenode B to
which Node A previously pointed.
Deletion:
LetlistbeaLinkedlistwithnodeNbetweenNodesAandBisasshowninthefollowing figure.

31
In the new list the node N is to be deleted from the Linked List. The deletion occurs as the
link field in the Node A is made to point node B this excluding node N from its path.

DOUBLELINKEDLIST(Or)TWOWAYLINKEDLIST
Incertain applications it is very desirable that list be traversedin either forward direction or
Backworddirection. The propertyofDoubleLinkedListimpliesthateachnodemustcontain two
link fields instead of one. The links are used to denote the preceding and succeeding of the
node. The link denoting the preceding of a node is called Left Link. The link denoting
succeeding of a node is called Right Link. The list contain this type of node is called a
“Double Linked List” or “Two Way List”. The Node structure in the Double Linked List is as
follows:

Lptr contains the address of the before node. Rptr contains the address of next node. Data
Contains the Linked List is as follows.

In the above diagram Last and Start are pointer variables which contains the address of last
node and starting node respectively.
Insertionin totheDoubleLinked List:Letlistbea doublelinkedlistwithsuccessivemodesA and B
as shown in the following diagram. Suppose a node N is to be inserted into the list between
the node s A and B this is shown in the following diagram.

32
As in the new list the right pointer of node A points to the new node N ,the Lptr of the node
‘N’ points to the node A and Rptr of node ‘N’ points to the node ‘B’ and Lpts of node Bpoints
the new node ‘N’
DeletionOfDoubleLinkedList:-Let listbea linkedlistcontainsnode Nbetweenthenodes A and
B as shown in the following diagram.

Support node N is to be deleted from the list diagram will appear as the above mention
double linked list. The deletion occurs as soon as the right pointer field of node A charged,
so that it points to node B and the lift point field of node B is changed. So that it pointes to
node A.
Circular Linked List:- Circular Linked List is a special type of linked list in which all the nodes
are linked in continuous circle. Circular list can be singly or doubly linked list. Note that,
there are no Nulls in Circular Linked Lists. In these types of lists, elements can be added to
the back of the list and removed from the front in constant time.
Both types of circularly-linked lists benefit from the ability to traverse the full list beginning
at any given node. This avoids the necessity ofstoring first Node andlast node,but we need
aspecial representation forthe emptylist,such asalastnodevariablewhich pointstosome node
in the list or is null if it's empty. This representation significantly simplifies adding and
removing nodes with a non-empty list, but empty lists are then a special case.Circular linked
lists are most useful for describing naturally circular structures, and have the advantage of
being able to traverse the list starting at any point. They also allow quickaccess tothe first
and last records through a single pointer(the address of the last element)

33
Circularsinglelinkedlist:

Circularlinkedlistare onethey oflinerlinkedlist.Inwhichthe linkfieldsoflastnodeofthe list


contains the address of the first node of the list instead of contains a null pointer.
Advantages:- Circular list are frequency used instead of ordinary linked list because in
circular list all nodes contain a valid address. The important feature of circular list is as
follows.
(1) Inacircularlisteverynodeisaccessiblefromagivennode.
(2) Certain operations like concatenation and splitting becomes more efficient in circular
list.
Disadvantages: Without some conditions in processing it is possible to get into an infinite
Loop.
Circular Double Linked List :- These are one type of double linked list. In which the rpt field
ofthe last node of the list contain the address of the first node ad the left points ofthe first
node contains the address of the last node of the list instead of containing null pointer.

Advantages:- circular list are frequently used instead of ordinary linked list because in
circular list all nodes contained a valid address. The important feature of circular list is as
follows.
(1) Inacircularlisteverynodeisaccessiblefromagivennode.
(2) Certainoperationslikeconcatenationandsplittingbecomesmoreefficient in
circular list.
Disadvantage:-Withoutsomeconditionsinprocessesitispossibletogetintoaninfantglad.

Differencebetweensinglelinkedlistanddouble linkedlist?

Singlelinkedlist(SLL) Doublelinkedlist(DLL)
1. InSingleLinkedListthelistwillbetraversed in 1. In Double Linked List the list will be
only one way ie; in forward. traversedintwowayie;eitherforwardand
2. InSingleLinkedListthenodecontainsone backward
link field only. 2. InDoubleLinkedListthenodecontainstwo
3. Everynodecontainstheaddressofnext link fields.
node. 3. Everynodecontainstheaddressofnext
4. ThenodestructureinSinglelinkedlistisas node as well as preceding node.
follows: 4. thenodestructureindoublelinkedlistisas
follows:

34
5. theconceptualviewofDLLisasfollows:
5. TheconceptualviewofSLL isas follows:

6. DLLismaintainedinmemorybyusingthree
arrays.
6. SLLaremaintainedinmemorybyusingtwo
arrays.

2. Differencebetweensequentialallocationandlinkedallocation?
OR
DifferencebetweenLinearListandLinkedList?
OR
DifferencebetweenArraysandLinkedList?
Arrays LinkedList
1. Arraysareusedinthepredictablestorage 1. Linked List are used in the unpredictable
requirement ie; exert amount of data storagerequirementie;exertamountofdata
storage required by the program can be storage required by the program can’t be
determined. determined.

2. Inarraystheoperationssuchasinsertion 2. In Linked List the operations such as


and deletion are donein an inefficient insertion and deletion are done more
manner. efficientmannerie;onlybychangingthe
pointer.

3. Theinsertionanddeletionaredoneby 3. Theinsertionanddeletionaredoneby
moving the elements either up or down. only changing the pointers.

4. Successiveelementsoccupyadjacent 4. Successiveelementsneednotoccupy
space on memory. adjacent space.

5. InarrayseachlocationcontainDATA only 5. Inlinkedlisteachlocationcontainsdata


6. The linear relation ship between the data and pointer to denote whether the next
elements of an array is reflected by the element present in the memory.
physicalrelationshipofdatainthememory.
6. Thelinearrelationshipbetweenthedata
7. Inarraydeclarationablockofmemory elements ofaLinkedList is reflected by the
space is required. Linked field of the node.

8. Thereisnoneedofstorageofpointeror 7. InLinkedlistthereisnoneedofsuch
lines thing.

35
8. InLinkedlistapointerisstoredalonginto the
element.
9. TheConceptualviewofanArrayisas 9. TheConceptualviewofLinkedlistisas
follows: follows:

10. Inarraythereisnoneedforanelement to
specify whether the next is stored
10. Thereisneedforanelement(node)to
specify whether the next node is formed.

36
SORTING AND
SEARCHING
SORTING-INTRODUCTION
Sorting is a technique of organizing the data. It is a process of arranging the records,
either in ascending or descending order i.e. bringing some order lines in the data. Sort
methods are very important in Data structures.
Sorting can be performed on any one or combination of one or more attributes present in
each record. It is very easy and efficient to perform searching, if data is stored in sorting
order. The sorting is performed according tothe key value of each record. Depending up on
the makeup of key, records can be stored either numerically or alphanumerically. In
numerical sorting, the records arranged in ascending or descending order according to the
numeric value of the key.
LetAbealistofnelementsA1,A2,A3......................................................... Aninmemory.SortingAreferstothe
operation of rearranging the contents of A so that they are increasing in order, that is, so
that A1<=A2<=A3<=…………….<=An. Since A has n elements, there are n! Ways that the
contents can appear in A. these ways corresponding precisely to the n! Permutations of
1,2,3,n. accordingly each sorting algorithm must take care of these n! Possibilities.

Ex:supposeanarrayDATAcontains8elementsas follows:
DATA:70,30,40,10,80,20,60,50.
AftersortingDATAmustappearinmemoryas follows:
DATA:1020304050607080
SinceDATAconsistsof8elements,thereare8!=40320waysthatthenumbers 10,20,30,40,50,60,70,80 can
appear in DATA.
Thefactorstobeconsideredwhilechoosingsortingtechniques are:
 ProgrammingTime
 ExecutionTime
 NumberofComparisons
 MemoryUtilization
 ComputationalComplexity

TypesofSorting Techniques:
Sorting techniques are categorized into 2 types. They are Internal Sorting and External
Sorting.
Internal Sorting: Internal sorting method is used when small amount of data has to be
sorted. In this method , the data to be sorted is stored in the main memory (RAM).Internal
sorting method can access records randomly. EX: Bubble Sort, Insertion Sort, Selection Sort,
Shell sort, Quick Sort, Radix Sort, Heap Sort etc.
External Sorting: Extern al sorting method is used when large amount of data has to be
sorted. In this method, the data to be sorted is stored in the main memory as well as in the
secondary memory such as disk. External sorting methods an access records only in a
sequential order. Ex: Merge Sort, Multi way Mage Sort.

Complexity of sorting Algorithms: The complexity of sorting algorithm measures therunning


time as a function of the number n of items to be stored. Each sorting algorithm S
willbemadeupofthefollowingoperations,whereA1,A2,A3............................................................ Ancontainthe
itemstobesortedandB isanauxiliarylocation.

37
 Comparisons,whichtestwhetherAi<AjortestwhetherAi<B.
 InterchangeswhichswitchthecontentsofAiandAjorofAiand B.
 Assignmentwhichset B:AiandthensetAj:=BorAj:=Ai
Normally,thecomplexityfunctionmeasuresonlythenumberofcomparisons,sincethe number of
other operations is at most a constant factor of the number of comparisons.

SELECTION SORT
In selection sort, the smallest value among the unsorted elements of the array is
selected in every pass and inserted to its appropriate position into the array. First, find the
smallest element of the array and place it on the first position. Then, find the second
smallest element of the array and place it on the second position. The process continues
until we get the sorted array. The array with n elements is sorted by using n-1 pass of
selection sort algorithm.
 In1stpass,smallestelementofthearray istobe foundalongwithitsindex pos.
then, swap A[0] and A[pos]. Thus A[0] is sorted, we now have n -1
elements which are tobe sorted.
 In2ndpas,positionpos ofthesmallestelementpresentinthesub-arrayA[n- 1] is
found. Then, swap, A[1] and A[pos]. Thus A[0] and A[1] are sorted, we now
left with n-2 unsorted elements.
 Inn-1thpass,positionposofthesmallerelement betweenA[n-1]andA[n-2] is to
be found. Then, swap, A[pos] and A[n-1].

Therefore,byfollowingtheaboveexplainedprocess,theelementsA[0], A[1],
A[2], ... , A[n-1] are sorted.

Example:Considerthe followingarraywith6elements.Sorttheelementsofthearrayby using


selection sort.
A={10,2,3,90,43,56}.

Pass Pos A[0] A[1] A[2] A[3] A[4] A[5]


1 1 2 10 3 90 43 56
2 2 2 3 10 90 43 56
3 3 2 3 10 90 43 56
4 4 2 3 10 43 90 56
5 5 2 3 10 43 56 90

SortedA={2,3,10,43,56,90}

Complexity
Complexity Best AverageCase WorstCase
Case
Time Ω(n) θ(n2) o(n2)

Space o(1)

38
Algorithm

SELECTIONSORT(ARR, N)

Step1:RepeatSteps2and3forK =1toN-1 Step

2: CALL SMALLEST(A, K, N, POS)

Step3:SWAPA[K]with
A[POS] [END OF LOOP]
Step 4: EXIT

BUBBLE SORT
Bubble Sort: This sorting technique is also known as exchange sort, which arranges
values by iterating over the list several times and in each iteration the larger value gets
bubble up to the end of the list. This algorithm uses multiple passes and in each pass thefirst
and second data items are compared. if the first data item is bigger than the second, then
the two items are swapped. Next the items in second and third position are compared and
ifthe firstone islargerthan thesecond,then theyareswapped,otherwisenochangein their
order. This process continues for each successive pair of data items until all items are sorted.
BubbleSortAlgorithm:
Step1:RepeatSteps2and3for i=1to10 Step 2:
Set j=1
Step3:Repeatwhilej<=n
(A)
if a[i] < a[j] Then
interchangea[i]anda[j] [End
of if]
(B)Setj=j+1
[EndofInner Loop]
[EndofStep1OuterLoop]
Step 4: Exit

39
INSERTION SORT
Insertion sort is one of the best sorting techniques. It is twice as fast as Bubble sort.
In Insertion sort the elements comparisons are as less as compared to bubble sort. In this
comparison the value until all prior elements are less than the compared values is notfound.
This means that all the previous values are lesser than compared value. Insertionsort is good
choice for small values and for nearly sorted values.

Working of Insertion sort:


The Insertion sort algorithm selects each element and inserts it at its proper position in
asublistsorted earlier.Ina firstpasstheelementsA 1iscomparedwith A0and if A[1]andA[0] are
not sorted they are swapped.
In the second pass the element[2] is comparedwith A[0] and A[1]. And it is inserted at its
proper position in the sorted sub list containing the elements A[0] and A[1]. Similarly doing
ithiteration the element A[i] is placed at its proper position in the sorted sub list, containing
the elements A[0],A[1],A[2],A[i-1].
Tounderstandtheinsertionsort considertheunsortedArrayA={7,33,20,11,6}.

The steps to sort the values stored in the array in ascending order using Insertion sort are
given below:

40
7 33 20 11 6

Step1:The firstvaluei.e;7istriviallysortedby itself.


Step 2: the second value 33 is compared with the first value 7. Since 33 is greaterthan7, so
no changes are made.
Step 3: Next the thirdelement 20 is comparedwithits previous element (towards left).Here
20 is less than 33.but 20 is greater than 7. So it is inserted at second position. For this 33 is
shifted towards right and 20 is placed at its appropriate position.

7 33 20 11 6

7 20 33 11 6

Step 4: Then the fourth element 11 is compared with its previous elements. Since 11 is less
than 33 and 20 ; and greater than 7. So it is placed in between 7 and 20. For this the
elements 20 and 33 are shifted one position towards the right.

7 20 33 11 6

7 11 20 33 6
Step5:Finally the last element 6 is compared with all the elements preceding it. Since it is
smaller than all other elements, so they are shifted one position towards right and 6 is
inserted at the first position in the array. After this pass, the Array is sorted.

7 11 20 33 6

6 7 11 20 33
Step6:FinallythesortedArrayisas follows:

6 7 11 20 33

ALGORITHM:
Insertion_sort(ARR,SIZE)
Step 1: Set i=1;
Step2:while(i<SIZE)
Settemp=ARR[i]
J=i=1;
While(Temp<=ARR[j]andj>=0) Set
ARR[j+1]=ARR[i]
Set j=j-1
EndWhile
SETARR(j+1)=Temp;

41
PrintARRafterithpass
Set i=i+1
Endwhile
Step3:printno.ofpassesi-1
Step4:end
AdvantagesofInsertion Sort:
 It is simple sorting algorithm, in which the elements are sorted by considering
oneitem at a time. The implementation is simple.
 It is efficient for smaller data set and for data set that has been substantially sorted
before.
 Itdoesnotchangethe relativeorderofelementswithequalkeys
 Itreducesunnecessarytravelsthroughthearray
 Itrequiresconstantamountofextramemoryspace.

Disadvantages:-
 Itislessefficientonlistcontainingmorenumberofelements.
 Asthenumberofelementsincreasestheperformanceofprogramwouldbe slow
ComplexityofInsertionSort:
BESTCASE:-
Onlyonecomparisonismadeineachpass.
The Time complexity is O(n2).

WORST CASE:- In the worst case i.e; if the list is arranged in descending order, the number
of comparisons required by the insertion sort is given by:
1+2+3+… ...................... +(n-2)+(n-1)=(n*(n-1))/2;
=(n2-n)/2.
ThenumberofComparisonsareO(n2).
AVERAGECASE:-Inaveragecasethenumerofcomparisonsisgivenby

1+2+ 3+ (n−2)
⋯+ +
(n−1) n∗(n−1)
= =(n2-n)/4=O(n2).
2 2 3 2 2 2∗2
Program:
/*Programtoimplementinsertionsort*/
#include<iostream.h>
#include<conio.h>
main()
{
inta[10],i,j,n,t;
clrscr();
cout<<”\nEnternumberofelementstobeSort:”; cin>>n;
cout<<”\nEntertheelementstobeSorted:”;
for(i=0;i<n;i++)
cin>>a[i];
for(i=0;i<n;i++)
{t=a[i];
J=I;
while((j>0)&&(a[j-1]>t))
{a[j]=a[j-1];

42
J=j-1;
}
a[j]=t;
}
cout<<”ArrayafterInsertionsort:”;
for(i=0;i<n;i++)
cout<”\na[i]”;
getch();
}
OUTPUT:
Enternumber ofelementstosot:5
Enternumberofelementstosorted:7 33 20 11 6
ArrayafterInsertionsort:6 7 11 20 33.

QUICK SORT
The Quick Sort algorithm follows the principal of divide and Conquer. It first picks
up the partition element called ‘Pivot’, which divides the list into two sub lists such that all
the elements in the left sub list are smaller than pivot and all the elements in the right sub
list are greater than the pivot. The same process is applied on the left and right sub lists
separately. This process is repeated recursively until each sub list containing more than one
element.
WorkingofQuickSort:
The main task in Quick Sort is to find the pivot that partitions the given list into two halves,
so that the pivot is placed at its appropriate position in the array. The choice of pivot as a
significant effect onthe efficiency ofQuickSortalgorithm. Thesimplestwayis tochoosethe first
element as the Pivot.However the first element is not good choice, especially if the given list
is ordered or nearly ordered .For better efficiency the middle element can be chosen as
Pivot.

Initially three elements Pivot, Beg and End are taken, such that both Pivot and Beg refers to
0thposition and End refers to the (n-1)th position in the list. The first pass terminates when
Pivot, Beg and End all refers to the same array element. This indicates that the Pivotelement
is placed at its final position. The elements to the left of Pivot are smaller than this element
and the elements to it right are greater.
To understandthe Quick Sort algorithm, consider an unsorted array as follows. The steps to
sort the values stored in the array in the ascending order using Quick Sort are given below.

8 33 6 21 4
Step 1: Initially the index ‘0’ inthe list is chosen as Pivot and the index variable Beg and End
are initiated with index ‘0’ and (n-1) respectively.

43
Step2:Thescanningoftheelementstartsfrom theendofthelist.
A[Pivot]>A[End]
i.e; 8>4
sotheyare swapped.

Step3:Nowthescanningoftheelementsstartsfromthebeginningofthelist.Since A[Pivot]>A[Beg]. So Beg


is incremented by one and the list remains unchanged.

Step4:TheelementA[Pivot]issmallerthan A[Beg].Sotheyareswapped.

Step 5: Again the list is scanned form right to left. Since A[Pivot] is smaller than A[End],
sothe value of End is decreased by one and the list remains unchanged.

Step 6:Nextthe elementA[Pivot]issmallerthan A[End],the valueof Endisincreased by one. and


the list remains unchanged.

44
Step7:A[Pivot>>A[End]sotheyareswapped.

Step 8: Now the list is scanned from left to right. Since A[Pivot]>A[Beg],value of Beg is
increased by one and the list remains unchanged.

At this point the variable Pivot, Beg, End all refers to same element, the first pass is
terminated and the value 8 is placed at its appropriate position. The elements to its left are
smaller than 8 and the elements to its right are greater than 8.The same process is applied
on left and right sub lists.
ALGORITHM
Step1:SelectfirstelementofarrayasPivot
Step2:Initializeiand jtoBegandEndelementsrespectively
Step3:IncrementiuntilA[i]>Pivot.
Stop
Step4:DecrementjuntilA[j]>Pivot Stop
Step5:ifi<jinterchangeA[i]with A[j].
Step6:Repeatsteps3,4,5untili>ji.e:icrossed j.
Step7:ExchangethePivotelementwithelement placedatj, whichis correctplacefor Pivot.
AdvantagesofQuickSort:
 Thisis fastestsortingtechniqueamongall.
 Itefficiencyisalsorelativelygood.
 Itrequiressmallamountof memory

Disadvantages:
 Itissomewhatcomplexmethodfor sorting.
 Itislittlehardtoimplementthanothersortingmethods
 Itdoesnotperformwellinthecaseofsmallgroupofelements.

ComplexitiesofQuickSort:
AverageCase:TherunningtimecomplexityisO(nlogn).
WorstCase:Inputarrayisnotevenlydivided.SotherunningtimecomplexityisO(n2).
BestCase:Inputarray isevenlydivided.Sothe runningtimecomplexityisO(n logn).

45
MERGE SORT
The Merge Sort algorithm is based on the fact that it is easier and faster to sort two
smaller arrays than one large array. It follows the principle of “Divide and Conquered”. In
this sorting the list is first divided into two halves. The left and right sub lists obtained are
recursively dividedintotwosublists untileachsublist contains not more thanone element. The
sub list containing only one element do not require any sorting. After that merge the two
sorted sub lists to form a combined list and recursively applies the merging process till the
sorted array is achieved.
LetusapplytheMergeSorttosortthefollowinglist:

13 42 36 20 63 23 12
Step1:Firstdividethe combinedlistintotwosublistsas follows.

Step2:NowDividetheleftsub listintosmallersub list

Step3:Similarlydividethesubliststilloneelementisleft inthe sublist.

Step4:Nextsorttheelementsintheirappropriatepositionsandthencombinedthesub lists.

Step5:Nowthesetwosublistsareagainmerged togivethefollowingsortedsublistofsize 4.

Step6:Aftersortingthe lefthalfofthearray,containingthesameprocess fortherightsub list also.


Then the sorted array of right half of the list is as follows.

Step7:Finallythe leftandrighthalvesofthearrayaremergedtogivethesorted arrayas follows.

46
Advantages:
 Mergesortisstablesort
 Itis easy tounderstand
 Itgivesbetterperformance.

Disadvantages:
 Itrequiresextramemoryspace
 Copyofelementstotemporaryarray
 Itrequiresadditionalarray
 Itisslow process.

ComplexityofMergeSort: Themergesortalgorithmpassesovertheentire listandrequires at


most log n passes and merges n elements in each pass. The total number of comparisons
required by the merge sort is given by O(n log n).

External searching: When the records are stored in disk, tape, any secondary storage then
that searching is known as ‘External Searching’.
InternalSearching:Whentherecordsaretobesearchedorstoredentirelywithinthe computer
memory then it is known as ‘Internal Searching’.

47
LINEAR SEARCH
The Linear search or Sequential Search is most simple searching method. It does
not expect the list to be sorted. The Key which to be searched is compared with each
element of the list one by one. If a match exists, the search is terminated. If the end of the
list is reached, it means that the search has failed and the Key has no matching element in
the list.
Ex:considerthe followingArrayA
231518174296103
Nowletussearchfor17byLinearsearch.Thesearchingstartsfromthe firstposition. Since
A[0] ≠17.
Thesearchproceedstothenextpositioni.e;secondpositionA[1]≠17.
TheaboveprocesscontinuousuntilthesearchelementisfoundsuchasA[3]=17. Here
the searching element is found in the position 4.

Algorithm:LINEAR(DATA,N,ITEM, LOC)
Here DATA is a linear Array with N elements. And ITEM is a given item of information. This
algorithm finds the location LOC of an ITEM in DATA. LOC=-1 if the search is unsuccessful.
Step1:Set DATA[N+1]=ITEM
Step2:Set LOC=1
Step3:Repeatwhile(DATA[LOC]!=ITEM) Set
LOC=LOC+1
Step4:ifLOC=N+1then
SetLOC=-1.
Step5:Exit

Advantages:
 Itissimplestknowntechnique.
 Theelementsinthelistcanbe inany order.
Disadvantages:
This method is in efficient when large numbers of elements are present in list because time
taken for searching is more.
ComplexityofLinearSearch:TheworstandaveragecasecomplexityofLinearsearchis
O(n),where‘n’ isthetotalnumberofelementspresentinthe list.

BINARY SEARCH
Suppose DATA is an array which is stored in increasing order then there is an extremely
efficient searching algorithm called “Binary Search”. Binary Search can be used to find the
location of the given ITEM of information in DATA.
WorkingofBinarySearch Algorithm:
During each stage of algorithm search for ITEM is reduced to a segment of elements of
DATA[BEG], DATA[BEG+1], DATA[BEG+2], ........................ DATA[END].
Here BEG and END denotes beginning and ending locations of the segment under
considerations. The algorithm compares ITEM with middle element DATA[MID] of a
segment, where MID=[BEG+END]/2. If DATA[MID]=ITEM then the search is successful. and
we said that LOC=MID. Otherwise a new segment of data is obtained as follows:
i. IfITEM<DATA[MID]thenitemcanappearonlyinthelefthalfofthesegment.
DATA[BEG], DATA[BEG+1], DATA[BEG+2]
SoweresetEND=MID-1.Andbeginthesearchagain.

48
ii. IfITEM>DATA[MID]thenITEMcan appearonlyinrighthalfofthesegmenti.e.
DATA[MID+1], DATA[MID+2], .................... DATA[END].
SoweresetBEG=MID+1.Andbeginthesearch again.
Initiallywe beginwiththeentire arrayDATA i.e.webeginwithBEG=1andEND=n Or
BEG=lb(Lower Bound)
END=ub(UpperBound)
IfITEM is not inDATA theneventually we obtainedEND<BEG. This conditionsignals that the searching
is Unsuccessful.
ThepreconditionforusingBinarySearchisthatthelistmustbesortedone.
Ex:considera listofsorted elementsstored inanArrayAis

Letthekeyelementwhichistobesearchedis35.
Key=35
Thenumberofelementsinthelistn=9.
Step1:MID= [lb+ub]/2
=(1+9)/2
=5

Key<A[MID]
i.e.35<46.
Sosearchcontinuesatlowerhalfofthearray.
Ub=MID-1
=5-1
=4.

Step2:MID= [lb+ub]/2
=(1+4)/2
=2.

Key>A[MID]
i.e.35>12.
SosearchcontinuesatUpperHalfofthearray.
Lb=MID+1
=2+1
=3.

49
Step3:MID= [lb+ub]/2
=(3+4)/2
=3.

Key>A[MID]
i.e.35>30.
SosearchcontinuesatUpperHalfofthearray.
Lb=MID+1
=3+1
=4.
Step4:MID= [lb+ub]/2
=(4+4)/2
=4.

ALGORITHM:
BINARYSEARCH[A,N,KEY]
Step1:begin
Step2: [Initilization]
Lb=1;ub=n;
Step3:[SearchfortheITEM]

Repeatthroughstep4,whileLowerboundislessthanUpperBound.
Step4:[Obtaintheindexofmiddlevalue] MID=(lb+ub)/2
Step5:[ComparetosearchforITEM] If
Key<A[MID] then
Ub=MID-1
OtherwiseifKey>A[MID]then
Lb=MID+1
Otherwisewrite“MatchFound”
Return Middle.
Step 6: [Unsuccessful Search]
write“MatchNotFound”
Step7:Stop.

Advantages:Whenthe numberofelementsinthelist islarge,BinarySearchexecuted faster


thanlinearsearch.Hencethismethodisefficientwhennumberofelementsislarge.

50
Disadvantages:ToimplementBinarySearchmethodtheelementsinthelistmustbein sorted
order, otherwise it fails.

Define sorting? What is the difference between internal and external sorting methods?
Ans:-Sortingisatechniqueoforganizingdata.Itisaprocessofarrangingtheelements either may
be ascending or descending order, ie; bringing some order lines with data.

Internalsorting Externalsorting
1.InternalSortingtakesplaceinthemain 1.Externalsortingisdonewithadditional
memory of a computer. externalmemorylikemagnetictapeorhard
disk
2.Theinternal sortingmethodsareapplied to 2. The External sorting methods are applied
small collection of data. only when the number of data elements to
be sorted is too large.
3.Internalsortingtakessmallinput 3. External sorting can take as much as large
input.
4.Itmeansthat,the entire collection of data 4. External sorting typically uses a sort-
tobe sorted in small enoughthat thesorting merge strategy, and requires auxiliary
can take place within main memory. storage.
5. For sorting larger datasets, it may be 5. In the sorting phase, chunks of data small
necessary to hold only a chunk of data in enough to fit in main memory are read,
memory at a time, since it wont all fit. sorted, and written out to a temporary file.
6.ExampleofInternalSortingalgorithmsare 6.ExampleofExternalsortingalgorithms are: -
:- Bubble Sort, Internal Sort, Quick Sort,Heap Merge Sort, Two-way merge sort.
Sort, Binary Sort, Radix Sort, Selection sort.

7.Internalsortingdoesnotmakeuseofextra 7.Externalsortingmakeuseofextra resources.


resources.

JustifythefactthattheefficiencyofQuicksortisO(nlogn)underbestcase?
Ans:-BestCase:-
The best case in quick sort arises when the pivot element divides the lists into two
exactlyequal sub lists. Accordingly
i) Reducingtheinitiallistplaces'1'elementandproducestwoequalsublists.
ii) Reducing the two sub lists places '2' elements and produces four equal sub lists and son
on.
Observe that the reduction step in the k th level finals the location of 2(k-1)
elements, hence there will be approximately log n levels of reduction. Further, each level
uses at most 'n' comparisons, So f(n) = O(n log n).Hence the efficiency of quick sortalgorithm
is O(nlog n) under the best case.

Mathematical Proof:- Hencefromtheabove,therecurrencerelationforquicksortunder best


case is given by
T(n)=2T(n/2)+kn
Byusingsubstitutionmethod,weget
T(n)=2T(n/2)+Kn
=2{2T(n/4)+k.n/2}+kn
=4T(n/4)+2kn

51
.
.
.
In general
T(n)= 2kT(n/2k) + akn // after k substitutions
Theaboverecurrencerelationcontinuesuntiln=2 k,k=logn
Bysubstitutingtheabovevalues,weget
T(n)isO(nlogn)

Quicksort, or partition-exchangesort, isasortingalgorithm that,onaverage,


makes O(nlogn) comparisons to sort n items. In the worst case, it makes O(n2) comparisons,
though this behavior is rare. Quick sort is often faster in practice than other O(nlog n)
algorithms. Additionally, quick sort’s sequential and localized memory references work well
with a cache. Quick sort is a comparison sort and, in efficient implementations, is not astable
sort. Quick sort can be implemented with an in-place partitioning algorithm, so the entire
sort can be done with only O(log n) additional space used by the stack during the recursion.
Since each element ultimately ends up in the correct position, the algorithm correctly sorts.
But how long does it take.
The best case fordivide-and-conqueralgorithms comes when we split the
input as evenly as possible. Thus in the best case, each sub problem is of size n/2.The
partition step on each sub problem is linear in its size. Thus the total effort in partitioningthe
2k problems of sizen/2kis O(n).
Therecursiontreeforthebestcaselookslikethis:

The total partitioning on each level is O(n), and it take lognlevels of perfect partitionsto get
to single element sub problems. When we are down to single elements, the problems are
sorted. Thus the total time in the best case is O(nlogn).

52
TREES AND BINARY TREES

TREES

INTRODUCTION
Inlineardatastructure datais organized in sequentialorderandinnon-lineardatastructure data
is organized in random order. A tree is a very popular non-linear data structure used in a
wide range of applications. Tree is a non-linear data structure which organizes data in
hierarchical structure and this is a recursive definition.
DEFINITIONOFTREE:
Tree is collection of nodes (or) vertices and their edges (or) links. In tree data structure,
every individual element is called as Node. Node in a tree data structure stores the actual
data of that particular element and link to next element in hierarchical structure.

Note:1.InaTree,ifwehave NnumberofnodesthenwecanhaveamaximumofN- 1 number of


links or edges.
2.Treehasnocycles.
TREETERMINOLOGIES:
1. Root Node: In a Tree data structure, the first node is called as Root Node. Every treemust
have a root node. We can say that the root node is the origin of the tree data structure. In
any tree, there must be only one root node. We never have multiple rootnodes in a tree.

2. Edge: In a Tree, the connecting link between any two nodes is called as EDGE. In a tree
with 'N' number of nodes there will be a maximum of 'N-1' number of edges.

53
3. Parent Node: In a Tree, the node which is a predecessor of any node is called as PARENT
NODE. In simple words, the node which has a branch from it to any other node is called a
parent node. Parent node can also be defined as "The node which has child / children".

Here,AisparentofB&C.BistheparentofD,E&F andso on…


4. Child Node: In a Tree data structure, the node which is descendant of any node is called
asCHILD Node. In simple words, the node which has a link from its parent node is called as
child node. In a tree, any parent node can have any number of child nodes. In a tree, all the
nodes except root are child nodes.

5. Siblings:InaTreedatastructure,nodeswhichbelongtosameParentarecalled as SIBLINGS. In
simple words, the nodes with the same parent are called Sibling nodes.

54
6. LeafNode:InaTreedatastructure,thenodewhichdoesnothaveachildiscalled asLEAF Node. In
simple words, a leaf is a node with no child.In a tree data structure, the leaf nodes are also
called as External Nodes. External node is also a node with no child. In a tree, leaf node is
also called as 'Terminal' node.

7. InternalNodes:InaTreedatastructure,thenodewhichhasatleastonechildiscalled as
INTERNALNode.Insimplewords,aninternalnodeisanodewithatleastonechild.

In a Tree data structure, nodes other than leaf nodes are called as Internal Nodes. The root
node is alsosaid to be Internal Node if the tree has more than one node. Internal nodes are
also called as 'Non-Terminal' nodes.

8. Degree:InaTreedatastructure,thetotalnumberofchildrenofanodeiscalledasDEGREEofthat
Node.Insimple words,the Degreeofa node istotalnumberofchildren it has. The highest
degree of a node among all the nodes in a tree is called as 'Degree of Tree'

DegreeofTreeis:3

9. Level: In a Tree data structure, the root node is said to be at Level 0 and the children of
root node are at Level 1and the children of the nodes which are at Level 1will be at Level 2

55
and so on... In simple words, in a tree each step from top to bottom is called as a Level and
the Level count starts with '0' and incremented by one at each level (Step).

10. Height:InaTree datastructure,thetotalnumberofedgesfrom leafnodetoa particular node


in the longest path is called as HEIGHTof that Node. In a tree, height of the root node is said
to be height of the tree. In a tree, height of all leaf nodes is '0'.

11. Depth: In a Tree data structure, the total number of egdes from root node to a
particular node is called as DEPTH of that Node. In a tree, the total number of edges from
root node toa leafnode inthe longest pathis saidtobe Depth of the tree. Insimple words, the
highest depth of any leaf node in a tree is said to be depth of that tree. In a tree, depth of
the root node is '0'.

12. Path: In a Tree data structure, the sequence of Nodes and Edges from one node to
another nodeiscalled as PATHbetween that two Nodes. Length of a Path is total numberof
nodes in that path. In below example the path A - B - E - J has length 4.

56
13. Sub Tree: In a Tree data structure, each child from a node forms a subtree recursively.
Every child node will form a subtree on its parent node.

TREE REPRESENTATIONS:
Atreedatastructurecanbe representedintwomethods.Thosemethodsare asfollows...

1. List Representation
2. Left Child-Right Sibling Representation

Considerthefollowingtree...

1. ListRepresentation
In this representation, we use two types of nodes one for representing the node with data
called 'data node' and another for representing only references called 'reference node'. We
start with a 'data node' from the root node in the tree. Then it is linkedto an internal node

57
through a 'reference node' which is further linked to any other node directly. This process
repeats for all the nodes in the tree.
TheaboveexampletreecanberepresentedusingListrepresentationasfollows...

2. Left Child-Right Sibling Representation


In this representation, we use a list with one type of node which consists of three fields
namely Data field, Left child reference field and Right sibling reference field. Data fieldstores
the actual value of a node, left reference field stores the address of the left child and right
reference fieldstores the address ofthe right sibling node. Graphical representationof that
node is as follows...

In this representation, every node's data field stores the actual value of that node. If that node has
left a child, then left reference field stores the address of that left child node otherwise stores NULL.
If that node has the right sibling, then right reference field stores the address of right sibling node
otherwise stores NULL.

The above example tree can be represented using Left Child - Right Sibling representation as
follows...

BINARY TREE:

Inanormaltree,everynode canhaveany numberof children.Abinarytree isaspecialtype


oftreedatastructure inwhicheverynodecan haveamaximumof2children.Oneisknown as a left
child and the other is known as right child.

Atree inwhicheverynodecanhaveamaximumoftwochildreniscalledBinary Tree.

58
In a binary tree, every node can have either 0 children or 1 child or 2 children but not more
than 2 children.

In general, tree nodes can have any number of children. In a binary tree, each node
canhaveatmosttwochildren.A binary tree iseitheremptyorconsistsofa node calledthe root
together with two binary trees called the left subtree and the right subtree.A tree with no
nodes is called as a null tree

Example:

TYPES OF BINARY TREE:


1. StrictlyBinary Tree:
Ina binary tree,every node can have a maximum of twochildren. But instrictly binary tree,
every node should have exactly two children or none. That means every internal node must
have exactly two children. A strictly Binary Tree can be defined as follows...
Abinarytreeinwhich everynodehaseithertwo orzeronumberofchildreniscalled Strictly
Binary Tree
StrictlybinarytreeisalsocalledasFullBinaryTreeorProperBinaryTreeor2-Tree.

Strictlybinarytreedatastructureisusedtorepresentmathematicalexpressions.

59
Example

2. Complete Binary Tree:


Ina binary tree,every node can have a maximum of twochildren. But instrictly binary tree,
every node should have exactly two children or none and in complete binary tree all the
nodes must have exactly two children and at every level of complete binary tree there must
be 2levelnumber of nodes. For example at level 2 there must be 2 2= 4 nodes and at level 3
there must be 23 = 8 nodes.
A binary tree in which every internal node has exactly two children and all leaf nodes are
at same level is called Complete Binary Tree.

CompletebinarytreeisalsocalledasPerfectBinaryTree.

3. Extended Binary Tree:


AbinarytreecanbeconvertedintoFullBinarytreebyaddingdummynodestoexisting nodes
wherever required.
Thefullbinarytreeobtainedbyaddingdummynodestoa binarytreeiscalledas
Extended Binary Tree.

60
Inabovefigure,anormalbinarytreeisconvertedintofullbinarytreebyaddingdummy nodes.
4. Ske wed BinaryTree:
Ifatreewhichisdominatedbyleftchildnodeorrightchildnode,issaidtobea Skewed Binary Tree.
Inaskewedbinarytree,allnodesexceptonehaveonlyonechildnode.Theremaining node has no
child.

Inaleftskewedtree,mostofthenodeshavetheleftchildwithoutcorrespondingright child.
Inarightskewedtree, mostofthenodeshavetherightchildwithoutcorrespondingleft child.
Propertiesofbinarytrees:
Someoftheimportantpropertiesofabinarytreeareas follows:
1. Ifh=heightofabinary tree, then
a. Maximumnumberofleaves=2h
b. Maximumnumberofnodes=2h +1- 1
2. Ifabinarytreecontainsmnodesatlevell,itcontainsatmost2mnodesatlevell+1.
3. Since abinarytree cancontainatmostonenodeatlevel0(theroot),itcancontainat most 2l
node at level l.
4. Thetotalnumber ofedgesin afullbinarytreewithnnodeisn–
BINARYTREEREPRESENTATIONS:
Abinarytreedatastructureisrepresentedusingtwomethods.Thosemethodsareas follows...
1. Array Representation
2. LinkedListRepresentation
Considerthefollowingbinarytree...

61
1. Array Representation of Binary Tree
Inarrayrepresentationofa binarytree,we useone-dimensionalarray(1-DArray)to represent a
binary tree.
Considertheaboveexampleofabinarytreeanditisrepresentedas follows...

Torepresentabinarytree ofdepth'n'usingarray representation,weneedonedimensional array


with a maximum size of 2n+1.
2. Linked List Representation of Binary Tree
We use a double linked list to represent a binary tree. In a double linked list, every node
consistsofthreefields.Firstfieldforstoring left childaddress,secondforstoringactual data and
third for the right child address.
Inthislinkedlistrepresentation,anodehasthefollowingstructure...

The above example of the binary tree represented using Linked list representation is shown
as follows...

BINARYTREETRAVERSALS:
Unlike linear data structures (Array, Linked List, Queues, Stacks, etc) which have only one
logical way to traverse them, binary trees can be traversed in different ways. Following are
the generally used ways for traversing binary trees.
When we wanted to display a binary tree, we need to follow some order in which all the
nodes of that binary tree must be displayed. In any binary tree, displaying order of nodes
depends on the traversal method.
Displaying(or)visitingorderofnodesinabinarytreeiscalledasBinaryTreeTraversal.
Therearethreetypesofbinarytreetraversals.
1. In-Order Traversal
2. Pre-OrderTraversal
3. Post-OrderTraversal
1. In-OrderTraversal(leftChild- root- rightChild):

62
In In-Order traversal, the root node is visited between the left child and right child. In this
traversal, the left child node is visited first, then the root node is visited and later we go for
visiting the right child node. This in-order traversal is applicable for every root node of allsub
trees in the tree. This is performed recursively for all nodes in the tree.
Algorithm:
Step-1:Visittheleftsubtree,usinginorder.
Step-2: Visit the root.
Step-3:Visittherightsubtree,using inorder.

In the above example of a binary tree, first we try to visit left child of root node 'A', but A's
left child 'B' is a root node for left subtree. so we try to visit its (B's) left child 'D' and again D
is a root for subtree with nodes D, I and J. So we try to visit its left child 'I' and it is the
leftmostchild.Sofirstwevisit 'I'thengo foritsrootnode 'D'andlaterwevisitD'sright child'J'.With
this wehave completedthe left partof node B.Thenvisit 'B'and nextB's right child'F'is visited.
With this we have completed left part of node A. Then visit root node 'A'. With this we have
completed left and root parts of node A. Then we go for the right part of the node A. In right
of A again there is a subtree with root C. So go for left child of C and again it is a subtree
with root G. But G does not have left part so we visit'G'and then visit
G'srightchildK.WiththiswehavecompletedtheleftpartofnodeC.Thenvisitroot node'C'and next
visit C's right child 'H'which is the rightmost child in the tree. So we stop the process.
That means here we have visitedin the order of I - D - J - B - F - A - G - K - C - Husing In- Order
Traversal.
2. Pre-OrderTraversal(root -leftChild-rightChild):
In Pre-Order traversal, the root node is visited before the left child and right child nodes. In
thistraversal,the root node isvisitedfirst,thenitsleftchildandlateritsrightchild. This pre- order
traversal is applicable for every root node of all subtrees in the tree.Preorder searchis also
called backtracking.
Algorithm:
Step-1:Visittheroot.
Step-2: Visit the left subtree, using preorder.
Step-3:Visittherightsubtree,usingpreorder.

63
Intheaboveexampleofbinarytree,firstwevisitrootnode 'A'thenvisititsleft child'B'which isa
root forD andF.Sowe visitB's left child 'D'andagain D isa root forI and
J. So we visit D's left child 'I'which is the leftmost child. So next we go for visiting D's right
child'J'. Withthis we have completed root,left andright parts ofnode D androot,left parts of
node B. Next visit B's right child'F'. With this we have completed root and left parts of node
A. So we go for A's right child 'C'which is a root node for G and H. After visiting C, we go for
its left child'G'which is a root for node K. So next we visit left of G, but it does not have left
child so we go for G's right child 'K'. With this, we have completed node C's root andleft
parts.NextvisitC's right child 'H'which is therightmostchildinthe tree.Sowestop the process.
That means here we have visited in the order of A-B-D-I-J-F-C-G-K-Husing Pre-Order
Traversal.
3. Post- OrderTraversal(leftChild-rightChild-root ):
In Post-Order traversal, the root node is visited after left child and right child. In this
traversal,left childnode isvisitedfirst,then itsrightchildandthen itsrootnode.Thisis recursively
performed until the right most nodes are visited.
Algorithm:
Step-1: Visit the left subtree, using postorder.
Step-2:Visittherightsubtree,usingpostorder
Step-3: Visit the root.

Herewehavevisitedintheorder of I -J-D - F- B -K -G- H- C- AusingPost-Order Traversal.

64
65
PROGRAMS ON DATA STRUCTURES

1. WriteaCprogramtoimplementstackusing arrays.
2. WriteaCprogramtoimplementqueueusing arrays.
3. WriteaCprogramimplementthe followingStackapplications
a) infixintopostfix
b) Evaluationofthepostfixexpression
4. WriteaCprogramtoimplementthefollowingtypesof queues
a) Priorityqueue
b) Circularqueue
5. WriteaCprogramtoimplementtheSinglyLinkedList
6. WriteaCprogramtoimplementthedoublyLinkedList
7. WriteaCprogramtoimplementthefollowingsearch algorithms.
i)Linearsearchii)Binarysearch iii)Fibonaccisearch
8. WriteaCprogramtoimplementthesortingalgorithms.
9. Writea Cprogramtoimplementbinarytree usingarraysandtoperformbinary
traversals.
i) Inorder ii)preorder iii)postorder
10. WriteaCprogramtobalanceagiventree.

66
1:STACKUSINGARRAYS
#include<stdio.h>
#include<conio.h>
#include<process.h>
intch,max,item,top=-1,s[20];voidmenu(void);
voidpush(int);intpop(void);voiddisplay(void);voidmain()
{
clrscr();
printf("ENTERSTACKSIZE:");scanf("%d",&max);
menu();
getch();
}
voidmenu()
{
printf("1.PUSH\n2.POP\n3.EXIT\n");printf("ENTERYOURCHOICE:");
fflush(stdin);
scanf("%d",&ch);
switch(ch)
{
case1:printf("ENTERTHEELEMENT\n");scanf("%d",&item);
push(item);
menu();
break;
case2:item=pop();menu();
break;
case3:exit(0);
}
}
voidpush(int item)
{
if(top==max-1)
printf("STACKISOVERFLOW\n");else
{
top++;
s[top]=item;
}
display();
}
intpop()
{
if(top==-1)
{
printf("STACKISUNDERFLOW\n");return0;
}
else
{
item=s[top];top--;
}
display();returnitem;

67
}
voiddisplay()
{
inti;
printf("top-->");
for(i=top;i>=0;i--)
printf("%d\n\t",s[i]);
}
OUTPUT:
Enterstacksize:3
1. Push
2. Pop
3. Exit
Enter your choice:1
Enter the element: 3
Top: 3
1. Push
2. Pop
3. Exit
Enter your choice:1
Entertheelement:5
Top: 5
3
1. Push
2. Pop
3. Exit
Enter your choice:1
Entertheelement:9
Top:9 5 3
1. Push
2. Pop
3. Exit
Enter your choice: 1
Entertheelement:15
Stack is overflow
Top: 953
1. Push
2. Pop
3. Exit
Enter your choice: 3
Popped element is: 9
Top: 5 3
1. Push
2. Pop
3. Exit
Enter your choice: 2
Poppedelementis:5
Top: 3
1. Push

68
2. Pop
3. Exit
Enteryourchoice:2Stackis underflow
1. Push
2. Pop
3. Exit
Enteryourchoice:3

2.QUEUE USING ARRAYS

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>voidinsertion(void);voiddeletion(void);voiddisplay(void); int
q[10],n,i,f,r;
intf=0,r=0;voidmain()
{
int op;
clrscr();
printf("ENTERTHESIZEOFQUEUE:");scanf("%d",&n);
while(1)
{printf("\n1.INSERTION\n2.DELETION\n3.DISPLAY\n4.EXIT\n");
printf("ENTER YOUR OPTION:");
scanf("%d",&op);
switch(op)
{
case1:insertion();break;
case 2:deletion(); break;
case3:display();break;default:exit(0);
} } }
voidinsertion()
{
if(r>=n)
printf("QUEUEISOVERFLOW");else
{
r=r+1;
printf("\nENTERANELEMENTTOINSERT:");scanf("%d",&q[r]); if(f==0)
f=1;
} }
voiddeletion()
{
if(f==0)
printf("THEQUEUEISEMPTY");else
{
printf("THEDELETINGELEMENTIS:%5d",q[f]);f=f+1;
if(f>r)
f=0,r=0;
} }

69
voiddisplay()
{
if(f==0)
printf("QUEUEISEMPTY");else
for(i=f;i<=r;i++)
printf("%5d",q[i]);
}
OUTPUT:
Enterthesizeofqueue:2
1. Insertion
2. Deletion
3. Display
4. Exit
Enteryouroption: 1
Enteran elementtoinsert:q[1]:34
1. Insertion
2. Deletion
3. Display
4. Exit
Enteryouroption:334
1. Insertion
2. Deletion
3. Display
4. Exit
Enteryouroption: 4

3:STACK APPLICATIONS
a) INFIXINTOPOSTFIX
b) EVALUATIONOFTHEPOSTFIXEXPRESSION

Program:(a)#includ
e<stdio.h>
#include<conio.h>#
define MAX 50
char stack[MAX];
int top=-1
void push(char); char pop();
intpriority(char);voidmain()
{
chara[MAX],ch;inti;
clrscr();
printf("Enteraninfixexpression:\t");gets(a);
printf("\thepostfixexpressionforthegivenexpressionis:\t");for(i=0;a[i]!='\0';i++)
{
ch=a[i];
if((ch>='a')&&(ch<='z'))printf("%c",ch);
elseif(ch=='(')push(ch);elseif(ch==')')
{

70
while((ch=pop())!='(')
printf("%c",ch);
}
else
{
while(priority(stack[top])>priority(ch))
printf("%c",pop());
push(ch);
}
}
while(top>-1)printf("%c",pop());
printf("\n");
getch();
}
voidpush(charch)
{
if(top==MAX-1)
{
printf("STACKOVERFLOW");return;
}
else
{
top++;
stack[top]=ch;} }
char pop()
{
intx;if(top==-1)
{
printf("STACKEMPTY");
}
else
{x=stack[top];top--;}
return x;
}
intpriority(charch)
{
switch(ch)
{
case'^':return4;case'*':
case'/':return3;case'+':
case'-':return2;default:return 0;
}}
OUTPUT:
Enteraninfixexpression:
((a+b((b^c–d)))*(e–(a/c)))
Thepostfixexpressionforthegivenexpressionis: a b
bc^d-+eac/-*

71
Program:(b)#includ
e<stdio.h>
#include<conio.h>
#include<math.h>
#include<ctype.h>v
oid push(char);
char pop(void);
charex[50],s[50],op1,op2;inti,top=-1;
void main()
{
clrscr();
printf("Entertheexpression:");gets(ex);for(i=0;ex[i]!='\0';i++)
{
if(isdigit(ex[i]))push(ex[i]-48);else
{
op2=pop();
op1=pop();
switch(ex[i])
{
case'+':push(op1+op2);
break;
case'-':push(op1-op2);
break;
case'*':push(op1*op2);
break;
case'/':push(op1/op2);
break;
case'%':push(op1%op2);
break;
case'^':push(pow(op1,op2));
break;
} } }
printf("resultis:%d",s[top]);getch();
}
voidpush(chara)
{ s[++top]=a;}
char pop()
{return(s[top--]);
}

OUTPUT:

Entertheexpression:384 *2/+83----
Resultis:14

72
4:TYPES OF QUEUES
a).Priority queue
b).Circular queue

Program: (a)
#include<stdio.h>
#include<conio.h>
#include<malloc.h>typed
efstructnode
{
intpriority;
int info;
structnode *link;
}n;
n*getnode()
{
return((n*)malloc(sizeof(n)));
}
n*front=NULL,*temp=NULL,*ptr=NULL,*q=NULL;
void insertion();
voiddeletion();
void display();
void main()
{
int ch;
clrscr();
printf("\tMenu\n1.Insertion\n2.Deletion\n3.Display\n4.exit");
while(1)
{
printf("Enteryourchoice");
scanf("%d",&ch);switch(ch)
{
case1:insertion();
break;
case2:deletion();
break;
case3:display();
break;
case 4:exit();
default:printf("\nInvalidchoice"); break;
} } }
voidinsertion()
{intitem,item_prty;
temp=getnode();
printf("Enteritemtoinsert");
scanf("%d",&item);
printf("Enter item prority ");

73
scanf("%d",&item_prty);
temp->priority=item_prty;
temp->info=item;
if(front==NULL||item_prty>front->priority)
{
temp->link=front;
front=temp;
}
else
{
q=front;
while(q->link!=NULL&&q->link->priority>=item_prty)
q=q->link;
temp->link=q->link;
q->link=temp;
}
}
voiddeletion()
{if(front==NULL)
printf("Queueisunderflow");
else
{
temp=front;
printf("Deleteditemis%d\n",
temp->info);
front=front->link;
free(temp);
}
}
voiddisplay()
{
ptr=front;
if(front==NULL)
printf("Queueisunderflow");
else
{
printf("Queue is :\n");
printf("priorityitem:\n");
while(ptr!=NULL)
{
printf("%5d%5d\n",ptr->priority,ptr->info);
ptr=ptr->link;

}
}
}

OUTPUT:

74
1 -Insertanelementintoqueue
2 -Deletean elementfromqueue
3 -Displayqueueelements
4 -Exit
Enteryourchoice:1

Entervaluetobeinserted:20Enter
your choice: 1
Entervaluetobeinserted:45Enter
your choice: 1
Entervaluetobeinserted:89Enter
your choice: 3
8945 20
Enteryourchoice:1
Entervaluetobeinserted:56Enter
your choice: 3
895645 20
Enter your choice:
2Entervaluetodelete:45
Enter your choice: 3
8956 20
Enteryourchoice:4

Program: (b)
#include<stdio.h>
#include<conio.h>#defin
e max 3
intq[max],rear=-1,front=-1;
void main()
{intch;
clrscr();
do
{ printf("\nqueue implementation\n");
printf("1.insert2.delete3.display4.exit\n");
printf("enter your choice\n");
scanf("%d",&ch);
switch(ch)
{ case 1:insert(); break;
case 2:delete(); break;
case3:display();break;
case 4:exit(1);
default:printf("wrongchoice\n");break;
}
}while(ch<=4);
getch();
}
insert()
{intitem;

75
if(rear==max-1)
{printf("queueoverflow\n");}
else
{if(front==-1)
front=0;
printf("inserttheelementinqueue:");
scanf("%d",&item);
rear++;
q[rear]=item;
}
}
delete()
{if(front==-1)
{printf("queueunderflow\n");
}
else
{printf("elementdeletedfromqueueis:%d\n",q[front]);
front++;
if(front==max)
front=rear=-1;
}
}
display()
{ int i;
if(front==-1)
printf("queueisempty\n");
else
{printf("queueis:\n");
for(i=front;;i++)
{printf("%2d",q[i]);
if(i==rear)
return;
} }}

OUTPUT:
1. Insert
2. Delete
3. Display
4. Exit
Enteryourchoice:1
Enterelementtocqueue: 10
1. Insert
2. Delete
3. Display
4. Exit
Enteryourchoice:1
Enterelementtocircular queue:20
1. Insert
2. Delete

76
3. Display
4. Exit
Enteryourchoice:2
Deletedelementfromcircularqueueis:10
1. Insert
2. Delete
3. Display
4. Exit
Enteryourchoice:3
Elementsfromcircularqueueis:20
1. Insert
2. Delete
3. Display
4. Exit
Enteryourchoice:4

5:SINGLY LINKED LIST


Program:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>#include<alloc.
h>structnode
{
intdata;
structnode*link; };
typedefstructnode*pnode;pnodehead=NULL;
voidmenu(void);voidinsbeg(int);void delbeg(void);voidinsend(int);voiddelend(void); void
insafter(int,int); void delmid(int); void display(void); void main()
{
intch,x,pos;clrscr();while(1)
{
menu();
printf("enterurchoice\n");scanf("%d",&ch); switch(ch)
{
case1:printf("enterelementtoinsert\n");
scanf("%d",&x);
insbeg(x);
break;
case2:delbeg();
break;

case3:printf("enterelementtoinsert\n");
scanf("%d",&x);
insend(x);
break;
case4:delend();
break;
case5:printf("enterelement,posto insert\n");

77
scanf("%d%d",&x,&pos);
insafter(x,pos);
break;
case6:printf("enterpositionofelementtodelete\n");scanf("%d",&pos); delmid(pos);
break;
case7:display();
break;
case8:exit(0);
} } }
voidmenu()
{
printf("1.insbeg\n2.delbeg\n3.insend\n4.delend\n");
printf("5.insafter\n6.delmid\n7.display\n8.exit\n");
}
voidinsbeg(int x)
{
pnode ptr;
ptr=(pnode)malloc(sizeof(structnode));
ptr->data=x;
ptr->link=head;head=ptr;
}
voiddelbeg()
{
pnodetmp;intx;
if(head==NULL)
{
printf("listisempty\n");return;
}
tmp=head;
head=tmp->link;
printf("deletedelementis%d\n",tmp->data);
free(tmp);
}
voidinsend(int x)
{
pnode tmp,ptr;
ptr=(pnode)malloc(sizeof(structnode));
ptr->data=x;
ptr->link=NULL;if(head==NULL)
{
head=ptr;
}
else
{
tmp=head;
while(tmp->link!=NULL)
tmp=tmp->link;
tmp->link=ptr;

78
} }
voiddelend()
{
pnodeprev=NULL,ptr=head;
int x; if(head==NULL)
{
printf("listisempty\n");return;
}
while(ptr->link!=NULL)
{
prev=ptr;ptr=ptr->link;
}
if(prev==NULL)
head=NULL;
else
prev->link=NULL;
printf("deletednode:%d\n",ptr->data);
free(ptr);
}
voidinsafter(intx,intpos)
{
pnodetmp=head,ptr;
int i;for(i=1;i<pos;i++)
{
tmp=tmp->link;
if(tmp==NULL)
{
printf("positionoutofrange\n");return;
} }
ptr=(pnode)malloc(sizeof(structnode));
ptr->data=x;
ptr->link=tmp->link;
tmp->link=ptr;
}
voiddelmid(intpos)
{
pnodeprev=NULL,tmp=head;
int i;

if(head==NULL)
{
printf("listisempty\n");return;
}
for(i=0;i<pos;i++)
{
prev=tmp;tmp=tmp->link;
if(tmp==NULL)
{printf("positionoutofrange\n"); return;

79
} }

if(prev!=NULL)
prev->link=tmp->link;
else
head=tmp->link;
printf("deletedelement:%d\n",tmp->data);
free(tmp);
}
voiddisplay()
{
pnodeptr=head;
while(ptr!=NULL)
{
printf("%d-->",ptr->data);
ptr=ptr->link;
}
printf("\n");
getch();
}
OUTPUT:
1. Insbeg
2. elbeg
3. Insend
4. Delend
5. Insafter
6. Delmid
7. Display
8. Exit
Enteryourchoice:1
Enterelementtoinsert: 94
1. Insbeg
2. Delbeg
3. Insend
4. Delend
5. Insafter
6. Delmid
7. Display
8. Exit
Enteryourchoice:1
Enterelementtoinsert: 90
1. Insbeg
2. Delbeg
3. Insend
4. Deled
5. Insafter
6. Delmid
7. Display
8. Exit

80
Enteryourchoice5
Enterelement,Postoinsert
552

1. Insbeg
2. Delbeg
3. Insend
4. Delend
5. Insafter
6. Delmid
7. Display
8. Exit
Enteryourchoice 790->94->55->
1. Insbeg
2. Delbeg
3. Insend
4. Delend
5. Insafter
6. Delmid
7. Display
8. Exit
Enteryourchoice8

6:DOUBLYLINKEDLIST
Program:
#include<stdio.h>#include<conio
.h>structnode
{
structnode*prev;intdata;
struct node *nxt;
}
*head=NULL,*curr=NULL,*curr1=NULL,*p;

voidinsert(intpos)
{
intcount=1,i;p=head;
while(p->nxt!=NULL)
{
count++;p=p->nxt;
}
p=head;
if(pos<=count+1)
{
curr=(structnode*)malloc(sizeof(structnode));
printf("Enter the node:");
scanf("%d",&curr->data);
curr->nxt=NULL;
curr->prev=NULL;
if(head==NULL)

81
{
head=curr;}
elseif(pos==1)
{
head->prev=curr;
curr->nxt=head;
head=curr;}
else
{ for(i=1;i<(pos-1);i++)p=p->nxt;
curr->prev=p; curr->nxt=p->nxt;
p->nxt->prev=curr;
p->nxt=curr;
}
printf("\n%dinsertedatpos:%d!\n",curr->data,pos);
}
else
printf("\nEnteravalid position!");

}
voiddeletenode(intdata)
{
intfound=0;curr=head;if(head->data== data)
{
(head->nxt)->prev=NULL;head=head->nxt;
printf("\n%d deleted!\n",curr->data);
free(curr);
}
else
{
curr=curr->nxt;
while(curr->nxt!=NULL)
{
if(curr->data==data)
{
found=1;
break;
}
else
curr=curr->nxt;
}
if(found==1||curr->data==data)
{
curr1=curr->prev;curr1->nxt=curr->nxt;(curr->nxt)->prev=curr1;printf("\n%d
deleted!\n",curr->data); free(curr);
}
else
printf("\n%disnotpresentinthelist!\n",data);
} }
voiddisplay()

82
{
curr=head;
if(head==NULL)
printf("\nList is empty!\n"); else {
printf("\nList:\n");while(curr->nxt!=NULL){
printf("%d\t",curr->data); curr=curr->nxt;
}
printf("%d\n",curr->data);
}
}
voidmain()
{
intop,data;
clrscr();
printf("Creation of Doubly Linked List\n");
curr=(structnode*)malloc(sizeof(structnode));
curr->nxt=NULL;
curr->prev=NULL;printf("Enterthefirstnode:");scanf("%d",&curr->data);head=curr;
head->nxt=NULL; head->prev=NULL; do
{printf("\nDOUBLYLINKEDLISTOPERATIONS:\n1.Insertanode"); printf("\n2.Delete a
node\n3.Display\n4.Exit\n");
printf("\nSelectanoperation:");scanf("%d",&op);
switch(op)
{
case1:
{ printf("Enterthepositionwhereyouwanttoinsertthenode:");scanf("%d",&data);
insert(data); break;
}
case2:{
printf("Enterthenodetobedeleted:");scanf("%d",&data);
deletenode(data); break; }

case3: {
display();
break;}
case4:
break;
default:
printf("\nEnteravalid option!");
}
}while(op!=4);
getch();
}
OUTPUT:
Doublylinkedlistoperations
1. Insertnode
2. Deletenode
3. Display

83
4. Exit
Selectanoperation:1
Enterthepositiontoinsertnode:1Enterthenode:59 59
inserted at pos: 1
1. Insertnode
2. Deletenode
3. Display
4. Exit
Selectanoperation:4

7:SEARCHING ALGORITHMS

i)Linearsearchii)Binarysearch
iii)Fibonaccisearch

Program: (i)and (ii)


#include <stdio.h>
#include
<conio.h>#include<
stdlib.h> void
main()
{
Inta[10],n,flag=0,i,lb,ub,key,mid,ch;
clrscr();
printf("enterthesizeoftheelements\n");
scanf("%d",&n);
printf("entertheelements\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("enteranykeyelementtosearch\n");
scanf("%d",&key);
printf("menu\n");
printf("\n1.linear search\n2.binary search \n");
printf("enteryourchoice:\n");scanf("%d",&ch);
switch(ch)
{case1:for(i=0;i<n;i++)if(a[i]==key)
{
flag=1;
break;}
case2:for(lb=0,ub=n-1;lb<=ub;)
{
mid=(lb+ub)/2;
if(key==a[mid])
{
flag=1;
break;
}
elseif(key<a[mid])ub=mid-1;
else lb=mid+1;
}
84
break;
default:exit(0);
}
if(flag==1)
printf("seachissuccessful");
else
printf("searchisnotsuccessful\n");
getch();

}
OUTPUT:
Enterthesizeoftheelements5
Enter the elements 32 6 3 9 5
Enter any element to search 3
Menu
1. Linearsearch
2. BinarysearchEnteryourchoice:2
Search is successful

Program:(iii)
#include<stdio.h>
void main()
{
intn,a[50],i,key,loc,p,q,r,m,fk;
clrscr();
printf("\nenternumberelementstobeentered");
scanf("%d",&n);
printf("enterelements");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
printf("enterthekeyelement");
scanf("%d",&key);
fk=fib(n+1);
p=fib(fk);
q=fib(p);
r=fib(q) ;
m=(n+1)-(p+q);
if(key>a[p])
p=p+m;
loc=rfibsearch(a,n,p,q,r,key);
if(loc==0)
printf("keyisnotfound");
else
printf("%disfoundatlocation%d",key,loc);
getch();
}
intfib(int m)
{
inta,b,c;

85
a=0;
b=1;
c=a+b;
while(c<m)
{
a=b;
b=c;
c=a+b;
}
return b;
}
intrfibsearch(inta[],intn,intp,intq,intr,intkey)
{
int t;
if(p<1||p>n)
return 0;
elseif(key==a[p])
return p;
else if(key<a[p])
{
if(r==0)
return 0;
else
{
p=p-r;
t=q;
q=r;
r=t-r;
returnrfibsearch(a,n,p,q,r,key);
} }
else
{
if(q==1)
return 0;
else
{
p=p+r;
q=q-r;
r=r-q;
returnrfibsearch(a,n,p,q,r,key);
} } }

OUTPUT:
Enterthenumberelementstobeentered8 Enter
the elements 1 3 2 5 4 6 7 9
Enterthekeyelement9 8
is found at location 8

86
8:SORTINGALGORITHMS
Program:BubbleSort
#include<stdio.h>
#include<conio.h>#defin
e TRUE 1
#defineFALSE0
voidbubblesort(intx[],intn);voidmain()
{
intnum[10],i,n;
clrscr();
printf("Enterthenoofelements\n");scanf("%d",&n);
printf("Entertheelements\n");for(i=0;i<n;i++)scanf("%d",&num[i]);bubblesort(num,n); printf("sorted
elements are\n"); for(i=0;i<n;i++) printf("%d\t",num[i]);
getch();}
voidbubblesort(intx[],intn)
{
inthold,j,pass,K=TRUE;for(pass=0;pass<n-
1&&K==TRUE;pass++)
{
K=FALSE;
for(j=0;j<n-pass-1;j++)if(x[j]>x[j+1])
{
K=TRUE;
hold=x[j];
x[j]=x[j+1];
x[j+1]=hold;}}}
OUTPUT:
Entertheno ofelements5
Entertheelements 362359682
Sortedelementsare223365968

Program: selection sort


#include<stdio.h>#include<conio
.h>voidmain()
{
intn,i,j,a[10],min,t;
clrscr();
printf("enterhowmanyelements\n");scanf("%d",&n);
printf("entertheelements\n");for(i=0;i<n;i++)scanf("%d",&a[i]);for(i=0;i<n-1;i++)
{
min=i;
for(j=i+1;j<n;j++)
{
if(a[min]>a[j])
min=j;
}
t=a[i];
a[i]=a[min];
a[min]=t;

87
}
printf("thesortedelementsare\n");for(i=0;i<n;i++)
printf("%5d",a[i]);
getch();
}
OUTPUT:
Enterhowmanyelements5
Entertheelements 5648462335
Thesortedelementsare2335465698

Program: insertion sort


#include<stdio.h>#include<conio
.h>voidmain()
{
intn,i,a[10],t,j;
clrscr();
printf("enterhowmanyelements\n");
scanf("%d",&n);
printf("entertheelements\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=1;i<n;i++)
{
for(j=i;j>0;j--)
{
if(a[j]<a[j-1])
{
t=a[j];a[j]=a[j-1];a[j-1]=t;
} }}
printf("thesortedelementsare\n");for(i=0;i<n;i++)
printf("%5d",a[i]);
getch();
}
OUTPUT:
Enter how many elements 5
Entertheelements263698125
Thesortedelementsare512263698

Program:Quicksort
#include<stdio.h>
#include<conio.h>
voidquick(inta[10],intlb,intn);
void main()
{
intn,i,a[10];
clrscr();
printf("enterhowmanyelements \n");scanf("%d",&n);
printf("entertheelements\n");for(i=0;i<n;i++)scanf("%d",&a[i]);quick(a,0,n-1);
printf("the sorted elements are \n"); for(i=0;i<n;i++)

88
printf("%d\n",a[i]);getch();
}
voidquick(inta[],intlb,intub)
{
inti,j,t,key;
if(lb>ub)return;i=lb; j=ub;
key=lb;
while(i<j)
{
while(a[key]>a[i])
i++;
while(a[key]<a[j])j--;
if(i<j)
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
t=a[j];
a[j]=a[key];
a[key]=t;
quick(a,0,j-1);
quick(a,j+1,ub);
}
OUTPUT:
Enterhowmanyelements5
Entertheelements 6523896871
Thesortedelementsare2365687189

program:heap sort
#include<conio.h>
void maxheap(int
[],int,int);voidbuildmaxheap(int
a[],intn)
{
inti;for(i=n/2;i>=1;i--)
{
maxheap(a,i,n);
}
}
voidmaxheap(inta[],inti,intn)
{
intR,L,largest,t;
L=2*i;R=2*i+1;
if((L<=n)&&(a[L]>a[i]))largest=L;
else largest=i;
if((R<=n)&&(a[i]>a[largest]))largest=R;

89
if(largest!=i)
{
t=a[i];
a[i]=a[largest];
a[largest]=t;
maxheap(a,largest,n);
}
}
voidheapsort(inta[],intn)
{
inti,temp;
buildmaxheap(a,n);
for(i=n;i>=2;i--)
{
temp=a[1];
a[1]=a[i];
a[i]=temp;maxheap(a,1,i-1);
}
}
vodmain()
{
inta[50],i,n;clrscr();
printf("Enter the size of array : "); scanf("%d",&n);
printf("Entertheelementsofarray\n");for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
heapsort(a,n);
printf("sortedarrayis\n");for(i=1;i<=n;i++)
{
printf("%d\t",a[i]);
}
getch();
}
OUTPUT:
Enterthesize ofarray:4
Entertheelements ofarray:35219517
Sortedarrayis:17213595
Program: merge sort
#include<stdio.h>
#include<conio.h>
voidmerge(int[],int,int,int); void
part(int [],int ,int );
intmain()
{
intarr[30];
inti,size;
printf("\n\t-------Mergesortingmethod --------- \n\n");
printf("Entertotalno.ofelements:");scanf("%d",&size);

90
for(i=0;i<size;i++)
{printf("Enter%delement:",i+1);
scanf("%d",&arr[i]);
}
part(arr,0,size-1);
printf("\n\t-------Mergesortedelements --------- \n\n");for(i=0;i<size;i++)

printf("%d",arr[i]);getch();
return 0;
}
voidpart(intarr[],intmin,intmax)
{
intmid;if(min<max)
{
mid=(min+max)/2;
part(arr,min,mid);

part(arr,mid+1,max);
merge(arr,min,mid,max);
}
}
voidmerge(intarr[],intmin,intmid,intmax)
{
inttmp[30];
inti,j,k,m;
j=min;
m=mid+1;
for(i=min;j<=mid&&m<=max;i++)
{
if(arr[j]<=arr[m])
{
tmp[i]=arr[j];
j++;
}
else
{
tmp[i]=arr[m];
m++;
}
}
if(j>mid)
{
for(k=m;k<=max;k++)
{
tmp[i]=arr[k];
i++;
}
}
else

91
{
for(k=j;k<=mid;k++)
{
tmp[i]=arr[k];
i++;
}
}
for(k=min;k<=max;k++)arr[k]=tmp[k];
}
OUTPUT:
Mergesortingmethod
Entertotalnoofelements:4
Enter 4 elements:
35
95
17
21
Mergesortedelements:17213595

9. BINARYTREETRAVERSALS
i) Preorder ii) Inorder iii)Postorder
Program:
#include<stdio.h>
#include<conio.h>
#include<malloc.h>#include<stdli
b.h>structnode
{
intdata;
struct node *left; struct node *right; };
typedefstructnode*pnode;pnoderoot=NULL; void
insert(intval)
{
pnodep,q,t;t=(pnode)malloc(sizeof(structnode));t->left=t->right=NULL;
t->data=val; if(root==NULL)
{
root=t;
return;
}
p=root;q=NULL;
while(p)
{
if(p->data==val)
{
return;
}
q=p;
if(val<p->data)p=p->left;
else if(val>p->data)
p=p->right;

92
}
if(val<q->data)q->left=t;if(val>q->data)q->right=t;
}
intsearch(intkey)
{
pnodep=root;
while(p)
{
if(p->data==key) return
1;elseif(key<p->data)p=p-
>left;
elseif(key>p->data)p=p->right;
}
return0;
}
voidinorder(pnodep)
{
if(p==NULL)
return;inorder(p->left);printf("%3d",p->data);inorder(p->right);
}
voidpreorder(pnodep)
{
if(p==NULL)
return;
printf("%3d",p->data);
preorder(p->left);
preorder(p->right);
}
voidpostorder(pnodep)
{
if(p==NULL)
return;
postorder(p->left);
postorder(p->right);
printf("%3d",p->data);
}
intmain()
{
intch,x;
clrscr();
while(1)
{
printf("\n1.insertion");
printf("\n2.inorder");
printf("\n3.preorder");
printf("\n4.postorder");
printf("\n5.search");
printf("\n6.exit");
printf("\nenterurchoice\n");
scanf("%d",&ch);
93
switch(ch)
{
case1:printf("enteranelements\n");scanf("%d",&x);
insert(x);
break;
case 2:inorder(root); break;
case 3:preorder(root); break;
case4:postorder(root);break;
case5:printf("enterkeyelements\n");
scanf("%d",&x);
if(search(x))
printf("found"); else
printf("notfound");break;
case 6:exit(0);
} } }
OUTPUT:

Treetraversal
Enterthenumberoftermstoadd7Entertheitem15
Enterthe item 7Enterthe item 9Enterthe item 18Enterthe item 6 Enterthe item 21Enter the
item 2
Inordertraversal2 679 15 1821
Preordertraversal15 76 291821
Postordertraversal2 69 7 21 18 15

10. BALANCEA TREE

Program:
#include <stdio.h>
#include<stdlib.h>
struct btnode
{
intvalue;
struct btnode*l;
structbtnode*r;
};

typedefstructbtnodeN;
N*bst(intarr[],intfirst,intlast); N*
new(int val);
voiddisplay(N*temp);
int main()
{
intarr[] ={10,20, 30,40,60,80, 90};
N *root = (N*)malloc(sizeof(N));
intn=sizeof(arr)/sizeof(arr[0]),i;

printf("Givensortedarrayis\n");
for (i = 0;i < n;i++)

94
printf("%d\t",arr[i]);
root=bst(arr,0,n- 1);
printf("\nThe preordertraversalofbinarysearchtreeisasfollows\n"); display(root);
printf("\n");
return 0;
}
N*new(intval)
{
N*node= (N*)malloc(sizeof(N));

node->value=val;
node->l = NULL;
node->r=NULL;
return node;
}

N*bst(intarr[],intfirst,int last)
{
intmid;
N*temp=(N*)malloc(sizeof(N));
if (first > last)
returnNULL;
mid = (first + last) / 2;
temp=new(arr[mid]);
temp->l= bst(arr, first,mid - 1);
temp->r=bst(arr,mid+1,last);
return temp;
}
voiddisplay(N*temp)
{
printf("%d->",temp->value);
if (temp->l != NULL)
display(temp->l);
if(temp->r!=NULL)
display(temp->r);
}
OUTPUT:

Givensortedarray is
10 20 30 40 60 80 90
Thepreordertraversalofbinarysearchtreeisasfollows 40-
>20->10->30->80->60->90

95

You might also like