Data Structures Notes
Data Structures Notes
[Link]. IV SEMESTER
II YEAR IV SEMESTER
Paper-IV: DATA STRUCTURES
UNIT I
Concept of Abstract Data Types (ADTs)- Data Types, Data Structures, Storage Structures, and
File Structures, Primitive and Non-primitive Data Structures, Linear and Non-linear Data
Structures.
Linear Lists – ADT, Array and Linked representations, Pointers.
Arrays – ADT, Mappings, Representations, Sparse Matrices Linked Lists: Single Linked List,
Double Linked List, Circular Linked List , applications
UNIT II
Stacks: Definition, ADT, Array and Linked representations, Implementations and Applications
Queues: Definition, ADT, Array and Linked representations, Circular Queues, Dequeues,
Priority Queues, Implementations and Applications.
UNIT III
Trees: Binary Tree, Definition, Properties, ADT, Array and Linked representations,
Implementations and Applications. Binary Search Trees (BST) – Definition, ADT, Operations
and Implementations,
UNIT IV
Graphs – Graph and its Representation, Graph Traversals, Connected Components, Basic
Searching Techniques, Minimal Spanning Trees
UNIT- V
Sorting and Searching: Selection, Insertion, Bubble, Merge, Quick, sort, Sequential and Binary
Searching.
UNIT I
These are derived from primitive data structures. But extending the size and ranges of
basic data type
They focus on grouping same or different data items with relationship between each
data item.
Arrays, Lists and Files come under this category.
Array: An array is a collection of memory locations which can share same data name
and same data type values.
List: An order set containing variable number of elements is called as lists.
o The list is a sequential data structure.
o Lists are a way to store many different values under a single variable.
o Every item in this list is numbered with an index.
File: A file is a collection of logically releated inforation. It can be viewed as large
list of records consisting of various fields.
A Non- primitive data type is further divided into linear and Non- linear data
strucutre.
Linera data stucture: A data structure is said to be linear if its elements form a
sequence or a linear list. Example: array, stacks, queues and linked lists come under
this category.
Non- Linear data strucutres: A data structure is said to be non linear if its elements
form a hierarchical classification where, data items appear at various [Link] and
Graphs are widely used non-linear data structures.
Data Type: Data type defines what type of value to stored on a variable.(or)A data type
defines a set of values and the allowable operations on those values. Different data types
include:
1. Abstract data types (ADT )
2. Composite types
3. Primitive types
Abstract data types (ADT ) : Abstract data types are mathematical models of
a set of data values or information that share similar behaviors. Abstract data
types are used in algorithms and also data items.(OR)
ADT is a user defined data type which encapsulates a range of data values and
their functions. (OR)
An abstract data type is a definition of new type, describes its properties and
operations.
Ex: ―Stack‖ is a ADT which contains push( ), pop( ) operations.
―Linked List‖ is a ADT which contains insert( ), delete( ) operations etc.
In an ADT, we encapsulate the data and the operations on data and we hide
them from the [Link] abstract data type consists of
i) Declaration of data
ii) Declaration of operations
Advantages:
Code is easier to understand.
Implementations of ADTs can be changed without requiring changes to
the program that uses the ADTs.
ADTs can be reused in future programs.
Composite types: Composite data type is any data type which can be
constructed in a program using the programming languages like primitive data
types and other data types.
Example : Structures, unions in ‗c‘.
struct Account
{
int account_number;
char first_name;
char last_name;
float balance;
};
Primitive types:
Primitive types are data types provided by a programming language. Primitive
types are also known as built-in types or basic types.
primitive types may include:
1. Character (character, char);
2. Integer (integer, int, short, long, byte) with a variety of precisions;
3. Floating-point number (float, double, real, double precision);
4. Boolean having the values true and false.
Basic primitive types :
SIZE NAME SIGNED INTEGER UNSIGNED
RANGE INTEGER RANGE
8 bits Byte -128 to + 127 0 to 255
16 bits Integer -32,768 to +32,767 0 to 65,535
-2,147,483,648
Double to
32 bits Long +2,147,483,648 0 to 4,294,967,295
integer
64 bits Long(JAV -9,223,372,036,854,775,808 0 to
A) to 18,446,744,073,709,551,
+9,223,372,036,854,775,808 615
Integer numbers
An integer number can hold a whole number, but no fraction. Integers may be
either signed (allowing Negative values) or unsigned (non negative values only).
Floating-point numbers
Cache memory: Fastest and most costly form of storage, volatile, managed by
the computer system hardware. Cache memory is an intermediate storage between
the CPU Registers and Main [Link] is small and fastest [Link] memories
are accessed much faster than RAM.
Main memory: Main memory also called as primary memory. Primary memory is
the only type memory that is directly accessed by the CPU. Any data operated by the
CPU, is stored in primary memory. Contents of main memory are usually lost if a
power failure or system crash occurs.
Flash Memory:
Data can be written at a location only once, but location can be erased and
written to [Link] support only a limited number (10K – 1M) of write/erase
[Link] writes are slow (few microseconds), erase is slower.
Optical storage
The Optical Drives are latest technology devices, that uses ―Light Sensors‖ to store the
[Link] Light Sensors are called ―Lasers‖.Optical drives are most widely used
and reliable storage [Link] most popular optical storage devices are:
a) CD-ROM
b) DVD-ROM
c) CD-R
d) CD-RW
Magnetic Disk
Data is stored on spinning disk, and read/written [Link]
medium for the long-term storage of [Link] must be moved from disk to
main memory for access, and written back for [Link] access i.e.
possible to read data on disk in any order, unlike magnetic tape.
Magnetic Tapes
Hold large volumes of data and provide high transfer [Link] slow access
time in comparison to magnetic disks and optical disks limited to sequential
[Link] mainly for backup, for storage of infrequently used information.
FILE STRUCTURES
A storage structure representation in auxiliary memory is often called a file
structure.A file is a collection of data stored on mass storage (e.g., disk or
tape).Advantages of mass storage
Too big to fit in main memory
Share data between programs
Backup (disks and tapes are less volatile than main memory)
The data is subdivided into records. Each record contains a number of fields.
One or more field is the key field (e.g., address).
Files
SEQUENTIAL ACCESS
A sequential file is one in which records can only be accessed one after another
from beginning to end. Records are stored one after another in auxiliary
storage, such as tape or disk, and there is an EOF (end-of-file) marker after the
last record. The operating system has no information about the record
addresses, it only knows where the whole file is stored. The only thing known
to the operating system is that the records are sequential.
Random access
If we need to access a specific record without having to retrieve all records
before it, we use a file structure that allows random access. Two file structures
allow this: indexed files and hashed files
INDEXED FILES
To access a record in a file randomly, we need to know the address of the
record.
HASHED FILES
A hashed file uses a mathematical function to accomplish this mapping. The
user gives the key, the function maps the key to the address and passes it to
the operating system, and the record is retrieved.
Topographical Structures:
Diplom
a
Data Structures Prepared by Mahesh MCA
9
[Link]. IV SEMESTER
Circular structure:
Tree: a tree can be defined as finite set of data items(nodes) in which data
items are arranged in branches and sub branches according to requirement.
Trees consist of nodes connected by edge, the node presented by circle and
edge lives connecting to circle.
Graph: Graph is a collection of nodes (information) and connecting edges(
Logical relation) between nodes.
A tree can be viewed as a restricted graph.
Graphs have many types.
o Un- directed graph
o Directed graph
o Mixed graph
o Multi graph
o Simple graph
o Null graph
o Weighted graph
Arrays
Definition:
An array is a finite, ordered and collection of homogeneous data elements. An
array is finite because it contains only a limited number of elements, ordered
as all the elements are stored one by one in contiguous locations of the
computer memory in a linear order. As homogeneous all the elements of an
array are of the same data type.
Basic Terminology:
Size: The number of elements in an array is called the size or length of the
array.
Type: The type of an array represents the kind of data type .
Base: The base of an array is the address of the memory location where the
first element of the array is located.
Element − Each item stored in an array is called an element.
Index: All the elements in an array can be referenced by a subscript like A[i],
this subscript is known as index. The index value is always an integer value.
Range of Indices: Indices of arrays elements may range from a lower bound to
an upper bound called boundaries of an array.
Word: Word ‗w’ denotes the size of an element i.e., the amount memory that is
required to store an element of the array.
Physical Representation
Eg: Let M=4560 and w=1,calculate the address of A[0], A[2], A[7]
Traversing: It is used to access each data item exactly once so that it can be
processed.
Searching: It is used to find out the location of the data item if it exists in the
given collection of data items.
Insertion: It is used to add a new data item in the given collection of data
items.
Deletion: It is used to delete an existing data item from the given collection of
data items.
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.
Merging: It is used to combine the data items of two sorted files into single file
in the sorted.
Multi-Dimensional arrays and their address mapping and operations
Definition:An array is a finite, ordered and collection of homogeneous data
elements. An array is finite because it contains only a limited number of
elements, ordered as all the elements are stored one by one in contiguous
locations of the computer memory in a linear order. As homogeneous all the
elements of an array are of the same data type.
Eg: Consider an array of size mxn, here m is the [Link] rows and n is the [Link]
columns as follows.
1. Row-Major Order
2. Column-Major Order
Eg:
a11 a12 a13
a21 a22 a23
a31 a32 a33
3X3
Memory Representation
Row-Major Order:
Address(aij) = (i-1)xn+j
If the base address is M, then the above formula can be modified as follows.
Address(aij) = M+(i-1)xn+j-1
= 4560+2x3+2-1
=4560+6+2-1 = 4567
Column-Major Order:
Address(aij) = (j-1)xm+j
If the base address is M, then the above formula can be modified as follows.
Address(aij) = M+(j-1)xm+i-1
= 4560+3+3-1
=4560+3+2 = 4565
A sparse matrix is a two – dimensional array where the majority of the elements have
the value null.
Input : An array a with two- Another array spm with two multiplied by 3.`
The above matrix contains 5 rows and 6 columns. Then the total number of
elements are 5x6=30. If each element requires 4 Bytes of memory, then we
need totally 120 Bytes of memory. But if we observe the matrix, it has very few
non-zero values, that is majority of values are zeros. We have only 6 non-zero
Sparse matrices are used by scientists and engineers when solving partial
differential equations. For example, a measurement of a matrix's sparsity can
be useful when developing theories about the connectivity of
computer networks. When using large sparse matrices in a computer program,
it is important to optimize the data structures and algorithms to take
advantage of the fact that most of the values will be zero.
Linked List is a linear data structure and it is very common data structure
which consists of group of nodes in a sequence which is divided in two
[Link] node consists of its own data and the address of the next node and
forms a [Link] Lists are used to create trees and graphs.
Singly Linked List : Singly linked lists contain nodes which have a data part
as well as an address part i.e. next, which points to the next node in sequence
of nodes. The operations we can perform on singly linked lists are insertion,
deletion and traversal.
Doubly Linked List : In a doubly linked list, each node contains two links the
first link points to the previous node and the next link points to the next node
in the sequence.
Circular Linked List : In the circular linked list the last node of the list
contains the address of the first node and forms a circular chain.
Single Linked List: In single linked list, each node contains only one link
which points to the next node in the list. We maintain a pointer called Headptr
to point the very first node of the list.
In the above example, we have five nodes from N1 to N5. The first node is called
as Head Node and last node is called as Tail Node. First node points to second,
second points to third and so on. Tail Node always points to null which
indicates there no more node in the list. In single-linked list, we can travel only
in direction that is from Head Node to Tail Node. We can move only to the next
node not to the previous node of the list. That is why it is called as one way list.
Operations:
addNewNode (data): This operation adds a new node to the list with the given
data.
delete (index): This operation deletes an existing node from the list at given
index position.
size(): This operation gives the size i.e., how many nodes are there in the list.
insert (index, data):This operation inserts a new node to the list at a given
index position with a given data value.
traversal():This operation gathers data from each node in the list starting from
head to tail node and displays the data.
Define linked list. Explain how to insert and delete an element at the
beginnning of the list.
Linked List is a linear data structure and it is very common data structure
which consists of group of nodes in a sequence which is divided in two parts.
Each node consists of its own data and the address of the next node and forms
a [Link] Lists are used to create trees and graphs.
Insertion: : Insertion is used to add a new data item. A node can be inserted
in various positions.
i. Inserting at the front ( as a first element)
ii. Inserting at end ( as a last element)
iii. Inserting at any position.
Steps for inserting an element in the beginning of a list
1. Create a new node
2. Make the next part of new node point to the first node
3. Make the START pointer point to new node
Algorithm
new_nodenext=START;
START =new_node;
while(pnext!=NULL)
{
p=pnext;
}
pnext=new_node;
new_nodenext=NULL;
while(p!=insert_position)
{
P=pnext;
}
store_next=pnext;
pnext=new_node;
new_nodenext=store_next;
Deleting a node from a list: It is used to delete an existing data item from the
given collection of data items. There three ways to delete element.
Example:
In the above example, we have four nodes from N1 to N4. The first node is
called as Head Node and last node is called as Tail Node. First node points to
second, second points to third and so on. The left link of head node and right
link of tail node points to null. It indicates that there is no previous node to
head and no next node to tail node. In double-linked list, we can travel in
either directions that is from Head Node to Tail Node and Tail Node to Head
Node. That is why it is called as two-way list.
Operations:
addNewNode (data):This operation adds a new node to the list with the given
data.
delete (index):This operation deletes an existing node from the list at given
index position.
size():This operation gives the size i.e., how many nodes are there in the list.
insert (index, data):This operation inserts a new node to the list at a given
index position with a given data value.
traversal():This operation gathers data from each node in the list starting from
head to tail node and displays the data.
Define double linked list. Explain how to insert and delete an element at
the end of the list.
In double linked list, each node contains two links one points to the next node
another points to the previous node in the list. We maintain a pointer called
Headptr to point the very first node of the list.
Steps for inserting in the beginning of a doubly linked list
1. Create a new node
2. Make the next part of new node equal to START
3. Make the previous part of new node equal to NULL
4. Make the previous part of the node pointed by START to new node
5. Make START point to new node
Algorithm for insert a node at the start
new_nodenext=head;
headprev=new_node;
new_nodeprev=NULL;
head=new_node;
1. Deletion at beginnning
2. Deletion at middle
3. Deletion at end
Algorithm:
p=head;
head=headnext;
headprev=NULL;
delete(p);
P=pnext;
}
store_next=pnext;
store_prev=pprev;
store_nextprev=store_prev;
store_prevnext=store_next;
delete(p);
2. Make the next part of the previous node equal to next of the node to be deleted
3. Make the TAIL equal to the previous part of the node to be deleted
Algorithm:
store_prev=pprev;
store_prevnext=NULL;
delete(p);
CircularLinked List: A linked list where the last node points the header node
is called the ‗Circular Linked List‘. A circular list doesn't have definite head and
definite tail nodes. Any Node in the list can be chosen as Head and node before
that as Tail. If there are more than one Node in the list, then every Node will
have next Node. If there is only one Node in the list that itself is the head and
tail. The tail Node in the circular list points to the head Node.
Operations:
addNewNode (data):This operation adds a new node to the list with the given data.
delete (index):This operation deletes an existing node from the list at given index
position.
size():This operation gives the size i.e., how many nodes are there in the list.
insert (index, data):This operation inserts a new node to the list at a given index
position with a givendata value.
traversal():This operation gathers data from each node in the list starting from head to
tail node and displays the data.
[Link] SLL the list will be traversed in 1. In DLL the list will be traversed in
only one way i.e., in forward two ways either in forward (or)
direction. Backward directions.
[Link] SLL the node contains only one 2. In DLL each node contains two Link
link field. fields.
[Link] node contains the address of 4. Every node contains the address of
next node. next node as well as the address of the
previous node.
[Link] SLL the first node address is 6. In DLL the first node address is
stored in a special pointer variable stored in ―left end‖ and last node
―START‖. address is stored in ―right end‖ pointer
variables.
UNIT-II
What is stack? Explain its Applications
A Stack is a linear list in which insertions and deletions take place at the same
end. The end through which items are added and deleted is called the Top End.
The other end of the list is called the Bottom End.
We can implement the stack ADT either with array or linked list.
Stack overflow happens when we try to push one more item onto our stack than
it can actually hold.
Stack underflow happens when we try to pop (remove) an item from the stack,
when nothing is actually there to remove.
To use a stack efficiently, we need to check the status of stack as well. For
the same purpose, the following functionality is added to stacks –
o peek() − get the top data element of the stack, without removing it.
o isFull() − check if stack is full.
o isEmpty() − check if stack is empty.
Applications of stack:
Paranthesis matching: Stacks can be used to find out whether the given
equation is balanced or not. It mainly checks for the matching of left and
right parenthesis in an equation.
Example:
(A+B(x+y)+C is not a valid expression because it miss right paranthesis
(A+B(x+y)+C) is a valid expression
Convert from infix to postfix: Stacks are used to convert an infix to
postfix expression.
Main()
{
fun();
…………
…………
}
fun()
{
………..
When data is PUSHed onto stack, To use a stack efficiently, we need to check
the status of stack as well. For the same purpose, the following functionality is
added to stacks.
peek( ) − get the top data element of the stack, without removing it.
3. top = top + 1
4. stack[top] = data
5. end procedure
Pop Operation
Accessing the content while removing it from the stack, is known as a POP
Operation. A POP operation may involve the following steps.
Step 1 − Checks if the stack is empty.
Step 2 − If the stack is empty, produces an error and exit.
Step 3 − If the stack is not empty, accesses the data element at which top is
pointing.
Step 4 − Decreases the value of top by 1.
Step 5 − Returns success.
Algorithm for Pop operation
1. begin procedure pop: stack
2. if stack is empty return null
3. end if 4. data = stack[top]
5. top = top - 1
6. return data
7. end procedure
Peek( ):
This operation returns the most accessible element from stack.
return stack[top]
end procedure
isFull( ):
This operation is performed to know whether the stack is full or not. If the TOP
value reaches to MAXSIZE then the stack is full.
Abstract Class :
AbstractDataType Stack
{
Instances
Linear list of elements: one end is called the bottom the other is the top.
Operations
isEmpty() : Return True if stack is empty, return False otherwise.
isFull() : Return True if stack is full, return False otherwise
push(x) : Add element x to the stack
pop(x) : Delete top element from stack and put it in x.
}
Operations:
push(x) : Adding items to the stack is called as Push operation. Here x is the
data item that is being added onto the stack.
pop(x) : Deleting items from the stack is called as Pop operation. Here x is the
data item that is being deleted from the stack.
isFull( ) :This function verifies whether the stack is full or not. If stack is full, it
returns true, otherwise return false.
isEmpty(): This function verifies whether the stack is empty or not. If stack is
empty, it returns true, otherwise it returns false.
Algorithm
Stack Operations: Basically, there are two operations performed on the
stack.
Push: Push is the term used to insert the element on the top of stack.
Pop: Pop is the term used to delete the elements from top of the stack.
Algorithm: push(s, top, x):[This algorithm inserts the elements.]
Step: 1 [check for the stack over flow]
If (top > = max-1) then write (―stack over flow‖)
Return;
Step: 2 [increment top by 1]
top top+1;
Step: 3 [insert element]
s[top] x;
Step: 4 [finished]
Return;
Algorithm pop(s, top): [this algorithm deletes the top element from the stack]
Step: 1 [check for the stack under flow]
if (top= = -1) then write (―stack underflow‖)
Return;
Step: 2 [assign top element to x]
X s[top];
Step: 3 [decrement top by 1]
top top-1;
Step: 4 [finished]
Return;
Algorithm isEmpty(s, top): [this algorithm checks the stack is empty ]
Step: 1 [check for the stack is empty()]
if (top= = -1) then write (―stack Empty‖)
Step: 2.[finished]
Return;
Algorithm: isFull(s, top):[This algorithm checks the stack is full]
Step: 1 [check for the stack is full]
If (top > = max-1) then write (―stack is Full‖)
Step: 2 [finished]
Return;
Stack Representation using Linked List:
Array representation of stacks is very easy, but it allows only fixed sized stacks.
In several applications, the size of the stack may vary during program
execution. In such cases we may use linked list. A single linked list structure is
sufficient to represent to any stack. Here data field is users data and link field
is as usual point to next item.
We can use either single linked or double linked list to represent a stack data
structure. But it is easy to use single linked list to represent a stack data
structure.
Example :
In the linked list representation, first node on the list is the current item that is
the item at the top of the stack and the last node is the node containing bottom
most item. So PUSH operation will perform at the front and POP operation will
perform at front. SIZE of the stack is not important here because dynamic
representation.
The implementation of isFull() method is not necessary because the only way to
know whether we can add an element on to the stack or not is to see whether
enough space exists to create a node of type Node. This check can be done by
invoking new.
Abstraction of Stack:
Data Objects:
Node :-consisting of two parts data and address.
headptr :-always points to the address of first node in the list
next :- used to store next node address
Methods :
isEmpty(): This method verifies that the stack is empty or not. If the stack is
empty it returns true, otherwise it returns false.
push(x): This method adds a data item x onto the stack. If the operation
executed successfully it returns true, otherwise it returns false.
pop(x): This method pops a data item from the stack and places it in x. If the
operation executed successfully it returns true, otherwise it returns
false.
peek(): To access the top element of the stack without removing it.
Algorithms
Algorithm: push_LL (s, top, x):[This algorithm inserts the elements.]
Step: 1[Create new node ]
New=Getnew(Node);
Step: 2 [inserting Values]
New Data=Item
Step3: [palcing reference]
New link=top
Top=new
Step: 4 [top is assigns to stack head]
Stack_Headlink=top
Step:5 [Finish]
Return;
Algorithm pop_LL(s, top): [this algorithm deletes the top element from the
stack]
Step: 1 [check for the stack under flow]
PTR= Stack_Headlink;
if (PTR=NULL) then write (―stack underflow‖)
Return;
Step: 2 [assign top element to x]
X PTR[top]; [Display x]
Step: 3 [Assign top to next node]
top = ptr link;
Step: 4[Assign head_ptr to top]
Stack_Head=top;
Step: 5 [finished]
Return;
Algorithm isEmpty(s, top): [this algorithm checks the stack is empty ]
Step: 1 [check for the stack is empty()]
if (top= = null) then write (―stack Empty‖)
Step: 2.[finished]
Return;
Example: (A + B) * (C - D)
Example: * + A B – C D
Example: A B + C D - *
A queue is a leaner list, which has two ends, where items are inserted at one end
called the rear and deleted at the other end called the front. Another name for a queue
is a ―FIFO‖ or ―First-in-first-out‖ list. Unlike stacks, a queue is open at both its ends.
One end is always used to insert data (enqueue) and the other is used to remove data
(dequeue). We can implement the queue by using Arrays and linked list.
Arrays
Queue operations :
Enqueue:
The process of adding an element into the queue is known as Enqueue. The
following steps are perform queue operations.
Accessing data from the queue is a process of two tasks − access the data
where front is pointing and remove the data after access. The following steps
are taken to perform dequeue operation:
Step 1 − Check if the queue is empty.
Step 2 − If the queue is empty, produce underflow error and exit.
Step 3 − If the queue is not empty, access the data where front is pointing.
Step 4 − Increment front pointer to point to the next available data element.
Step 5 − Return success.
Procedure dequeue
if queue is empty
return underflow
end if
data = queue[front]
front = front + 1
return true
end procedure
peek( )
This function helps to see the data at the front of the queue. The algorithm of
peek() function is as follows
begin procedure peek
return queue[front]
end procedure
isFull:
As we are using single dimension array to implement queue, we just check for
the rear pointer to reach at MAXSIZE to determine that the queue is full.
Begin procedure isfull
if rear equals to MAXSIZE
return true
else
return false
end if
end procedure
Applications of Queue:
Printing using the computer: When several documents are to be printed, the
printer prints the documents in FIFO method only. i.e. to keep track of
documents in FIFO order, a queue is used.
Reservation system: Reservations such as air ticket or railway reservation
systems, use to issue reservations on first come first serve basis i.e. FIFO
method.
Computer networks: Computer networks use queue to give access from server
to several clients, who are connected to the server in FIFO method.
BFS: Breadth first search uses a queue data structure to find an element from
a graph.
2. Circular queue:
Circular queue is a linear data structure. It follows FIFO principle. In
circular queue the last node is connected back to the first node to make
a circle.
Elements are added at the rear end and the elements are deleted at front
end of the queue
It is also called as ―Ring buffer‖.
Adding large integers: large integers can be added very easily using circular
queues. Here the right most digit is placed in the front node and left most digit
is placed in rear node.
3. Priority queue:
A priority queue is a queue that contains items that have some preset
[Link] an element ha to be removed from a priority queue, the item with
the highest pririty is removed first.
Double Ended Queue can be represented in TWO ways, those are as follows...
Limitations:
The drawback of circular queue is , difficult to distinguished the full and empty cases.
It is also known as boundary case problem.
The first kind of representation uses a one dimensional array and it is a better
a choice where a queue of fixed size is required. The other representation uses
double linked list and provides queue whose size can vary during processing.
Represntation of Queue using an array:
A one dimensional array, say q[1…N], can beused to represent a queue.
In the above representation, two pointers namely FRONT and REAR are used to indicate
the two ends of the queue. For the insertion of the next element, the pointer REAR will be
the consultant and for the pointer FRONT will be the consultant. Three states of a queue
with this representation are given below.
Queue is empty:
FRONT =0,
REAR=0
Queue is full
REAR=N
FRONT=1
Queue contains elements >=1
Number of elelnts = REAR-FRONT+1
Representation of a Queue using linked list:
A Linear Queue can be represented as a Linked List. For this we need two
variables front and rear to keep track of the two ends of the Queue. There are
two possibilities for binding these two variables to the ends of the Linked list.
The nodes can be linked from front to rear or rear to front. But linking the
nodes from front to rear is more efficient for deletions.
Queue is empty
FRONT =REAR=HEADER
HEADERRLINK=NULL
QUEUE contains at least one element
HEADER RLINK ≠ NULL
UNIT –III
TREES
Path: The sequence of lines which connect node to node of tree is called path.
Root: The node at the top of a tree is called the root. There is only one root in a tree.
Parent: Any node (except root) that has at least one node as a child node, is called parent.
Child: All the nodes except root are child nodes.
Leaf: A node that has no child node can be called leaf node.
Sub-tree: A sub-tree constitutes of a node and all its decendants.
Visiting: Visiting means reaching a particular node to either print it or perform some operation
on it.
Traversing: traversing means to visit all the nodes in some specified order.
Level: The level refers to number generations from the root of a tree ( it is also called depth of
atree)
Keys: Key refers to a value ( data field) of a node.
Depth of a node we will call the length of the path from the root to certain node.
Height of tree: is the maximum depth of all its nodes.
Degree of node we call the number of direct children of the given node.
Branching factor is the maximum of the degrees of all nodes in the tree.
What is binary Tree? Write the properties and applications of binary Trees. ?
A binary tree is defined as a finite set of elements, called nodes, such that:
In the above tree ―A‖ is the root node and ―B‖ and ―C‖ are called subtrees. B
and C are left and right successor of A. The node A is called parent node and B
and C are called children. All lower level nodes are called descendants and
upper level nodes are called ancestors of their descendants. The line drawn
between parent and child is called an edge or arc whereas the line(s) between
and ancestor and descendant is called path. A node without any children is
called a terminal or leaf node and all others are called nonterminal or non-leaf
node. A path ending with a leaf is called a branch.
Properties of binary trees
The depth of a binary tree containing N nodes is at most N-1.
The depth of a binary tree containing N leaves is at least [log2(N)].
A binary tree of depth d has at most 2d leaves.
The number of nodes in a binary tree of depth d is at most 2d-1-1.
The average depth of a binary tree containing N nodes is O( 𝑁 )
The maximum number of nodes on level i of a binary tree is 2i-1, i ≥1
The maximum number of nodes in a binary tree of depth k is 2k – 1, k ≥1
If a complete binary tree with n nodes (depth = ˪ log2n +1˩ ) is represented
sequentially, then for any node with index i, 1 ≤ i ≤ n, we have:
Heap is a tree data structure which is implemented using arrays and used
to implement priority queues.
B-Tree and B+ Tree : They are used to implement indexing in databases.
Syntax Tree: Used in Compilers.
K-D Tree: A space partitioning tree used to organize points in K dimensional
space.
Trie : Used to implement dictionaries with prefix lookup.
Suffix Tree : For quick pattern searching in a fixed text.
One reason to use trees might be because you want to store information
that naturally forms a hierarchy. For example, the file system on a
computer: file system.
Skewed Tree:
A tree is called Skew if all the nodes of a tree are attached to one
side only. i.e A left skew will not have any right children in its each
node and right skew will not have any left child in its each node.
Array Representation
The numbering scheme used in it suggests out first representation of a binary
tree in memory. Since the nodes are numbered from 1 to n, we can use a one-
dimensional array to store the nodes. (We do not use the 0th position of the
array.) Using the node numbering easily determine the locations of the parent,
left child, and right child of any node, i, in the binary tree.
Advantages:
This method benefits from more compact storage and better locality of
reference, particularly during a preorder traversal.
Limitations:
Wastage of space for some types of binary tree.
Insertion and deletions require potential changes in the array.
Linked Representation
We can easily overcome the problems arise due to array representation by
using a linked representation. Each node has three fields, left_child, data, and
right_child as two pictures show the node representation of the binary tree
below:
Advantages:
Insertion and deletion involve no data movement and no movement of
nodes except the rearrangement of pointers.
Limitations:
Given a node structure, it is difficult to determine its parent node.
Memory spaces are wasted for storing NULL pointers for the nodes,
which have no subtrees.
There are many operations that we can perform on tree, but one that arises
frequently is traversing a tree, that is, visiting each node in the tree exactly
once. A full traversal produces a linear order for the information in a tree.
Inorder Traversal:
In the case of inorder traversal, the root of each subtree is visited after its left
subtree has been traversed but before the traversal of its right subtree begins.
The steps for traversing a binary tree in inorder traversal are:
Preorder Traversal:
In a preorder traversal, each root node is visited before its left and right
subtrees are traversed. Preorder search is also called backtracking. The steps
for traversing a binary tree in preorder traversal are:
1. Visit the root.
2. Visit the left subtree, using preorder.
3. Visit the right subtree, using preorder.
Algorithm for preorder traversal
void preorder(node root)
{
if( root != NULL )
{
print root . data; preorder (root . lchild);
preorder (root . rchild);
}
}
Postorder Traversal:
In a postorder traversal, each root is visited after its left and right subtrees
have been traversed. The steps for traversing a binary tree in postorder
traversal are:
Visit the left subtree, using postorder.
Visit the right subtree, using postorder
Visit the root.
Algorithm for postorder traversal
void postorder(node root)
{
if( root != NULL )
{
postorder (root . lchild);
postorder (root . rchild);
print (root . data);
}
}
traverse the binary tree in level order. This is nothing but a breadth first search
technique.
BST Operations
The basic operations that can be performed on a binary search tree data
structure, are the following
1. Insert node
2. Searching
3. Delete a node
4. Traversal
Insert Operation
The very first insertion creates the tree. Afterwards, whenever an element is to
be inserted, first locate its proper location. Start searching from the root node,
then if the data is less than the key value, search for the empty location in the
left subtree and insert the data. Otherwise, search for the empty location in the
right subtree and insert the data.
Algorithm:
Step1: Compare item with the root( N) of the tree as
If ( item<N )proceed to the left child of N.
If( item>N) proceed to the right child of N
Step2: Repeat step1 until one of the following occurs.
We meet a node N such that item = N. in this case the search is successful.
We meet an empty sub tree, which indicates the search is unsuccessful. Insert item
in place of the empty sub tree.
Step 3: exit
Search Operation
Whenever an element is to be searched, start searching from the root node,
then if the data is less than the key value, search for the element in the left
subtree. Otherwise, search for the element in the right subtree. Follow the
same algorithm for each node.
Algorithm
If [Link] is equal to [Link]
return root
else
while data not found
If data is greater than [Link]
goto right subtree
else
goto left subtree
If data found
return node
endwhile
return data not found
end if
Binary Search Tree Traversal
Traversal is a process to visit all the nodes of a tree and may print their values
too. Because, all nodes are connected via edges (links) we always start from the
root (head) node. That is, we cannot randomly access a node in a tree. There
are three ways which we use to traverse a tree
In-order Traversal
Pre-order Traversal
Post-order Traversal
Generally, we traverse a tree to search or locate a given item or key in the tree
or to print all the values it contains.
In-order Traversal
In this traversal method, the left subtree is visited first, then the root and later
the right sub-tree. We should always remember that every node may represent
a subtree itself.
Post-order Traversal
In this traversal method, the root node is visited last,
hence the name. First we traverse the left subtree, then
the right subtree and finally the root node.
We start from A, and following pre-order traversal, we
first visit the left subtree B. B is also traversed post-
order. The process goes on until all the nodes are visited.
The output of post-order traversal of this tree will be −
D→E→B→F→G→C→A
DELETING A NODE
Removing is the most complicated operation from the basic binary search Tree
operations. After it the tree must keep its order.
The firsrt step before we remove an element from the tree is to find it. We have
three cases.
2. First, search for that starting from the root. i.e. move to left the element is
less than parent or right till the elementis encountered or empty node is
encountered.
5. if the node has only left child, parent node must be linked to its left before
deleting the node.
6. if the node has only right child, parent node must be linked to its right
before deleting the node.
7. if a node to be deleted has two children, find minimum value in its right sub
tree. Replace the element to be deleted with the minimum element and repeat
the same process to delete the node containing minimum element.
UNIT – IV
GRAPHS
Graph is a non linear data structure which contains a set of points known as
nodes (or vertices) and set of links known as edges (or Arcs) which connects the
vertices.
Directed Graph
A graph with only directed edges is said to be directed graph.
Degree
Total number of edges connected to a vertex is said to be degree of that vertex.
In-degree
Total number of incoming edges connected to a vertex is said to be in-degree of
that vertex.
Out-degree
Total number of outgoing edges connected to a vertex is said to be out-degree of
that vertex.
Path
A path is a sequence of alternating vertices and edges that starts at a vertex
and ends at a vertex such that each edge is incident to its predecessor and
successor vertex.
Adjacent
If there is an edge between vertices A and B then both A and B are said to be
adjacent. In other words, Two vertices A and B are said to be adjacent if there
is an edge whose end vertices are A and B.
Mixed Graph
A graph with undirected and directed edges is said to be mixed graph.
Origin
If an edge is directed, its first endpoint is said to be origin of it.
Destination
If an edge is directed, its first endpoint is said to be origin of it and the other
endpoint is said to be the destination of the edge.
Cyclic graph:- A graph that has cycles is called cyclic graph.
Acyclic graph:- a graph that has no cycles is called an acyclic graph.
Isolated graph:- if a node has no edges connected with any other node then it‘s
degree will be o and it will be called isolated graph.
Self-loop
An edge (undirected or directed) is a self-loop if its two endpoints coincide.
Multigraph:- a graph which has loop or multiple edges can be described as
multigraph.
Graph is a non linear data structure which contains a set of points known as
nodes (or vertices) and set of links known as edges (or Arcs) which connects the
vertices.
1. Directed graph
2. Undirected Graph
3. Weighted Graph
Directed Graph:
A directed graph G is defined as an ordered pair (V, E) where, V is a set of
vertices and the ordered pairs in E are called edges on V. A directed graph can
be represented geometrically as a set of marked points (called vertices) V with a
set of arrows (called edges) E between pairs of points (or vertex or nodes) so
that there is at most one arrow from one vertex to another vertex. For example,
in the figure shows a directed graph, where G = {a, b, c, d }, {(a, b), (a, d), (d, b),
(d, d), (c, c)}
An edge (a, b), in said to the incident with the vertices it joints, i.e., a, b. We
can also say that the edge (a, b) is incident from a to b. The vertex a is called
the initial vertex and the vertex b is called the terminal vertex of the edge (a, b).
If an edge that is incident from and into the same vertex, say (d, d) of (c, c) in
the above Fig , is called a loop.
Undirected Graph:
An undirected graph G is defined abstractly as an ordered pair (V, E), where V
is a set of vertices and the E is a set at edges. An undirected graph can be
Weighted Graph:
A graph G is said to be weighted graph if every edge and/or vertices in the
graph is assigned with some weight or value. A weighted graph can be defined
as G = (V, E, We, Wv) where V is the set of vertices, E is the set at edges and
We is a weights of the edges whose domain is E and Wv is a weight to the
vertices whose domain is V. Consider a graph In Fig, which shows the distance
in km between four metropolitan cities in India. Here V = {N, K, M, C,} E = {(N,
K), (N,M,), (M,K), (M,C), (K,C)} We = {55,47, 39, 27, 113} and Wv = {N, K, M, C}
The weight at the vertices is not necessary to maintain have become the set Wv
and V are same.
Complete Graph:
A graph G is said to complete (or fully connected or strongly connected) if there
is a path from every vertex to every other vertex. Let a and b are two vertices in
the directed graph, then it is a complete graph if there is a path from a to b as
well as a path from b to a. A complete graph with n vertices will have n (n –
1)/2 edges.
Where (e1, e2, d3, e4, e5) is a path; (e1, e3, e4, e5, e12, e9, e11, e6, e7, e8,
e11) is a path but not a simple one; (e1, e3, e4, e5, e6, e7, e8, e11, e12) is a
simple path but not elementary one; (e1, e3, e4, e5, e6, e7, e8) is an elementary
path.
A circuit is a path (e1, e2, .... en) in which terminal vertex of en coincides with
initial vertex of e1. A circuit is said to be simple if it does not include (or visit)
the same edge twice. A circuit is said to be elementary if it does not visit the
same vertex twice. In Fig. (e1, e3, e4, e5, e12, e9, e10) is a simple circuit but
not a elementary one; (e1, e3, e4, e5, e6, e7, e8, e10) is an elementary circuit.
Social network graphs: Graphs that represent who knows whom, who
communicates with whom or other relationships in social structures
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.
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.
Graph is a non linear data structure which contains a set of points known as
nodes (or vertices) and set of links known as edges (or Arcs) which connects the
vertices.
Example:
For a Undirected graph representation the adjacency matrix representation is
That means if a graph with 4 vertices can be represented using a matrix of 4X4
class. In this matrix, rows and columns both represent vertices. This matrix is
filled with either 1 or 0. Here, 1 represents there is an edge from row vertex to
column vertex and 0 represents there is no edge from row vertex to column
vertex.
In adjacency list representation of graph, we will maintain two lists. First list
will keep track of an nodes in the graph and second list will maintain a list of
adjacent nodes for each node. It is more efficiency of than adjacency matrix.
Example: Consider the following directed graph representation implemented
using linked list
A complete traversal of the graph can be made by repeatedly calling BFS each
time with a new unvisited starting vertex.
Step-2: Put the starting node A in QUEUE and change its status to the waiting
state (status-2)
Step-4: Remove the front node N of queue, process N and change the status of
N to the processes state (status-3).
Step-5; Add to the rear of queue all the neighbors of N that are in the ready
state (status- 1) and change their status to the waiting state (status-2).
Step-6: Exit
Algorithm:
Step-1: Initialize all nodes to the ready state (status-1).
Step-2: Push the starting node A onto the Stack and change its status to the
waiting state (status-2). Step-3: Repeat step 4 and 5 until stack is empty.
Step-4: Pop the top node N of stack . process N and change its status to the
processed state (STATUS-3).
Step-5: Push onto stack all the neighbor of N that are still in the ready state
(status-1) and change their status to the waiting state (status-2).
Step-5: Exit.
A spanning tree is a subset of Graph G, which has all the vertices covered with
minimum possible number of edges. Hence, a spanning tree does not have
cycles and it cannot be disconnected. Every connected and undirected Graph G
has at least one spanning tree. A disconnected graph does not have any
spanning tree, as it cannot be spanned to all its vertices.
We found three spanning trees off one complete graph. A complete undirected
graph can have maximum nn-2 number of spanning trees, where n is the
number of nodes. In the above addressed example, 33−2 = 3 spanning trees are
possible.
2) Kruskal’s algorithm
Kruskal's algorithm is an algorithm in graph theory that finds a minimum
spanning tree for a connected weighted graph. This means 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. If the graph is not connected, then it
finds a minimum spanning forest (a minimum spanning tree for each
connected component). Kruskal's algorithm is an example of a greedy
algorithm.
Algorithm:
1) Start by selecting the two nodes with the minimal costing link.
2) Select any two nodes with the minimal costing link. Your selection is not
bound by any requirement to
select nodes connected to previously selected nodes. Any two nodes we can
select, as long as it the minimal cost.
3) Repeat steps 1 and 2 until all nodes have been selected / connected.
Example:
Solution:
UNIT – V
Sortings & Searching
External Sorts
Explain the algorithm for selection sort and give a suitable example.
In selection sort the list is divided into two sub-lists sorted and unsorted.
These two lists are divided by imaginary wall. We find a smallest element from
unsorted sub-list and swap it to the beginning. And the wall moves one
element ahead, as the sorted list is increases and unsorted list is decreases.
Assume that we have a list on ―n‖ elements. By applying selection sort, the first
element is compared with all remaining (n-1) elements. The smallest element is
placed at the first location. Again, the second element is compared with
remaining (n-1) elements. At the time of comparison, the smaller element is
swapped with larger element. Similarly, entire array is checked for smallest
element and then swapping is done accordingly. Here we need n-1 passes or
iterations to completely rearrange the data.
Algorithm:
The idea of algorithm is quite simple. Array is imaginary divided into two parts
- sorted one and unsorted one. At the beginning, sorted part is empty, while
unsorted one contains whole array. At every step, algorithm finds minimal
element in the unsorted part and adds it to the end of the sorted one. When
unsorted part becomes empty, algorithm stops.
When algorithm sorts an array, it swaps first element of unsorted part with
minimal element and then it is included to the sorted part.
Selection_Sort ( A [ ] , N )
Step 1 : Repeat For K = 0 to N – 2 Begin
Step 2 : Set POS = K
Step 3 : Repeat for J = K + 1 to N – 1 Begin
If A[ J ] < A [ POS ]
Set POS = J
End For
Step 4 : Swap A [ K ] with A [ POS ]
End For
Step 5 : Exit
A list of unsorted elements are: 23 78 45 8 32 56
Example
Explain the algorithm for insertion sort and give a suitable example.
Both the selection and bubble sorts exchange elements. But insertion sort does
not exchange elements. In insertion sort the element is inserted at an
appropriate place similar to card insertion. Here the list is divided into two
parts sorted and unsorted sub-lists. In each pass, the first element of unsorted
sub list is picked up and moved into the sorted sub list by inserting it in
suitable position. Suppose we have „n‟ elements, we need n-1 passes to sort
the elements.
We start with an empty left hand [sorted array] and the cards face down
on the table [unsorted array].
Then remove one card [key] at a time from the table [unsorted array], and
insert it into the correct position in the left hand [sorted array].
To find the correct position for the card, we compare it with each of the
cards already in the hand, from right to left.
1. FOR j ← 2 TO length[A]
2. DO key ← A[j]
3. {Put A[j] into the sorted sequence A[1 . . j − 1]}
4. i ← j − 1
5. WHILE i > 0 and A[i] > key
6. DO A[i +1] ← A[i]
7. i ← i – 1
8. A[i + 1] ← key
Example:
for(int x:arr){
[Link](x+" "); }
}
}
Explain the algorithm for bubble sort and give a suitable example.
In bubble sort method the list is divided into two sub-lists sorted and unsorted.
The smallest element is bubbled from unsorted sub-list. After moving the
smallest element the imaginary wall moves one element ahead. The bubble sort
was originally written to bubble up the highest element in the list. But there is
no difference whether highest / lowest element is bubbled. This method is easy
to understand but time consuming. In this type, two successive elements are
compared and swapping is done. Thus, step-by-step entire array elements are
checked. Given a list of „n‟ elements the bubble sort requires up to n-1 passes
to sort the data.
1. Compare each pair of adjacent elements from the beginning of an array and,
if they are in reversed order, swap them.
Bubble_Sort ( A [ ] , N )
Step 3 : If ( A [ J ] < A [ J – 1 ] )
Swap ( A [ J ] , A [ J – 1 ] )
Step 4 : Exit
Example
int n , temp ,i , j;
[Link]( );
n = [Link]; temp = 0;
//swap elements
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
Explain the algorithm for QUICK sort ( partition exchange sort) and give a
suitable example.
Quick sort is based on partition. It is also known as partition exchange sorting.
It was invented by CAR Hoare. The basic concept of quick sort process is pick
one element from an array and rearranges the remaining elements around it.
This element divides the main list into two sub lists. This chosen element is
called pivot. Once pivot is chosen, then it shifts all the elements less than pivot
to left of value pivot and all the elements greater than pivot are shifted to the
right side. This procedure of choosing pivot and partition the list is applied
recursively until sub-lists consisting of only one element.
if length(q) ≤ 1
return q
array[i] = array[j];
array[j] = temp;
}
public static void main(String a[ ]){
MyQuickSort sorter = new MyQuickSort();
int[] arr = {24,2,45,20,56,75,2,56,99,53,12};
[Link]("List before sort ");
for(int x :arr)
[Link](x+" ");
[Link](arr);
[Link]("\nList after sort");
for(int x:arr){
[Link](x+ " ");
[Link](" ");
}
}
}
Explain the algorithm for Merge sort and give a suitable example.
The basic concept of merge sort is divides the list into two smaller sub-lists of
approximately equal size. Recursively repeat this procedure till only one
element is left in the sub-list. After this, various sorted sub-lists are merged to
form sorted parent list. This process goes on recursively till the original sorted
list arrived.
1. Divide Step
If a given array A has zero or one element, simply return; it is already sorted.
Otherwise, split A[p .. r] into two sub-arrays A[p .. q] and A[q + 1 .. r], each
containing about half of the elements of A[p .. r]. That is, q is the halfway point
of A[p .. r].
2. Conquer Step
Conquer by recursively sorting the two sub-arrays A[p .. q] and A[q + 1 .. r].
3. Combine Step
Combine the elements back in A[p .. r] by merging the two sorted sub-arrays
A[p .. q] and A[q + 1 .. r] into a sorted sequence. To accomplish this step, we
will define a procedure MERGE (A, p, q, r).
Note that the recursion bottoms out when the sub-array has just one element,
so that it is sorted. To sort the entire sequence A[1 .. n], make the initial call to
the procedure MERGE-SORT (A, 1, n).
Properties
It is a Stable algorithm i.e does not change the relative order of elements
with equal keys
It does not require random access to data
Example:
for(int i:inputArr)
[Link](inputArr);
for(int i:inputArr)
[Link] = inputArr;
[Link] = [Link];
doMergeSort(lowerIndex, middle);
doMergeSort(middle + 1, higherIndex);
tempMergArr[i] = array[i];
int i = lowerIndex;
int j = middle + 1;
int k = lowerIndex;
array[k] = tempMergArr[i];
i++;
else {
array[k] = tempMergArr[j];
j++;
k++;
array[k] = tempMergArr[i];
k++;
i++;
1. Linear search
2. Binary search
1. LINEAR SEARCH
Consider an array K with n elements as K[1], K[2], . . . K[n]. Suppose an item
of information is given to search.
In this technique, compare item value with each element of K form index 1 to
index n. At any position i, if K[i]=item, then return index i value refers to
successful search; otherwise, return -1 refers to unsuccessful search.
item = 19
ELEMENT FOUND
This function returns an index position ‗i' if the element is found; otherwise,
return -1.
Time Complexity:
2. Binary Search :
Binary search is another searching algorithm, that takes less time complexity
compared with the linear search. Binary search can be applied only on the
array which is available in sorted order.
Case 2: If ITEM > K[Mid]; Then the ITEM can appear only in the right half
of the array. So, we reset the Low value as Low = Mid+1 and begin
search again.
Case 3: If ITEM < K[Mid]; Then the ITEM can appear only in the left half of
the array. So, we reset the High value as High = Mid-1 and begin
search again.
This procedure is repeated upto we reach Low > High. When we obtain this
condition, it indicates that the search is unsuccessful search.
class BinarySearchExample
{
public static void binarySearch(int arr[ ], int first, int last, int key)
{
int mid = (first + last)/2;
while( first <= last )
{
if ( arr[mid] < key )
{
first = mid + 1;
}
else if (arr[mid] == key)
{
[Link]("Element is found at index: " + mid);
break;
}
else
{
last = mid - 1;
}
mid = (first + last)/2;
}
if ( first > last )
{
[Link]("Element is not found!");
}
}
public static void main(String args[ ])
{
int arr[ ] = {10,20,30,40,50};
int key = 40;
int last=[Link]-1;
binarySearch(arr,0,last,key);
}
}
[Link]();
[Link]();
[Link]("LinkedList after deletion of first and last element: \n" +ll);
[Link](1, "Karan");
[Link](2);
[Link]("Final Content: \n" +ll);
}
}
MyStack(int size)
{
top = -1;
item = new int[size];
}
void popItem( )
{
if (top < 0)
{
[Link]("Stack is Empty");
}
else
{
top--;
[Link]("Pop Item : " + item[top+1]);
}
}
}
class StackExample
{
public static void main(String[] args) throws IOException
{
MyStack stk = new MyStack(10);
boolean yes=true;
int choice;
Scanner sc = new Scanner([Link]);
//BufferedReader is = new BufferedReader(new InputStreamReader([Link]));
do{
[Link]("_________________");
[Link]("Menu:");
[Link]("_________________");
[Link]("[Link]\[Link]\[Link]\[Link]\n\nEnter Choice");
choice = [Link]();
switch(choice)
{
case 1: [Link]("Enter Push Item: ");
[Link]([Link]());
break;
case 2: [Link]( );break;
case 3: [Link]("Stack elements:");
[Link]( ); break;
case 4: yes = false;break;
default: [Link]("Invalid Choice");
}
}while(yes==true);
}
}
Menu:
___________________
[Link]
[Link]
[Link]
[Link]
Enter Choice
1
Enter Push Item :
77
Pushed Item : 77
___________________
Menu:
___________________
[Link]
[Link]
[Link]
[Link]
Enter Choice
1
Enter Push Item :
66
Pushed Item : 66
___________________
Menu:
___________________
[Link]
[Link]
[Link]
[Link]
Enter Choice
3
Stack element
66 77
77
___________________
Menu:
___________________
[Link]
[Link]
[Link]
[Link]
Enter Choice
2
Pop item:66
___________________
Menu:
___________________
[Link]
[Link]
[Link]
[Link]
Enter Choice
4
front=-1;
rear=-1;
item=new int[size];
}
void eQ(int data)
{
if (rear==[Link]-1)
{
[Link]("Queue is full");
}
else
{
if (rear==-1)
{
front = 0;
rear = 0;
item[rear] = data;
}
else if (rear+1<[Link])
item[++rear] = data;
[Link]("Element " + data + " is entered into the Queue ");
display();
}
}
public void dQ( )
{
if(front<0)
{
[Link]("Queue is Empty");
}
else
{
temp=front;
front++;
[Link]("Deleted element from the queue is:"+item[temp]);
display( );
}
}
public void display( )
{
if(rear >= front)
{
[Link]("Elements in the Queue :");
for(int i=front;i<=rear;i++)
{
[Link](item[i]);
}
}
}
}
}
//[Link] Programs to implement the Stack operations using a single linked list
import [Link].*;
class MyNode
{
int item;
MyNode next;
MyNode(int val)
{
item = val;
}
public void displayNode()
{
[Link](item );
}
}
class MyLinkedList
{
MyNode first;
boolean isEmpty()
{
return (first==null);
}
void insert(int val)
{
MyNode newNode = new MyNode(val);
[Link] = first;
first = newNode;
}
MyNode delete()
{
MyNode temp = first;
first = [Link];
return temp;
}
void display()
{
[Link]("Elements from top to bottom");
MyNode current = first;
while(current != null)
{
[Link]();
current = [Link];
}
[Link]("");
}
class MyStack
{
MyLinkedList list;
MyStack()
{
list = new MyLinkedList();
}
void push(int num)
{
[Link](num);
}
MyNode pop()
{
return [Link]();
}
boolean isEmpty()
{
return [Link]();
}
void displayStack()
{
[Link]("Stack : ");
[Link]();
}
}
class StackLinkedList
{
public static void main(String[] args) throws IOException
{
MyStack s= new MyStack();
[Link](10);
[Link](20);
[Link]();
[Link](30);
[Link](40);
[Link]();
[Link]();
[Link]();
[Link]("Two elements are popped");
[Link]();
}
}
20
10
//[Link] Programs to implement the Queue operations using a singly linked list
import [Link].*;
class MyNode
{
int item;
MyNode next;
MyNode(int val)
{
item = val;
}
void displayNode( )
{
[Link](item+" " );
}
}
class MyLinkedList
{
MyNode start;
MyNode end;
boolean isEmpty( )
{
return start==null;
}
void insertEnd(int val)
{
MyNode newNode = new MyNode(val);
if( isEmpty( ) )
start = newNode;
else
[Link] = newNode;
end = newNode;
}
int deleteStart( )
{
int temp = [Link];
if([Link] == null)
end = null;
start = [Link];
return temp;
}
void displayList( )
{
MyNode current = start;
while(current != null)
{
[Link]();
current = [Link];
}
[Link](" ");
}
}
class MyQueue
{
MyLinkedList list;
MyQueue( )
{
list= new MyLinkedList( );
}
boolean isEmpty( )
{
return [Link]( );
}
void insert(int k)
{
[Link](k);
}
int delete( )
{
return [Link]( );
}
void display( )
{
[Link]("Queue [start to end]: ");
[Link]( );
}
}
class QueueLinkedList
{
public static void main(String[ ] args)
{
MyQueue demo = new MyQueue( );
[Link]("Inserting two elements into the queue");
[Link](10);
[Link](20);
[Link]( );
[Link]("Inserting one more element into the queue at the end");
[Link](30);
[Link]( );
[Link]("Deleting one element from the front");
[Link]( );
[Link]( );
}
}
At command prompt:
D:\ JDS Programs>javac [Link]
D:\JDS Programs>java QueueLinkedList
Output:
Inserting two elements into the queue
Queue [start to end]: 10 20
Inserting one more element into the queue at the end
Queue [start to end]: 10 20 30
Deleting one element from the front
Queue [start to end]: 20 30
}
/* The main function that implements QuickSort( )
arr[ ] --> Array to be sorted,
low --> Starting index,
high --> Ending index */
void sort(int arr[ ], int low, int high)
{
if (low < high)
{
/* pi is partitioning index, arr[pi] is now at right place */
int pi = partition(arr, low, high);
// Recursively sort elements before partition and after partition
sort(arr, low, pi-1);
sort(arr, pi+1, high);
}
}
[Link]("Sorted Array:");
printArray(arr);
}
}
class BinarySearchExample
{
public static void binarySearch(int arr[ ], int first, int last, int key)
{
int mid = (first + last)/2;
while( first <= last )
{
if ( arr[mid] < key )
{
first = mid + 1;
}
else if (arr[mid] == key)
{
[Link]("Element is found at index: " + mid);
break;
}
else
{
last = mid - 1;
}
mid = (first + last)/2;
}
if ( first > last )
{
[Link]("Element is not found!");
}
}
public static void main(String args[ ])
{
int arr[ ] = {10,20,30,40,50};
int key = 40;
int last=[Link]-1;
binarySearch(arr,0,last,key);
}
}
//8) Write a Java program for implementation of Linear Search (or) Sequential
public class LinearSearchExample
{
public static int linearSearch(int[] arr, int key)
{
for(int i=0;i<[Link];i++)
{
if(arr[i] == key)
{
return i;
}
}
[Link]("searching element was not found in the array");
return -1;
}
public static void main(String a[ ])
{
int a1[ ]= {10,20,30,50,70,90};
int key = 70;
[Link](key+" is found at index: "+linearSearch(a1, key));
}
}
Output:
70 is found at index: 4
import [Link];
{
arr[i] = [Link]();
}
Output:
Enter Array Size : 6
Enter Array Elements : 12
98
23
87
45
76
Sorting Array using Selection Sort Technique:
Now the Array after Sorting is:
12 23 45 76 87 98
import [Link];
Output:
Enter Array Size : 6
Enter Array Elements : 12
98
23
87
45
76
Sorting Array using Insertion Sort Technique:
Now the Array after Sorting is:
12 23 45 76 87 98
Output:
Enter number of integers to sort:
6
Enter 6 elements:
8
4
6
11
3
10
Sorted list of numbers:
3 4 6 8 10 11