Data Structures With C (New Syllabus)
Data Structures With C (New Syllabus)
WITH C
affiliated to Acharaya Nagarjuna University
BSC- II SEM
P.Y.KUMAR
M.C.A,M.Tech,M.Phil..,
www.anuupdates.org
2
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
DATA REPRESENTATION
Various methods are used to represent data in computers. Hierarchical
layers of data structure are used to make the use of data structure easy and
efficient. The basic unit of data representation is a bit. The value of a bit
asserts one of the two mutually exclusive possibilities–0 or 1. Various
combinations of two values of a bit are used to represent data in a different
manner in different systems. Eight bits together form one byte which
represents a character and one or more than one characters are used to
form á string. A string can thus be seen as a data structure that emerges
through several layers of data structures
The representation of a string can be made easier (i.e. working with the
strings without bothering about the NULL (‘\0’) character at the end of the
string) by wrapping it into another data structure which takes care of such
intricacies and supports a set of operations that allows us to perform
various string related operations like storing and fetching a string joining
two strings, finding the length of strings, etc The use of the concrete data
structure during design creates lot of difficulties and requires much. more
efforts, such a problem can be avoided by using abstract data type in the
design process. Bui before moving to the discussion of concepts of Abstract
Data Types (ADTS), let us discuss how the primitive or basic data types of
any language (i.e. integer, character, etc.) are internally represented in the
memory
www.anuupdates.org
5
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
Integer Representation
An integer is the basic data type which is commonly used for storing
negative as well as non-negative integer numbers. The non-negative data is
represented using binary number system. In this, each bit position
represents the power of 2. The rightmost bit position represents 2" which is
1, the next represents 2 which is 2, then 2' which is 4 and so on. For
example, 00100110 represents the integer as 2' + 2- + 2 = 2 + 4 + 32 = 38.
For negative binary numbers the methods of representation used are one's
complement and two's complement
In one's complement method the number is represented by complementing
each bit, i.e. changing each bit in its value to the opposite bit setting. For
example, 00100 | 10 represents 38, after complementing, it becomes
1101100 1 which is used to represent -38.
In two's complement method, 1 is added to one's complement representation
of the negative number. For example. -38 is represented by 1101100 1
which on adding 1 to it will become
11011001
+1
11011010, which represents –38 in Ino's complement notation
ATOMIC TYPE
Generally, a data structure is represented by a memory block, which has
two parts:
Data storage
Address storage
This facilitates in storing the data and relating it to some other data by
means of storing pointers in the address part.
An atomic type data is a data structure that contains only the data items
and not the pointers. Thus, for a list of data items, several atomic type
nodes may exist each with a single data item coresponding to one of the
legal data types. The list is maintained using a list node which contains
pointers to these atomic nodes and a type indicator indicating the type of
atomic node to which it points. Whenever a test node is inserted in the list,
its address is stored in the next free element of the list of pointers.
a list of atomic nodes maintained using list of nodes. In each node, type represents
the type of data stored in the atomic node to which the list node points. I
stands for integer type, 2 for real number and 3 for character type or any
different assumption can be made at implementation level to indicate different data
types.
REFINEMENT STAGES
The best approach to solve a complex problem is to divide it into smaller
parts such that each part becomes an independent module which is easy to
manage. An example of this approach is the System Development Life Cycle
(SDLC) methodology. This helps in understanding the problem, analyzing
solutions, and handling the problems efficiently.
The principle underlying writing large programs is the top-down refinement.
While writing the main program, we decide exactly how the work will be
divided into various functions and then, in the refinement process, it is
further decided what will be the task of each function, and what inputs are
to be given and results to be obtained. The data and actions of the
functions are specified precisely. Similarly, the purpose of studying Abstract
data types is to find out some general principles that will help in designing
efficient programs. There exists a similarity between the process of top down
refinement of algorithms and the top-down specification of the data
structures. In algorithm design, we begin with the problem and slowly
specify more details until we develop a complete program. In data
specification, we begin with the selection of mathematical concepts and
abstract data types required for our problem, and slowly specify more details
until finally we can describe our data structures in terms of programming
language.
The application or the nature of problem determines the number of
refinement stages required in the specification process. Different problems
have different number of refinement stages, but in general, there are four
levels of refinement processes:
Conceptual or abstract level
Algorithmic or data structures
Programming or implementation
Applications
Conceptual Level
At this level we decide how the data is related to each other, and what
operations are needed. Details about how to store data and how various
operations are performed on that data are not decided at this level
www.anuupdates.org
8
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
The first two levels are often called conceptual. The middle two levels can be
called algorithmic as they are concerned with representing data and the
operations performed on the same. Last level is basically concerned with
programming
at the conceptual level, the queue has been selected as an abstract data type
and further at the next level circular queue has been selected, as this could
provide the best solution. Last level shows the operations which can be
performed on the data, for the Airport simulation,
www.anuupdates.org
9
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
Example: “Arrays, Stacks, Queues and linked lists” are the examples
for linear data structures.
Example: “Trees & Graphs” are the examples for the non-linear data
structures.
Linear Data Structures: The data structure where data items are organized
sequentially or linearly where data elements attached one after another is
called linear data structure. Data elements in a liner data structure are
traversed one after the other and only one element can be directly reached
while traversing. All the data items in linear data structure can be traversed
in single run.
These kind of data structures are very easy to implement because memory
of computer is also organized in linear fashion.
Examples of linear data structures are:
Arrays,
Stack,
Queue
Linked List.
An arrays is a collection of data items having the same data types.
A Stack is a LIFO (Last In First Out) data structure where element
that added last will be deleted first. All operations on stack are
performed from on end called TOP. A Queue is a FIFO (First In First
Out) data structure where element that added first will be deleted
first.
In queue, insertion is performed from one end called REAR and
deletion is performed from another end called FRONT.
A Linked list is a collection of nodes, where each node is made up of a
data element and a reference to the next node in the sequence.
www.anuupdates.org
12
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
Non Linear Data Structures: The data structure where data items are not
organized sequentially is called non linear data structure. In other words, A
data elements of the non linear data structure could be connected to more
than one elements to reflect a special relationship among them. All the data
elements in non linear data structure can not be traversed in single run.
Examples of non linear data structures are:
Trees
Graphs
A tree is collection of nodes where these nodes are arranged
hierarchically and form a parent child relationships.
A Graph is a collection of a finite number of vertices and an edges that
connect these vertices. Edges represent relationships among vertices
that stores data elements.
Difference Between Linear and Non Linear Data Structure:
Every item is related to its previous Every item is attached with many
and next item. other items.
Single dimensional arrays have only one subscript or index where as multi-
dimensional arrays may have more than one subscript or index.
For Example:
int a[20];
float b[10]; //single dimensional or one dimensional arrays
int a[3][3]; // double dimensional or table or two dimensional
int a[3][3][3]; // multi-dimensional
Declaration of Arrays:
Syntax:
datatype array_name [no. of items];
OR
datatype array_name [index];
Ex:
int a [10]; // integer array
Note:
Array name should not contain any spaces.
Index of the array should not be zero or less than zero.
Array size is fixed.
Array index starts from zero always.
www.anuupdates.org
14
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
11 33 22 55 44 88 66 55 77 99 100 101
0 1 2 3 0 1 2 3 0 1 2 3
Initialization of array:
int a[5]={11,12,13,14,15};
int a[]={11,22,33};
char a[7]={“sairam”};
float b[4]={1.2,3.5,7};
For example, some of the valid double dimensional arrays are written as
below:
int a[10][10];
float b[50][50];
char name[10][20];
Also you can declare two-dimensional array in static form i.e. these type of
array declarations have fixed value or constant value. The syntax used for
static two dimensional array is as follows:
For example, suppose you want to assign some fixed value to a variable
array named table by using the static two-dimensional array as.
Eg:
int a[3][2][4];
www.anuupdates.org
16
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
Operations on Arrays:
1. Creation of array
2. Initialization of array
3. Accepting data into array
4. Displaying contents of array
5. Insertions
6. Deletions
7. Search
8. Sort
Advantages of arrays:
As arrays store all the elements in continuous locations, it becomes
easy to access all the elements.
Arrays allow the user to store elements of same type in sequential
manner.
Array elements can be accessed randomly (need not to follow any
order).
Arrays avoid no. of variables & their naming.
Disadvantages of arrays:
Array size is fixed. The user cannot grew or shrink the size
dynamically.
Optimum utilization of memory may not be achieved (i.e., there is a
scope for wasting the memory).
Arrays allow only similar kind of items as data.
Characteristics of a Data Structure
Correctness:
Data structure implementation should implement its interface correctly.
Time Complexity:
Running time or the execution time of operations of data structure must be
as small as possible.
Space Complexity:
Memory usage of a data structure operation should be as little as possible.
Operations on Data Structures: The operations involve in data
structure are as follows.
Create: Used to allocate/reserve memory for the data element(s).
Destroy: This operation de allocate /destroy the memory space
assigned to the specified data structure.
Selection: Accessing a particular data within a data structure.
Update: For updating (insertion or deletion) of data in the data
structure.
www.anuupdates.org
17
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
Searching: Used to find out the presence of the specified data item in
the list of data
Sorting: Process of arranging all data items either in ascending or in
descending order.
Merging: Process of combining data items of two different sorted lists
of data items into a single list.
1 Triplet Representation
2 Linked Representation
Triplet Representation
In this representation, we consider only non-zero values along with their row
and column index values. In this representation, the 0th row stores total
rows, total columns and total non-zero values in the matrix. For example,
consider a matrix of size 5 X 6 containing 6 number of non- zero values.
This matrix can be represented as shown in the fig:
In above example matrix, there are only 6 non-zero elements ( those are 9, 8,
4, 2, 5 & 2) and matrix size is 5 X 6. We represent this matrix as shown in
the above image. Here the first row in the right side table is filled with values
5, 6 & 6 which indicates that it is a sparse matrix with 5 rows, 6 columns &
6 non-zero values. Second row is filled with 0, 4, & 9 which indicates the
www.anuupdates.org
18
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
value in the matrix at 0th row, 4th column is 9. In the same way the
remaining non-zero values also follows the similar pattern.
Linked Representation
In linked representation, we use linked list data structure to represent a
sparse matrix. In this linked list, we use two different nodes namely header
node and element node. Header node consists of three fields and element
node consists of five fields as shown in the image...
STACKS
A stack is a linear list in which insertions & deletions are made at one end
called top. Stack follows LIFO manner in order to store data. LIFO means
Last In First Out. As an example to stack, consider a set of plates placed one
over the other or a pile of books.
Operations on Stack:
Push
Pop
Show
www.anuupdates.org
19
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
Is empty
Is Full
4 4 4 4 4 50 4
3 3 3 3 40 3 40 3
2 2 2 30 2 30 2 30 2
1 1 20 1 20 1 20 1 20 1
0 10 0 10 0 10 0 10 0 10 0
For each insertion, we check out whether the stack is full or not. If it is
FULL stop the process otherwise continue pushing items.
Procedure to perform push operation:
Note: Here ‘MAX’ is the value of maximum number of items that can be
stored in a stack.
www.anuupdates.org
20
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
POP:
In pop operation, the elements of stack are removed one after other by
decrementing the value of top. Once after removing the last item from the
stack, pop operation is terminated. For each deletion, we check out whether
the stack is empty or not.
50 4 4 4 4 4 4
40 3 40 3 3 3 3 3
30 2 30 2 30 2 2 2 2
20 1 20 1 20 1 20 1 1 1
10 0 10 0 10 0 10 0 10 0 0
Applications of Stack:
Used in operating systems, compilers other system software
Processor itself maintains a stack in order to execute applications.
Used for expression evaluations.
Used in regular function calls, nested function calls and recursive
function calls.
www.anuupdates.org
21
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
ans) abc*def^/g*-h*+
2) 5,6,2,+,*,12,4,/,-
ans) 5 5
6 5,6
2 5,6,2
+ 5,8
* 40
12 40,12
4 40,12,4
/ 40,3
- 37
22
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
( (
(( ((
A (( A
+ ((+ A
B ((+ AB
) ( AB+
* (* AB+
( (*( AB+
D (*( AB+D
^ (*(^ AB+D
( (*(^( AB+D
E (*(^( AB+DE
- (*(^(- AB+DE
F (*(^(- AB+DEF
) (* AB+DEF-
(^
) AB+DEF-^
(*
) AB+DEF-^*
23
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
QUEUES
Types of Queues:
Queues
Circular Queues
Double Ended Queues (De-Queues)
Priority Queues
Queues
A queue is a linear list where items may be inserted or deleted in FIFO manner.
FIFO means First In First Out. That is, the item placed in the first, will be
accessed and removed first from the queue. Similarly the item placed last will
be accessed and removed last. A queue uses two pointers called front, rear to
perform storage & retrieval operations.
In other words, queue has two ends: front and rear. All the insertions into
queue are made at ‘rear’ end and all the deletions are done at ‘front’ end.
24
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
A queue is called as linear data structure or static data structure or
homogeneous data structure. The no. Of items in a queue is fixed. The
operating system itself maintains an instruction queue while executing user
programs.
Operations on Queues:
Create or Initialize a queue.
Insert an item into a queue (Insertq () or Enqueue())
Delete an item from a queue (Deleteq()).
Display all the items (show ()).
Check whether Queue is empty or not (isempty())
Check whether Queue is full or not (isfull())
Initially declaration & initializing the front and rear pointers is to be done.
Enqueue:(Insertq) Storing elements one after the other into the queue is
possible at this level of operation using the rear pointer. Increment each time
an item is placed in the queue.
The process of adding an element into the queue is known as Enqueue. The
following steps should be taken to enqueue (insert) data into a queue .
0 1 2 3 4 0 1 2 3 4
10
r =-1 f = 0 f=r=0
10 20 10 20 30
f r f r
10 20 30 40 10 20 30 40 50
Dequeue Operation(Deletions):
This operation allows removing of elements from the queue one by one. Here we
use front end (or pointer) to remove each item. For each removal front is
incremented by 1. The process of removing items from the queue is done until
the queue becomes EMPTY. That is, when the queue becomes empty, the
deletion process is terminated.
f r f r
0 1 2 3 4 0 1 2 3 4
30 40 50 40 50
f r f r
0 1 2 3 4 0 1 2 3 4
50
if(front==rear)
BEGIN
front=0;rear=-1;
END
else
front=front+1;
End.
Applications of queue
There are various applications of computer science, which are performed using
data structure queue. This data structure is usually used in simulation,
various features of operating system, multiprogramming platform systems and
different type of scheduling algorithm are implemented using queues. Round
robin technique is implemented using queues. Printer server routines, various
applications software are also based on queue data structure.
The operating system itself uses a queue called an Instruction Queue & a Message
Queue.
In a network, there will be a print queue that manages the documents to be printed
Circular Queues( It is also called as “Ring buffer”.)
In regular queues, there is a situation where the user cannot insert items
through the positions are free. That is, for example, consider a queue with full
of data.
f r
10 20 30 40 50 60 70
Perform Deletion operation on the above queue for 3 times. The following is the
resultant queue.
27
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
40 50 60 70
f r
Now there are 3 empty locations, but still the user cannot store any more items
because the rear pointer cannot be incremented further.
In order to overcome the above problem and to reutilize the empty locations,
circular queues have come into picture.
Step1: Empty CQueue
So that in CIRCULAR QUEUE we can again insert new values at the deleted
positions
30
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
The above insertions and deletions are done as like normal QUEUE. Now we
can see the insertions and deletions are not doing by the normal
QUEUE….they are:
Priority Queue
Often the items added to a queue have a priority associated with them; this
priority determines the order in which they are removed from the queue. Higher
priority items are removed first. Such a queue is said to be priority queue.
Priority queues are used in Process Control Systems.
Applications:
Band width management : pq can be used to manage the limited
resources such as band width on transmission line from a network
router
Discrete event simulation: pq is to manage events in a discrete event
simulation . The events are added to the queue with their simulation
time used as priority
Relationship to store the algorithms: the semantics of pq naturally
suggested to storing methods (heap sort)
LINKED LIST
A linked list is a sequence of nodes connected by means of pointers. In other
words a linked list is a collections of nodes that are connected using pointers. If
the memory is allocated in the memory before the execution of the program, it
is fixed and cannot be changed. We have to use an alternative strategy to
allocate memory only when it is required. There is a special kind of data
structure called “Linked List “ that provides more flexible storage system.
struct node
{
data type data member;
struct node *next node pointer;
};
Ex:
struct node
{
int data;
struct node *next;
};
1) Create
2) Insert
a) Insert at begin
b) Insert at Location
c) Insert at end
3) Delete
a) Delete at begin
b) Delete at Location
c) Delete at End
4) Concat
5) Merge
6) Search
7) Sort
8) Display
head
35
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
Insert at Begin:
Insert at Middle:
Insert at End:
Delete at Begin:
Delete at Middle:
36
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
Delete at End:
Insert at Begin:
Insert at Middle:
Insert at End:
38
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
Delete at Begin:
Delete at Middle:
Delete at End:
Doubly Linked List contains a link element called first and last.
Each link carries a data field(s) and two link fields called next and
prev.
Each link is linked with its next link using its next link.
Each link is linked with its previous link using its previous link.
The last link carries a link as null to mark the end of the list.
Basic Operations
Following are the basic operations supported by a list.
Advantages:
Optimum utilization of memory can be achieved.
Easy to implement insert & delete operations.
As it is dynamic, any number of data items can be stored.
It can hold different kinds of data in each node.
Garbage collection can be achieved.
Disadvantages:
As the nodes are connected sequentially, it is difficult to
perform random access.
Memory may be wasted in terms of pointers.
Differences between arrays & linked lists
TREES
A tree is a nonlinear data structure and is generally defined as a nonempty
finite set of elements, called nodes such that:
T contains a distinguished node called root of the tree.
The remaining elements of tree form an ordered collection of zero or
more disjoint subsets called sub tree.
Q) Explain Binary Tree and its properties ?
A binary tree is defined as a finite set of elements, called nodes, such that:
Tree is empty (called the null tree or empty tree) or
Tree contains a distinguished node called root node, and the remaining nodes
form an ordered pair of disjoint binary trees.
43
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
1. Root: In a tree data structure, the first node is called as Root Node. Every
tree must have root node. We can say that root node is the origin of tree data
structure. In any tree, there must be only one root node. We never have
multiple root nodes in a tree.
44
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
2. Edge: In a tree data structure, 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.
3. Parent: In a tree data structure, the node which is predecessor of any node
is called as PARENT NODE. In simple words, the node which has branch from
it to any other node is called as parent node. Parent node can also be defined
as "The node which has child / children".
4. Child: In a tree data structure, the node which is descendant of any node
is called as CHILD 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.
45
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
5. Siblings: In a tree data structure, nodes which belong to same Parent are
called as SIBLINGS. In simple words, the nodes with same parent are called as
Sibling nodes.
6. Leaf: In a tree data structure, the node which does not have a child is called
as LEAF 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.
46
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
7. Internal Nodes: In a tree data structure, the node which has atleast one
child is called as INTERNAL Node. In simple words, an internal node is a node
with atleast one child.
In a tree data structure, nodes other than leaf nodes are called as Internal
Nodes. The root node is also said to be Internal Node, if the tree has more than
one node. Internal nodes are also called as 'Non-Terminal' nodes.
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 1 and the children of the nodes which are
at Level 1 will be at Level 2 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).
47
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
10. Height: In a tree data structure, the total number of edges from leaf node
to a particular node in the longest path is called as HEIGHT of 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 to a leaf node in the longest path is said to be Depth of the tree. In
simple 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'.
48
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
12. Path: In a tree data structure, the sequence of Nodes and Edges from one
node to another node is called as PATH between that two Nodes. Length of a
Path is total number of nodes in that path. In below example the path A - B - E
- J has length 4.
13. Sub Tree: In a tree data structure, each child from a node forms a sub
tree recursively. Every child node will form a sub tree on its parent node.
.
49
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
Binary tree: Here, binary name itself suggests two numbers, i.e., 0 and 1. In a
binary tree, each node in a tree can have utmost two child nodes. Here, utmost
means whether the node has 0 nodes, 1 node or 2 nodes.
51
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
A node can be created with the help of a user-defined data type known
as struct, as shown below:
struct node
{
int data;
struct node *left;
struct node *right;
}
The above is the node structure with three fields: data field, the second field is
the left pointer of the node type, and the third field is the right pointer of the
node type.
AVL tree
It is one of the types of the binary tree, or we can say that it is a variant of the
binary search tree. AVL tree satisfies the property of the binary tree as well as of
the binary search tree. It is a self-balancing binary search tree that was invented
by Adelson Velsky Lindas. Here, self-balancing means that balancing the heights of
left sub tree and right sub tree. This balancing is measured in terms of
the balancing factor.
We can consider a tree as an AVL tree if the tree obeys the binary search tree
as well as a balancing factor. The balancing factor can be defined as
the difference between the height of the left subtree and the height of the right
subtree. The balancing factor's value must be either 0, -1, or 1; therefore, each
node in the AVL tree should have the value of the balancing factor either as 0, -
1, or 1.
52
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
Preorder:
1) Process the root R.
2) Traverse the left sub tree of R in preorder.
3) Traverse the right sub tree of R in preorder.
Inorder:
1) Traverse the left sub tree of R in inorder.
2) Process the root R.
3) Traverse the right sub tree of R in inorder.
Postorder:
1) Traverse the left sub tree of R in postorder.
2) Traverse the right sub tree of R in postorder.
3) Process the root R.
If a node is in Jth location of array, then its left child is stored in the
location (2J) and its right child in the location (2J+1)
The maximum size that is required for an array to store a tree is 2 power
(d+1) – 1, where d is the depth of the binary tree.
A B C D E F G H I J
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Here the node C at location 3 has child F at 6 th (2*3) location and the right
child at 7th (2*3+1) location. Since the depth of the binary tree is 4 the required
array size is 32-1 = 31.
The main advantage of this method is no complex pointer maintenance and we can
easily identify the locations.
The basic disadvantage is that growing and shrinking of a tree cannot be made
efficiently.
NULL is represented by (X). A binary tree with N nodes contains N+1 NULL
pointers. In essence all leaf nodes has two NULL pointers. Each node is
associated with one information field and two pointer fields, LeftPtr and
RightPtr, which denote the pointers to the left child and the right child of the
node.
54
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
The disadvantages are, wasted space due to NULL pointers and finding a
parent of a particular node is difficult.
B C
Inorder traversal: -
Step 1: (check if the tree is empty by verifying root pointer p)
If (p==NULL)
Print tree is empty
Step 2: if=(leftptr (p)! =NULL) then call
Inorder (leftptr (p))
Step 3: print data (p)
Step 4: if (rightptr (p)! =NULL) then call
Inorder (rightptr (p))
Step 5: return
Preorder traversal: -
Step 1: (check if the tree is empty by verifying the root pointer p)
If (p==NULL)
Print tree is empty
Step 2: print data (p)
Step 3: if (leftptr (p)! =NULL) then call
Preorder (leftptr (p))
Step 4: if (rightptr (p)! =NULL) then call
Preorder (rightptr (p))
Step 5: return
Postorder traversal: -
Step 1: (check if the tree is empty by verifying the root pointer p)
If (p==NULL)
55
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
Print tree is empty
Step 2: if (leftptr (p)! =NULL) then call
Preorder (leftptr (p))
Step 3: if (rightptr (p)! =NULL) then call
Postorder (rightptr (p))
Step 4: print data (p)
Step 5: return
Step 1: - initially push NULL on to stack. Then ser ptr=the of T. Here prt is
pointer variable.
Step 2: - proceed down the left most path rooted at ptr=a, pushing the nodes A,
B, D, G, K onto stack (No other nodes are pushed into the stack since k has no
left child)
Step 3: - Back tracking the nodes K, G and D are poped and processed.
Stack=Ө, a, b, (we stop the processing at D since D has right child) then set
ptr=h.
Step 4: - process down the left most part rooted at ptr =h pushing the nodes H
and L onto the stack. Stack=Ө, a, b, h, l (No other nodes is pushed on the stack
L has no left child)
Step 5: - Back traking the nodes l and H are poped and processed.
Stack =Ө, a, b
(We stop the processing at H. Since H has right child then set ptr=M, the right
child of H)
Step 6: - process down the left most path rooted at ptr=m, pushing a node m
onto the stack.
Stack =o, a, b, m.
(No other nodes is pushed on to stack)
Since m has no left child.
Step 7: - Backtracking the nodes m, b and a are poped and processed. Stack=Ө
(No other elements of stack is poped. A have right child) set ptr=c.
Step 8: - process down the left most path rooted at ptr=c pushing the nodes c
and e onto the stack. Stack=c, e, ө.
Step 9: - Backtracking node e is poped and processed and E has no child and
node c is poped and processed. (Since c has no right child so NULL (ө) is poped
from stack) The result will be k, g, d, l, h, m, b, a, e, c.
56
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
Algorithm: -
Inorder (info, left, right, root)
Preorder: -
Preorder (info, left, right, root)
(end of if structure)
(end of if structure)
Step6:- Exit
Post order:-
Explanation:-
Step1:- initially ,push Null on to stack and set ptr=A, the root of T.
Step2:- proceed down the left most path rooted at ptr=A, pushing the
nodes A,B,D,G and K onto stack . Further more, since A has a right child
c, push -c on to stack after A but before B ,and since D has a right child H,
push -H on to stack after D but before G. this yields:
Stack : θ,A,-C ,B,D,H,-M,L.
Step5:- [Back tracking] pop and process L, but only pop –M this leaves
Stack: θ, A, -C, B, D, H.
Now ptr = -M . Reset ptr=n and return to step (a) .
Step6:- proceed down the left-most path rooted at ptr=M.
Now, only M is pushed on to stack. This yields :
stack: θ,A,-C,B,D,H,M.
Step7:- [Back tracking] pop and process M,H,D and B, but only pop -C.
This leaves:
stack: θ,A
Now ptr= -C. Reset ptr=c and return to step(a)
Step8:-proceed down the left most path rooted at ptr=c first c is pushed
onto stack and then E,
stackθ,A,C,E.
58
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
step9:- [Back tracing] pop and process E,C and A. When NULL is poped,
stack is empty and the algorithm is completed.
a) loc=NULL and par=NULL it will indicates that item the root is empty
c) loc=NULL and par!=NULL it will indicates that item is not in T and can
be added to T as a child of the node n with loc par
if root=NULL , them set loc = NULL and par =NULL and return.
Else
(end if statement)
if item=info[ptr], then
Step6:-if item<info[ptr],then
Else
[end of if structure]
60
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
[end of step 4 loop]
step7:-[search unsuccessful]
step8:-exit
step1:- call find (info, left, right, root, item, loc, par)
step2:- if loc!=NULL, then exit,
step3:- (copy item into new node in avail list )
a) if avail=NULL, them write overflow and exit
b) set new=avail, avail=left[avail]and info [new]=item
c) set loc =new, left[new]=NULL and right [new]=NULL
step4:- (Add item to tree )
if par=NULL ,then
set root=new
else
if item<info[par], then
set left[par]=new
else
set right [par]= new
(end of if statement )
step5:- exit
(The pointer suc gives the location of the inorder successor of n and
parsuc gives the location of the parent of the inorder successor)
step1:- (find suc and parsuc)
a) set ptr=right(loc)and save=loc
b) Repeat while left[ptr]!=NULL
set save=ptr and ptr=left[ptr]
(end of loop )
c) set suc=ptr and parsuc=save
step2:-(delete inorder successor)
call casea (info, left, right, root, suc, parsuc)
step3:- (replace node n by its inorder successor )
a) if par!=NULL,
if loc=left[par]then
set left[par]=suc
else
set right [par]=suc
(end if statement)
else
set root=suc
(end of if)
b) set left[suc] =left[loc] and right[suc]=right[loc]
step4:-return.
1. The right NULL pointer of each leaf node can be replaced by a thread to
the successor of that node under in order traversal called a right thread,
and the tree will called a right threaded tree or right threaded binary
tree.
2. The left NULL pointer of each node can be replaced by a thread to the
predecessor of that node under in order traversal called left thread, and
the tree will called a left threaded tree.
3. Both left and right NULL pointers can be used to point to predecessor
and successor of that node respectively, under in order traversal. Such a
tree is called a fully threaded tree.
A threaded binary tree where only one thread is used is also known as one way
threaded tree and where both threads are used is also known as two way
threaded tree.
63
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
64
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
GRAPHS
A graph is a set of vertices & a set of edges. Vertices may be called as nodes. In
some other words, a graph is a collection of set of vertices denoted by V and a
set of edges called E
B
A
c
D
Directed Graph: A directed graph consists of vertices and edges that have
directions. It is also referred as a digraph. The diagram beside this definition is
an example for digraph.
65
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
Weighted graph: A graph with a set of vertices & edges that have certain
values as weights is said to be weighted graph. If it posses directions on edges
then it is referred as weighted digraph.
6 7 5
5
7 c
c 4
D
D
4
Connected Graph Non-Connected Graph
A B
A
c c
D
Eg:-
a
b d
c
66
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
Weekly connected graph:-
In a weekly connected graph the direction of a graph is ignored and
connectedness is defined as if the graph is undirected
v1 v2 v4
v3
Tree graph :-
A connected graph tree without cycles called as tree graph
Indegree outdegree:-
1
The no of edges coming from the node is called out degree. Here out degree of 2
is two The no of edges enter to the node is called in degree
Q) Graph Representations:
A graph can be represented either by using arrays or linked list representation.
i.e., Graphs may be represented in two different ways:
Adjacency Matrix
Adjacency List
Adjacency Matrix: Array representation of a graph is nothing but adjacency
matrix. In adjacency matrix, if you find an edge between two distinct nodes,
place a ‘1’ otherwise place a ‘0’.
Consider the above-directed graph, and Aij is the adjacency matrix.
67
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
=0 otherwise
C 0 0 0 1
B C
A B C D
A 0 1 1 1
B 1 0 1 1
C 1 1 0 1
D 1 1 1 1
B C
D
68
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
A B C D
A 0 1 1 1
B 0 0 0 1
C 0 0 0 1
D 0 0 0 0
Path matrix: : let G be simple directed graph with m nodes v1,v2,…,vn the
path matrix is square matrix p=v[I,j] is a defined as follows p[I,j]=1 if there is a
path from v[i]to v[j] otherwise zero
Applications of Graphs
Since they are powerful abstractions, graphs can be very important in modeling
data.
Social network graphs: Graphs that represent who knows whom, who
communicates with whom or other relationships in social structures
Transportation networks: Graph networks are used by many map
programs such as Google maps, Bing maps and now Apple IOS 6 maps
to find the best routes between locations.
Utility graphs. The power grid, the Internet, and the water network are
all examples of graphs where vertices represent connection points, and
edges the wires or pipes between them.
Document link graphs. The best known example is the link graph of the
web, where each web page is a vertex, and each hyperlink a directed
edge.
Network packet traffic graphs. Vertices are IP (Internet protocol)
addresses and edges are the packets that flow between them.
Robot planning. Vertices represent states the robot can be in and the
edges the possible transitions between the states.
Neural networks. Vertices represent neurons and edges the synapses
between them. Neural networks are used to understand how our brain
works and how connections change when we learn.
Semantic networks. Vertices represent words or concepts and edges
represent the relationships among the words or concepts.
Graphs in compilers. Graphs are used extensively in compilers. They
can be used for type inference, for so called data flow analysis, register
allocation and many other purposes.
Q) Graph Traversal Mechanisms
Graph nodes can be traversed in two different ways:
v1
v3
v2
v6
v4 v5
v7
v8
Explanation:-
Step1:- Visit v1 node adjacency vertices of v1 is ,v2,v3,v8.Let us pick us v2
adjacency vertices are v1,v4,v5.Here v1 is already visited then we pick up v4 .It
adjacency vertices are v2,v8. v2 is already visited then we pickup v8 . It
adjacency vertices are v4, v5, v1,v6, v7. v4, v1 are already visited let us pick up
v5. It’s adjacency vertices are v2, v8. Both are already visited so backtrack. V6,
v7 are unvisited in the list of v8 .We visit v6 it’s adjacency vertices are v8,v3.
Let us we choose v3 it’s adjacency vertices v1,v6,v7. Now we visit v7 them stack
is empty .The DFS travel is
v1
v3
v2
v6
v4 v5
v7
v8
71
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
Algorithm:
1. Initialize all nodes to the ready state (STATUS=1).
2. Put the starting node A in STACK and change its status to the Waiting state
(STATUS=2).
3. Repeat steps 4 and 5 until STACK is empty.
4. Remove the TOP node N of STACK. Process N and change the status of N to the
processed state (STATUS=3).
5. Add all the neighbors of N that are in the ready state (STATUS=1) on to the TOP,
and change their status to the waiting state (STATUS=2).
[End of step 3 loop.]
6.Exit.
Example:
72
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
73
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
74
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
75
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
V1
V2 V3
V4 V5 V6 V7
V8
76
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
We start with V1. Its adjacent vertices are V2, V8, V3. We visit all one by
one.
V1 V1 V1
V2 V8 V3
V2 V3
V8 V4 V5
V1
V2 V8 V3
V4 V5 V6 V7
77
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
V1
V11
V2 V8 V3
V2 V8 V3
V8 V3 V4 V5 V4 V5
V6 V7
V3 V4 V5 V6 V7
V4 V5 V6 V7
V5 V6 V7
V6 V7
V7
Empty Q
Example:
79
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
’
80
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
81
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
Path: a path sequence of vertices that map a source vertex to the destination
vertex.
Cycle: A cycle is a path in which the source & destination vertices are same.
Adjcent Vertices: A vertex v1 is said be adjacent to vertex v2 if there exists an
edge (v1, v2) or (v2, v1).
Degree: The number of edges incident on a vertex determine its degree.
Indegree & Outdegree: The number of edges that are coming towards a vertex
is said be the “In Degree” & the number of edges that are going away from the
vertex is said be the “Out degree”.
Complete Graph: A graph G is said be complete or fully connected if there is
path from every vertex to every other vertex. A complete graph with n vertices
will have n (n-1)/2 edges.
Connected Graph: A graph is said to be connected if there exists a path from
any vertex to any vertex of the graph other wise such a graph is said to be
unconnected graph.
Explain Spanning Tree ? Find Minimum Spanning Cost
Q)Spanning Tree: A tree T is said be spanning tree of a connected graph G (V,
E) such that,
1. Every vertex of G belongs to an edge T and
2. The edges in T form a tree.
Minimum cost spanning Tree: A connected graph can have more than one
spanning tree; if we select or calculate the spanning that can be constructed
with low cost is said to be minimum cost spanning tree.
82
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
Tree graph: A graph is said to be a tree graph if it has 2 properties:
1) It is connected, and
2) There are no cycles in the graph.
Path Matrix: A matrix that holds a ‘1’ (one) if there exists a path between any
two nodes of a graph otherwise it holds a ‘0’ (zero). It is also known as
‘reachability matrix’.
Hamitonian Path: A path is said to be Hamiltonian path if that passes
through each of the vertices in a graph exactly once.
Algorithm Purpose
Krushkal’s algorithm To find the min. cost spanning
Tree
Prim’s algorithm To find the min. cost spanning
Tree
Dijkstra’s Algorithm To find single source shortest
paths on a weighted digraph.
Warshall’s algorithm To find the path matrix of a
graph
BFS & DFS algorithms Graph traversal algorithms
Warshall’s algorithm: -
A directed graph G with M nodes is maintained in memory by it adjacency
matrix A. This algorithm finds the path matrix P of the graph G.
Step1: - Repeat for I, j=1,2…m (initialize of P)
If A [I, j]=0 then set p [I, j] =0
Else
Set p [I, j]=1
(end loop)
Step2: - repeat step3&4 for k=1,2,3 …….m (updates p)
Step3: - repeat step 4 for I =1, 2,3…m
Step4: - repeat for j=1,2,3…m
set p [I, j]=p[I, j] v (p[I, k] ^ p[k, j])
(end of loop)
83
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
(end of step3 loop)
(end of step2 loop)
Step5: - exit.
Recursion Iteration
1.It is a technique of defining 1. It is a process of executing itself
anything in terms of itself. a statement or a set of statements
repeatedly until a given condition
satisfied.
2. There must a terminating 2. Iteration involves 4 clear steps:
condition to stop the process. initialization, condition, execution
and updation.
3. Not all problems have recursive 3. Any recursive problem can be
solution. solved iteratively.
4. Recursion will be a overhead on 4. It is a process that utilizes less
the processor as it consumes much cpu time & space to execute itself.
memory & time.
5. Recursive concepts can be 5. Relatively bigger in code compare
implemented in less code. to Recursion.
84
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
6. Requires stack to implement 6. Does not use any stack data
itself. structure.
Example
Sorted: V1
Remove edges: (V1,V2) , (V1, V3) and (V1,V4)
Updated indegrees:
86
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
V2: 0
V3: 1
V4: 1
V5: 2
Indegree
V1 0
V2 1 0
V3 2 1 1 0
V4 2 1 0
V5 2 2 1 0 0
Improved algorithm
After the initial scanning to find a vertex of degree 0, we need to scan
only those vertices whose updated indegrees have become equal to zero.
For all edges (U,V) update the indegree of V, and put V in the queue if the
updated indegree is 0.
If a graph G is not a connected graph, then it cannot have any spanning tree.
Suppose a graph G with n vertices then the MST will have (n – 1) edges,
assuming that the graph is connected. A minimum spanning tree (MST) for a
weighted graph is a spanning tree with minimum weight .That is all the
vertices in the weighted graph will be connected with minimum edge with
minimum weights.
Two algorithms can be used to obtain a minimum spanning tree of a connected
weighted and undirected graph.
Q) Kruskal‟s Algorithm
Explain KRUSKAL’S ALGORITHM
1. This is a one of the popular algorithm and was developed by Joseph
Kruskal. To create a minimum cost spanning trees, using Kruskalls, we
begin by choosing the edge with the minimum cost and add it to the
spanning tree. In the next step, select the edge with next
2. lowest cost, and so on, until we have selected (n – 1) edges to form the
complete
3. spanning tee. The only thing of which beware is that we don‟t form any
cycles as we add edges to the spanning tree.
ALGORITHM
Suppose G = (V, E) is a graph, and T is a minimum spanning tree of graph G.
1. Initialize the spanning tree T to contain all the vertices in the graph G but no
edges.
89
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
2. Choose the edge e with lowest weight from graph G.
3. Check if both vertices from e are within the same set in the tree T, for all
such sets of T.If it is not present, add the edge e to the tree T, and replace the
two sets that this edge connects.
4. Delete the edge e from the graph G and repeat the step 2 and 3 until there is
no more edge to add or until the panning tree T contains (n-1) vertices.
5. Exit
It finds a subset of the edges that forms a tree that includes every vertex,
where the total weight of all the edges in the tree is minimized.
90
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
This algorithm is directly based on the MST( minimum spanning tree)
property.
ALGORITHM
2. Choose an edge e = (v1, v2) of G such that v2 not equal to v1 and e has
smallest weight among the edges of G incident with v1.
3. Select an edge e = (v2, v3) of G such that v2 is not equal to v3 and e has
smallest weight among the edge of G incident with v2.
4. Suppose the edge e1, e2, e3, ...... ei Then select an edge ei + 1 = (Vj, Vk) such
that
(b) Vk ∉ {v1, v2, v3, ...... vi, vi + 1} such that ei+1 has smallest weight among
the edge of G
6. Exit
91
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
We find that 27 is smaller than 33 and these two values must be swapped.
Next we compare 33 and 35. We find that both are in already sorted positions.
We know then that 10 is smaller 35. Hence they are not sorted.
We swap these values. We find that we have reached the end of the array. After one
iteration, the array should look like this −
93
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
Iteration-2:
To be precise, we are now showing how an array should look like after each
iteration. After the second iteration, it should look like this −
Iteration-3:
Notice that after each iteration, at least one value moves at the end.
Iteration-4:
And when there's no swap required, bubble sorts learns that an array is
completely sorted.
Step 2: Consider first element from the unsorted list and insert that element
into the sorted list in order specified.
Step 3: Repeat the above process until all the elements from the unsorted list
are moved into the sorted list.
Example:
95
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
96
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
Step by Step Process: The selection sort algorithm is performed using following
steps...
Step 1: Select the first element of the list (i.e., Element at first position in the list).
Step 2: Compare the selected element with all other elements in the list.
Step 3: For every comparison, if any element is smaller than selected element (for Ascending
order), then these two are swapped.
Step 4: Repeat the same procedure with next position in the list till the entire list is sorted.
Example:
97
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
98
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
99
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
Scanning from right to left, the first number visited that has value less than 50
is 30 thus exchange both of them.
Scanning from left to right, the first number visited that has value greater than
50 is 60, so exchange both of them.
100
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
Scanning from right to left, the first number visited that has value less than 50
is 45, so exchange both of them.
Scanning from left to right, the first number visited that has value greater than
50 is 80, so exchange both of them.
After Scanning, the number 50 is placed in its proper position and we get
sublists, sublist-1 and sublist-2. Sublist-2 has value greater than 50 while
sublist-1 has value lesser than 50, the whole process is repeated for both the
sublists to obtained,
After applying the same method again and again for new sublist until we get
the elements that cannot be sorted further, the final list that we get is the
sorted list as shown below:
Algorithm:
Merge-sort( A[0….n-1])
If(n>1)
Mergesort(B[0…[n/2]-1])
Mergesort(C[0…[n/2]-1])
Merge(B,C,A)
Procedure:
We know that merge sort first divides the whole array iteratively into equal
halves unless the atomic values are achieved. We see here that an array of 8
items is divided into two arrays of size 4.
This does not change the sequence of appearance of items in the original. Now
we divide these two arrays into halves.
102
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
We further divide these arrays and we achieve atomic value which can no more
be divided.
Now, we combine them in exactly the same manner as they were broken down
with a sorted order.
In the next iteration of the combining phase, we compare lists of two data
values, and merge them into a list of found data values placing all in a sorted
order.
After the final merging, the list should look like this –
Searching
Searching is the process of finding some particular element in the list. If the
element is present in the list, then the process is called successful and the
process returns the location of that element, otherwise the search is called
unsuccessful.
There are two popular search methods that are widely used in order to search
some item into the list. However, choice of the algorithm depends upon the
arrangement of the list.
Linear Search
Binary Search
103
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
Linear Search
Linear search is the simplest search algorithm and often called sequential
search. In this type of searching, we simply traverse the list completely and
match each element of the list with the item whose location is to be found. If
the match found then location of the item is returned otherwise the algorithm
return NULL.
Linear search is mostly used to search an unordered list in which the items are
not sorted. The algorithm of linear search
Algorithm
o LINEAR_SEARCH(A, N, VAL)
o Step 1: [INITIALIZE] SET POS = -1
o Step 2: [INITIALIZE] SET I = 1
o Step 3: Repeat Step 4 while I<=N
o Step 4: IF A[I] = VAL
SET POS = I
PRINT POS
Go to Step 6
[END OF IF]
SET I = I + 1
[END OF LOOP]
o Step 5: IF POS = -1
PRINT " VALUE IS NOT PRESENTIN THE ARRAY "
[END OF IF]
o Step 6: EXIT
Binary Search
Binary search is the search technique which works efficiently on the sorted
lists. Hence, in order to search an element into some list by using binary
search technique, we must ensure that the list is sorted.
Binary search follows divide and conquer approach in which, the list is divided
into two halves and the item is compared with the middle element of the list. If
the match is found then, the location of middle element is returned otherwise,
104
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
we search into either of the halves depending upon the result produced
through the match.
Another technique to improve search efficiency for a sorted file is indexed sequential search. But it
involves an increase in the amount of memory space required. An auxiliary table called an index, is set
aside in addition to a sorted file. Each element in the index table consists of a key Kindex and pointer to
the record in the field that corresponds to the kindex. The elements in the index, as well as elements in
the file, must be sorted on the file.
105
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
The algorithm used for searching an indexed sequential file is simple and straight. Let r, k and key be
defined as before. Let k index be an array of the keys in the index, and let pindex be the array of
pointers within the index to the actual records in the file, and the size of index is also taken in a variable.
The indexed sequential search can be explained as the following example in the figure.
The advantage of the indexed sequential method is that items in the table can be examined sequentially
if all records in the file have to be accessed, yet the search time for particular items is reduced. A
sequential search is performed on the smaller index rather than on the large table. Once the index
position is found, the search is made on the record table itself.
Deletion from an indexed sequential table can be most easily by flagging deleted entries. When
sequential searching is done deleted items are ignored. The item is deleted from the original table.
Insertion into an indexed sequential table may be difficult as there may not be any place between two
table entries which may lead to a shift to a large number of elements.
106
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
printf("\n -------------------------------------------------\n");
while(choice != 4)
{
printf("\nChose one from the below options...\n");
printf("\n1.Push\n2.Pop\n3.Show\n4.Exit");
printf("\n Enter your choice \n");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
push();
break;
}
case 2:
{
pop();
break;
}
case 3:
{
show();
break;
}
case 4:
{
printf("Exiting. .... ");
break;
}
default:
107
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
{
printf("Please Enter valid choice ");
}
};
}
}
void push ()
{
int val;
if (top == n-1 )
printf("\n Overflow");
else
{
printf("Enter the value?");
scanf("%d",&val);
top = top +1;
stack[top] = val;
}
}
void pop ()
{
if(top == -1)
printf("Underflow");
else
{
printf("the delted value =%d\n",stack[top]);
top = top -1;
}
}
void show()
{
for (i=top;i>=0;i--)
{
printf("%d\n",stack[i]);
}
if(top == -1)
{
printf("\nStack is empty\n");
}
}
108
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
}
printf("Item pushed");
}
}
void pop()
{
int item;
struct node *ptr;
if (head == NULL)
{
printf("Underflow");
}
else
{
item = head->val;
ptr = head;
head = head->next;
free(ptr);
printf("Item popped");
}
111
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
}
void display()
{
int i;
struct node *ptr;
ptr=head;
if(ptr == NULL)
{
printf("Stack is empty\n");
}
else
{
printf("Printing Stack elements \n");
while(ptr!=NULL)
{
printf("%d\n",ptr->val);
ptr = ptr->next;
}
}
}
112
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
}
void lastinsert()
{
struct node *ptr,*temp;
int item;
ptr = (struct node*)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
printf("\nEnter value?\n");
scanf("%d",&item);
ptr->data = item;
if(head == NULL)
{
ptr -> next = NULL;
head = ptr;
printf("\nNode inserted");
}
else
{
temp = head;
while (temp -> next != NULL)
{
temp = temp -> next;
}
temp->next = ptr;
ptr->next = NULL;
printf("\nNode inserted");
}
119
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
}
}
void randominsert()
{
int i,loc,item;
struct node *ptr, *temp;
ptr = (struct node *) malloc (sizeof(struct node));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
printf("\nEnter element value");
scanf("%d",&item);
ptr->data = item;
printf("\nEnter the location after which you want to insert ");
scanf("\n%d",&loc);
temp=head;
for(i=0;i<loc;i++)
{
temp = temp->next;
if(temp == NULL)
{
printf("\ncan't insert\n");
return;
}
}
ptr ->next = temp ->next;
temp ->next = ptr;
printf("\nNode inserted");
}
}
void begin_delete()
{
struct node *ptr;
if(head == NULL)
{
printf("\nList is empty\n");
120
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
}
else
{
ptr = head;
head = ptr->next;
free(ptr);
printf("\nNode deleted from the begining ...\n");
}
}
void last_delete()
{
struct node *ptr,*ptr1;
if(head == NULL)
{
printf("\nlist is empty");
}
else if(head -> next == NULL)
{
head = NULL;
free(head);
printf("\nOnly node of the list deleted ...\n");
}
else
{
ptr = head;
while(ptr->next != NULL)
{
ptr1 = ptr;
ptr = ptr ->next;
}
ptr1->next = NULL;
free(ptr);
printf("\nDeleted Node from the last ...\n");
}
}
void random_delete()
{
struct node *ptr,*ptr1;
int loc,i;
121
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
printf("\n Enter the location of the node after which you want to
perform deletion \n");
scanf("%d",&loc);
ptr=head;
for(i=0;i<loc;i++)
{
ptr1 = ptr;
ptr = ptr->next;
if(ptr == NULL)
{
printf("\nCan't delete");
return;
}
}
ptr1 ->next = ptr ->next;
free(ptr);
printf("\nDeleted node %d ",loc+1);
}
void search()
{
struct node *ptr;
int item,i=0,flag;
ptr = head;
if(ptr == NULL)
{
printf("\nEmpty List\n");
}
else
{
printf("\nEnter item which you want to search?\n");
scanf("%d",&item);
while (ptr!=NULL)
{
if(ptr->data == item)
{
printf("item found at location %d ",i+1);
flag=0;
}
else
122
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
{
flag=1;
}
i++;
ptr = ptr -> next;
}
if(flag==1)
{
printf("Item not found\n");
}
}
void display()
{
struct node *ptr;
ptr = head;
if(ptr == NULL)
{
printf("Nothing to print");
}
else
{
printf("\nprinting values .............\n");
while (ptr!=NULL)
{
printf("\n%d",ptr->data);
ptr = ptr -> next;
}
}
}
123
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
if(head==NULL)
{
ptr->next = NULL;
ptr->prev=NULL;
ptr->data=item;
head=ptr;
}
else
{
ptr->data=item;
ptr->prev=NULL;
ptr->next = head;
head->prev=ptr;
head=ptr;
126
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
}
printf("\nNode inserted\n");
}
}
void insertion_last()
{
struct node *ptr,*temp;
int item;
ptr = (struct node *) malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
printf("\nEnter value");
scanf("%d",&item);
ptr->data=item;
if(head == NULL)
{
ptr->next = NULL;
ptr->prev = NULL;
head = ptr;
}
else
{
temp = head;
while(temp->next!=NULL)
{
temp = temp->next;
}
temp->next = ptr;
ptr ->prev=temp;
ptr->next = NULL;
}
}
printf("\nnode inserted\n");
}
127
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
void insertion_specified()
{
struct node *ptr,*temp;
int item,loc,i;
ptr = (struct node *)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\n OVERFLOW");
}
else
{
temp=head;
printf("Enter the location");
scanf("%d",&loc);
for(i=0;i<loc;i++)
{
temp = temp->next;
if(temp == NULL)
{
printf("\n There are less than %d elements", loc);
return;
}
}
printf("Enter value");
scanf("%d",&item);
ptr->data = item;
ptr->next = temp->next;
ptr -> prev = temp;
temp->next = ptr;
temp->next->prev=ptr;
printf("\nnode inserted\n");
}
}
void deletion_beginning()
{
struct node *ptr;
if(head == NULL)
{
printf("\n UNDERFLOW");
}
128
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
else if(head->next == NULL)
{
head = NULL;
free(head);
printf("\nnode deleted\n");
}
else
{
ptr = head;
head = head -> next;
head -> prev = NULL;
free(ptr);
printf("\nnode deleted\n");
}
}
void deletion_last()
{
struct node *ptr;
if(head == NULL)
{
printf("\n UNDERFLOW");
}
else if(head->next == NULL)
{
head = NULL;
free(head);
printf("\nnode deleted\n");
}
else
{
ptr = head;
if(ptr->next != NULL)
{
ptr = ptr -> next;
}
ptr -> prev -> next = NULL;
free(ptr);
printf("\nnode deleted\n");
}
129
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
}
void deletion_specified()
{
struct node *ptr, *temp;
int val;
printf("\n Enter the data after which the node is to be deleted : ");
scanf("%d", &val);
ptr = head;
while(ptr -> data != val)
ptr = ptr -> next;
if(ptr -> next == NULL)
{
printf("\nCan't delete\n");
}
else if(ptr -> next -> next == NULL)
{
ptr ->next = NULL;
}
else
{
temp = ptr -> next;
ptr -> next = temp -> next;
temp -> next -> prev = ptr;
free(temp);
printf("\nnode deleted\n");
}
}
void display()
{
struct node *ptr;
printf("\n printing values...\n");
ptr = head;
while(ptr != NULL)
{
printf("%d\n",ptr->data);
ptr=ptr->next;
}
}
void search()
{
130
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
struct node *ptr;
int item,i=0,flag;
ptr = head;
if(ptr == NULL)
{
printf("\nEmpty List\n");
}
else
{
printf("\nEnter item which you want to search?\n");
scanf("%d",&item);
while (ptr!=NULL)
{
if(ptr->data == item)
{
printf("\nitem found at location %d ",i+1);
flag=0;
break;
}
else
{
flag=1;
}
i++;
ptr = ptr -> next;
}
if(flag==1)
{
printf("\nItem not found\n");
}
}
}
131
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
{
printf("Queue is overflow..");
}
else
{
rear=(rear+1)%max; // rear is incremented
queue[rear]=element; // assigning a value to the queue at the r
ear position.
}
}
switch(choice)
{
case 1:
case 3:
display();
}}
return 0;
}
135
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
// insert method
void insert(int data,int priority)
{
NODE *temp,*q;
// delete method
void del()
{
NODE *temp;
// condition to check whether the Queue is empty or not
if(front == NULL)
printf("Queue Underflow\n");
else
{
temp = front;
printf("Deleted item is %d\n", temp->info);
front = front->link;
free(temp);
}
// display method
void display()
{
NODE *ptr;
ptr = front;
if(front == NULL)
printf("Queue is empty\n");
else
{
printf("Queue is :\n");
printf("Priority Item\n");
while(ptr != NULL)
{
printf("%5d %5d\n",ptr->priority,ptr->info);
ptr = ptr->link;
}
}
}
/*End of display*/
137
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
// main method
int main()
{
int choice, data, priority;
do
{
printf("1.Insert\n");
printf("2.Delete\n");
printf("3.Display\n");
printf("4.Quit\n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("Enter the data which is to be added in the queue : ");
scanf("%d",&data);
printf("Enter its priority : ");
scanf("%d",&priority);
insert(data,priority);
break;
case 2:
del();
break;
case 3:
display();
break;
case 4:
break;
default :
printf("Wrong choice\n");
}
}
while(choice!=4);
return 0;
}
138
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
Output
if(head==NULL)
{
ptr->next = NULL;
ptr->prev=NULL;
ptr->data=item;
head=ptr;
}
else
{
ptr->data=item;
ptr->prev=NULL;
ptr->next = head;
head->prev=ptr;
head=ptr;
}
printf("\nNode inserted\n");
141
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
}
}
void insertion_last()
{
struct node *ptr,*temp;
int item;
ptr = (struct node *) malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
printf("\nEnter value");
scanf("%d",&item);
ptr->data=item;
if(head == NULL)
{
ptr->next = NULL;
ptr->prev = NULL;
head = ptr;
}
else
{
temp = head;
while(temp->next!=NULL)
{
temp = temp->next;
}
temp->next = ptr;
ptr ->prev=temp;
ptr->next = NULL;
}
}
printf("\nnode inserted\n");
}
void insertion_specified()
{
142
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
struct node *ptr,*temp;
int item,loc,i;
ptr = (struct node *)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\n OVERFLOW");
}
else
{
temp=head;
printf("Enter the location");
scanf("%d",&loc);
for(i=0;i<loc;i++)
{
temp = temp->next;
if(temp == NULL)
{
printf("\n There are less than %d elements", loc);
return;
}
}
printf("Enter value");
scanf("%d",&item);
ptr->data = item;
ptr->next = temp->next;
ptr -> prev = temp;
temp->next = ptr;
temp->next->prev=ptr;
printf("\nnode inserted\n");
}
}
void deletion_beginning()
{
struct node *ptr;
if(head == NULL)
{
printf("\n UNDERFLOW");
}
else if(head->next == NULL)
{
143
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
head = NULL;
free(head);
printf("\nnode deleted\n");
}
else
{
ptr = head;
head = head -> next;
head -> prev = NULL;
free(ptr);
printf("\nnode deleted\n");
}
}
void deletion_last()
{
struct node *ptr;
if(head == NULL)
{
printf("\n UNDERFLOW");
}
else if(head->next == NULL)
{
head = NULL;
free(head);
printf("\nnode deleted\n");
}
else
{
ptr = head;
if(ptr->next != NULL)
{
ptr = ptr -> next;
}
ptr -> prev -> next = NULL;
free(ptr);
printf("\nnode deleted\n");
}
}
void deletion_specified()
144
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
{
struct node *ptr, *temp;
int val;
printf("\n Enter the data after which the node is to be deleted : ");
scanf("%d", &val);
ptr = head;
while(ptr -> data != val)
ptr = ptr -> next;
if(ptr -> next == NULL)
{
printf("\nCan't delete\n");
}
else if(ptr -> next -> next == NULL)
{
ptr ->next = NULL;
}
else
{
temp = ptr -> next;
ptr -> next = temp -> next;
temp -> next -> prev = ptr;
free(temp);
printf("\nnode deleted\n");
}
}
void display()
{
struct node *ptr;
printf("\n printing values...\n");
ptr = head;
while(ptr != NULL)
{
printf("%d\n",ptr->data);
ptr=ptr->next;
}
}
void search()
{
struct node *ptr;
int item,i=0,flag;
145
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
ptr = head;
if(ptr == NULL)
{
printf("\nEmpty List\n");
}
else
{
printf("\nEnter item which you want to search?\n");
scanf("%d",&item);
while (ptr!=NULL)
{
if(ptr->data == item)
{
printf("\nitem found at location %d ",i+1);
flag=0;
break;
}
else
{
flag=1;
}
i++;
ptr = ptr -> next;
}
if(flag==1)
{
printf("\nItem not found\n");
}
}
}
146
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
if(head==NULL)
{
ptr->next = NULL;
ptr->prev=NULL;
ptr->data=item;
head=ptr;
}
else
{
ptr->data=item;
ptr->prev=NULL;
ptr->next = head;
head->prev=ptr;
head=ptr;
}
printf("\nNode inserted\n");
}
149
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
}
void insertion_last()
{
struct node *ptr,*temp;
int item;
ptr = (struct node *) malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
printf("\nEnter value");
scanf("%d",&item);
ptr->data=item;
if(head == NULL)
{
ptr->next = NULL;
ptr->prev = NULL;
head = ptr;
}
else
{
temp = head;
while(temp->next!=NULL)
{
temp = temp->next;
}
temp->next = ptr;
ptr ->prev=temp;
ptr->next = NULL;
}
}
printf("\nnode inserted\n");
}
void insertion_specified()
{
struct node *ptr,*temp;
int item,loc,i;
150
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
ptr = (struct node *)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\n OVERFLOW");
}
else
{
temp=head;
printf("Enter the location");
scanf("%d",&loc);
for(i=0;i<loc;i++)
{
temp = temp->next;
if(temp == NULL)
{
printf("\n There are less than %d elements", loc);
return;
}
}
printf("Enter value");
scanf("%d",&item);
ptr->data = item;
ptr->next = temp->next;
ptr -> prev = temp;
temp->next = ptr;
temp->next->prev=ptr;
printf("\nnode inserted\n");
}
}
void deletion_beginning()
{
struct node *ptr;
if(head == NULL)
{
printf("\n UNDERFLOW");
}
else if(head->next == NULL)
{
head = NULL;
free(head);
151
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
printf("\nnode deleted\n");
}
else
{
ptr = head;
head = head -> next;
head -> prev = NULL;
free(ptr);
printf("\nnode deleted\n");
}
}
void deletion_last()
{
struct node *ptr;
if(head == NULL)
{
printf("\n UNDERFLOW");
}
else if(head->next == NULL)
{
head = NULL;
free(head);
printf("\nnode deleted\n");
}
else
{
ptr = head;
if(ptr->next != NULL)
{
ptr = ptr -> next;
}
ptr -> prev -> next = NULL;
free(ptr);
printf("\nnode deleted\n");
}
}
void deletion_specified()
{
struct node *ptr, *temp;
152
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
int val;
printf("\n Enter the data after which the node is to be deleted : ");
scanf("%d", &val);
ptr = head;
while(ptr -> data != val)
ptr = ptr -> next;
if(ptr -> next == NULL)
{
printf("\nCan't delete\n");
}
else if(ptr -> next -> next == NULL)
{
ptr ->next = NULL;
}
else
{
temp = ptr -> next;
ptr -> next = temp -> next;
temp -> next -> prev = ptr;
free(temp);
printf("\nnode deleted\n");
}
}
void display()
{
struct node *ptr;
printf("\n printing values...\n");
ptr = head;
while(ptr != NULL)
{
printf("%d\n",ptr->data);
ptr=ptr->next;
}
}
void search()
{
struct node *ptr;
int item,i=0,flag;
ptr = head;
if(ptr == NULL)
153
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
{
printf("\nEmpty List\n");
}
else
{
printf("\nEnter item which you want to search?\n");
scanf("%d",&item);
while (ptr!=NULL)
{
if(ptr->data == item)
{
printf("\nitem found at location %d ",i+1);
flag=0;
break;
}
else
{
flag=1;
}
i++;
ptr = ptr -> next;
}
if(flag==1)
{
printf("\nItem not found\n");
}
}
}
154
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
/* LINEAR SEARCH */
#include<stdio.h>
#include<conio.h>
void main()
{
int a[100],i,n,e,f=0;
clrscr();
printf("enter n value\n");
scanf("%d",&n);
printf("enter in array\n");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
printf("enter element\n");
scanf("%d",&e);
i=1;
155
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
while((i<=n)&&(f==0))
{
if(a[i]==e)
{
f=1;
break;
}
i++;
}
if(f)
printf("FOUND");
else
printf("NOT FOUND");
getch();
}
/* input
enter n value
5
enter in array
9 6 7 2 10
enter element
10
FOUND */
#include<stdio.h>
#include<conio.h>
void main()
{
int i,h,low=1,n,a[100],mid,e;
clrscr();
printf("enter n \n");
scanf("%d",&n);
printf("enter into array in ascending\n");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
printf("enter element\n");
scanf("%d",&e);
h=n;
mid=(low+h)/2;
while((low<h)&&(a[mid]!=e))
{
156
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
if(a[mid]>e)
h=mid-1;
else
if(a[mid]<e)
low=mid+1;
mid=(low+h)/2;
}
if(a[mid]==e)
printf("FOUND AT %d",mid);
else
printf("NOT FOUND");
getch();
}
/* input
enter n
5
enter in array in ascending
11 12 13 14 15
enter element
13
FOUND AT 3 */
/*BUBBLE SORTING */
#include<stdio.h>
#include<conio.h>
void main()
{
int a[100],i,j,t,n;
clrscr();
printf("enter n value\n");
scanf("%d",&n);
printf("enter in array\n");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
for(i=1;i<n;i++)
{
for(j=i+1;j<=n;j++)
if(a[i]>a[j])
{
t=a[i];
a[i]=a[j];
a[j]=t;
157
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
}
}
printf("after sorting\n");
for(i=1;i<=n;i++)
printf("%4d",a[i]);
getch();
}
/* input
enter n value
6
enter in array
9 45 8 2 5 6
after sorting
2 5 6 8 9 45 */
/* SELECTION SORT */
#include<stdio.h>
#include<conio.h>
void main()
{
int j,n,k,min,i,p,a[100];
clrscr();
printf("enter n value\n");
scanf("%d",&n);
printf("enter in array\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
p=0;
while(p<n-1)
{
min=p;
for(j=p+1;j<n;j++)
{
if(a[min]>a[j])
min=j;
}
if(min!=p)
{
k=a[p];
a[p]=a[min];
a[min]=k;
}
p++;
}
158
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
printf(" AFTER SORTING\n");
for(i=0;i<n;i++)
printf("%4d",a[i]);
getch();
}
/* input
enter n value 4
enter in array
6839
AFTER SORTING 3689 */
/* input
enter n value
4
enter in array
1345
enter e and p
22
after inserting
1 2 3 4 5 */
159
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,a[100],n,t;
clrscr();
printf("enter n value\n");
scanf("%d",&n);
printf("enter in array\n");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
for(i=2;i<=n;i++)
{
for(j=i-1;j>=1;j--)
{
if(a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
printf("AFTER SORTING\n");
for(i=1;i<=n;i++)
printf("%4d",a[i]);
getch();
}
/* input
enter n value
4
enter in array
7 4 2 6
AFTER SORTING
2 4 6 7 */
160
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
Quick sort
#include <stdio.h>
#include <stdbool.h>
#define MAX 7
printf("=\n");
}
void display() {
int i;
printf("[");
printf("]\n");
}
while(true) {
while(intArray[++leftPointer] < pivot) {
//do nothing
161
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
int main()
{
printf("Input Array: ");
display();
printline(50);
quickSort(0,MAX-1);
printf("Output Array: ");
display();
printline(50);
}
162
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
Output
Input Array: [4 6 3 2 1 9 7 ]
==================================================
pivot swapped :9,7
Updated Array: [4 6 3 2 1 7 9 ]
pivot swapped :4,1
Updated Array: [1 6 3 2 4 7 9 ]
item swapped :6,2
pivot swapped :6,4
Updated Array: [1 2 3 4 6 7 9 ]
pivot swapped :3,3
Updated Array: [1 2 3 4 6 7 9 ]
Output Array: [1 2 3 4 6 7 9 ]
==================================================
struct Node
{
int coeff;
int pow;
struct Node* next;
};
if(first)
{
temp->coeff = first->coeff;
temp->pow = first->pow;
first = first->next;
}
else if(second)
{
temp->coeff = second->coeff;
temp->pow = second->pow;
second = second->next;
}
}
}
int main()
{
#include<stdio.h>
#include<stdlib.h>
void bfs(int v)
int i, cur;
visited[v] = 1;
q[++rear] = v;
while(front!=rear)
{
166
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
cur = q[++front];
for(i=1;i<=n;i++)
if((a[cur][i]==1)&&(visited[i]==0))
{ q[++rear] = i;
visited[i] = 1;
void dfs(int v)
int i;
visited[v]=1;
s[++top] = v;
for(i=1;i<=n;i++)
dfs(i);
}
167
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
int main()
scanf("%d",&n);
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
for(i=1;i<=n;i++)
visited[i]=0;
scanf("%d",&start);
printf("\n==>3:Exit");
scanf("%d", &ch);
switch(ch)
for(i=1;i<=n;i++)
if(visited[i]==0)
break;
dfs(start);
break;
case 3: exit(0);
}}
#include<stdio.h>
169
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
#include<conio.h>
#include<ctype.h>
#define MAX 50
typedef struct stack
{
int data[MAX];
int top;
}stack;
int precedence(char);
void init(stack *);
int empty(stack *);
int full(stack *);
int pop(stack *);
void push(stack *,int);
int top(stack *); //value of the top element
void infix_to_postfix(char infix[],char postfix[]);
void main()
{
char infix[30],postfix[30];
printf("Enter an infix expression(eg: 5+2*4): ");
gets(infix);
infix_to_postfix(infix,postfix);
170
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
while(precedence(token)<=precedence(top(&s))&&!empt
y(&s))
{
x=pop(&s);
postfix[j++]=x;
}
push(&s,token);
}
}
while(!empty(&s))
{
x=pop(&s);
postfix[j++]=x;
}
postfix[j]='\0';
}
int precedence(char x)
{
if(x=='(')
return(0);
if(x=='+'||x=='-')
172
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,
return(1);
if(x=='*'||x=='/'||x=='%')
return(2);
return(3);
}
void init(stack *s)
{
s->top=-1;
}
int empty(stack *s)
{
if(s->top==-1)
return(1);
return(0);
}
int full(stack *s)
{
if(s->top==MAX-1)
return(1);
return(0);
}
173
P.Y.KUMAR. M.C.A,M.Tech,M.Phil..,