Sie sind auf Seite 1von 38

College of

Department of SRSWTI Engineering


Computer Engineering
College of
Engineering
College of
Course Objectives
1. To introduce the
Engineering
fundamental concept of data structures and emphasize
importance of Data Structures in developing and implementing efficient
algorithms.
2. To teach efficient storage mechanisms of data for an easy access.
3. To design and implementation of various basic and advanced data structures.
4. To develop application using data structures.
5. To teach the concept of management of data.
6. To improve the logical ability and understand the generic principles of computer
programming as applied to sophisticated data structures.
7. Analyze performance of algorithms.

Course Outcomes

At the end, of course students will be able to

1. Choose appropriate data structure as applied to specified problem definition.


2. Handle operations like searching, insertion, deletion, traversing mechanism
etc. on various data structures.
3. Apply concepts learned in various domains like DBMS, compiler construction
etc.
4. Describe how arrays, records, linked structures, stacks, queues, trees, and
graphs are represented in memory and used by algorithms.
5. Describe common applications for arrays, records, linked structures, stacks,
queues, trees, and graphs.
6. Demonstrate different methods for traversing trees.
7. Compare alternative implementations of data structures with respect to
performance.
8. Discuss the computational efciency of the principal algorithms for sorting,
searching, and hashing.

SRSWTI 1
College of
Department of SRSWTI Engineering
Computer Engineering
College of
LIST OF EXPERIMENT Engineering
College of
Expt. No. Name of the Experiment
Engineering
1. Implementation of Stack using array.

2. Implementations of Infix to Postfix conversion.

3. Implementation of Queue using array.

4. Array implementation of circular queue.

5. Implementations of singly Linked Lists menu driven program.

6. Implementation of Stack using Linked List.

7. Implementations of Binary Search Tree menu driven program.

8. Implementation of Quick sort.

9. Implementations of Binary search.


Implementation of Depth First Search and Breadth First Search
10.
(DFS & BFS).
11. Mini project.

Content Beyond Syllabus

12. Write a recursive function to implement Tower of Hanoi.

H/W Requirement P IV and above, RAM 512MB, Printer, Cartridges

S/W Requirement Turbo C/C++

SRSWTI 2
College of
Department of SRSWTI Engineering
Computer Engineering
College of
EXPERIMENT NO. 1 Engineering
College of
AIM : Implementation of Stack using array. Engineering
PROBLEM : WAP to perform stack operation using static memory allocation
STATEMENT

RESOURCES : Equipment/Machines - P IV and Above, Printer, Turbo C.


REQUIRED Consumables Printer Pages for printouts.

THEORY : A collection of data and its relationship among the elements


forms a data structure. A stack is ordered collection of items in
which all insertion, deletion is done at the same end called the
top. The basic operations on stack are push and pop. It is often
called LIFO data structure.

Operations on Stack:

Push: Adds an item in the stack. If the stack is full, then it is


said to be an Overflow condition.
Pop: Removes an item from the stack. The items are popped in
the reversed order in which they are pushed. If the stack is
empty, then it is said to be an Underflow condition.
Peek or Top: Returns top element of stack.
isEmpty: Returns true if stack is empty, else fals.

Algorithm to push an element:

SRSWTI 3
College of
Department of SRSWTI Engineering
Computer Engineering
College of
Engineering
1. Check whether stack is full or not. (i.e. if(top==MAXSIZE))
College of
2. Otherwise increase the top by 1(else top=top+1)
Engineering
3. Insert the element, elem.

stack[top]=elem;

Algorithm to pop an element:

1. Check whether stack is empty or not (if (top==-1))

2. Otherwise decrement top by 1.

To check whether the stack is empty or not (STACK


EMPTY).

To check whether the stack is full or not (STACK FULL)

CONCLUSION : Stack is one of the efficient way to implement discipline in the


system. Stacks are last in first out so two major applications
that Stacks accomplish are things like state and reversing.
Stack would be the undo/redo feature. Every time the user
enters something, save the state (in this case, the text) on a
stack and if we need to reverse something, just pop it off the
top of the undo stack and push it onto the redo stack.

EXPERIMENT NO. 2

AIM : Implementations of stack application.

PROBLEM : WAP to implement Infix to Postfix conversion.

SRSWTI 4
College of
Department of SRSWTI Engineering
Computer Engineering
College of
STATEMENT Engineering
RESOURCES :
College of
Equipment/Machines - P IV and Above, Printer, Turbo C/C+
REQUIRED + Engineering
Consumables Printer Pages for printouts.

THEORY : A stack is a container of objects that are inserted and


removed according to the last-in first-out (LIFO) principle. In
the pushdown stacks only two operations are
allowed: push the item into the stack, and pop the item out of
the stack.

Application of Stack:

1. Expression Evolution
2. Expression conversion

1. Infix to Postfix

2. Infix to Prefix

3. Postfix to Infix

4. Prefix to Infix

3. Parsing

4. Simulation of recursion

5. Fuction call

Infix, Prefix, and Postfix Notation

We are accustomed to write arithmetic expressions with the


operation between the two operands: a+b or c/d. If we
write a+b*c, however, we should apply precedence rules to
avoid the ambiguous evaluation (add first or multiply first?).

There's no real reason to put the operation between the variables or

SRSWTI 5
College of
Department of SRSWTI Engineering
Computer Engineering
College of
Engineering
College
values. They can just as well precede or follow the of
operands. You
should note the advantage of prefix and postfix: the need for
precedence rules and parentheses are eliminated.
Engineering

Infix Prefix Postfix

a+b +ab ab+

a+b*c +a*bc abc*+

(a + b) * (c - d) *+ab-cd ab+cd-*

b*b-4*a*c

40 - 3 * 5 + 1

Postfix expressions are easily evaluated with the aid of a


stack.

Algorithm:

1. Start by initializing an empty stack. This will be for holding


our operators.
2. Read the string, getting the first operand and add it to the
postfix string.
3. Read the next object in the string, normally a operator, and
push the operator to the stack. Is the operator of greater,
equal, or lesser precedence than the top most operator on the
stack?
If the operator is greater than the top most operator,
push the current operator and continue.
If the operator is lesser to the top most operator, pop the
stack adding it to the postfix string, and then push the current
operator to the stack. Test the next operator to see if it is also
lesser and repeat step 2. If not continue.
If the operator is equal to the top most operator pop the
top of the stack adding it to the postfix string and then push
the current operator to the stack.
4. Repeat these steps until all of the operands and operators

SRSWTI 6
College of
Department of SRSWTI Engineering
Computer Engineering
College of
are taken care of. Engineering
5. Afterwards look at the stack one last timeCollege of
to see if any
operators remain, pop them all and add them to the end of
the postfix string.
Engineering
6. Stop the process.

CONCLUSION : In computer, reverse polish notation is used in stack-based


and concatenative programming languages. It is a way of
expressing arithmetic expressions that avoids the use of
brackets to define priorities for evaluation of operators. It is
also common in dataflow and pipeline-based systems,
including Unix pipelines.

EXPERIMENT NO. 3
AIM : Implementation of Queue using array.

PROBLEM : WAP to implement Queue operation using array.


STATEMENT

RESOURCES : Equipment/Machines - P IV and Above, Printer, Turbo


REQUIRED C/C++.
Consumables Printer Pages for printouts.

THEORY : Queue is also an abstract data type or a linear data

SRSWTI 7
College of
Department of SRSWTI Engineering
Computer Engineering
College of
structure, in which the first element is insertedEngineering
from one
College
end called REAR(also called tail), and the deletion of of
existing element takes place from the other Engineering
end called
as FRONT(also called head). This makes queue as FIFO
data structure, which means that element inserted first
will also be removed first.

The process to add an element into queue is


called Enqueue and the process of removal of an
element from queue is called Dequeue.

Queue Representation:
As we now understand that in queue, we access both
ends for different reasons. The following diagram given
below tries to explain queue representation as data
structure

As in stacks, a queue can also be implemented using


Arrays, Linked-lists, Pointers and Structures. For the
sake of simplicity, we shall implement queues using

SRSWTI 8
College of
Department of SRSWTI Engineering
Computer Engineering
College of
one-dimensional array.
Engineering
College of
Basic Operations:
Engineering
Queue operations may involve initializing or defining the
queue, utilizing it, and then completely erasing it from
the memory. Here we shall try to understand the basic
operations associated with queues

enqueue() add (store) an item to the queue.

dequeue() remove (access) an item from the


queue.

Few more functions are required to make the above-


mentioned queue operation efficient. These are

peek() Gets the element at the front of the


queue without removing it.

isfull() Checks if the queue is full.

isempty() Checks if the queue is empty.

In queue, we always dequeue (or access) data, pointed


by frontpointer and while enqueing (or storing) data in
the queue we take help of rear pointer.

ALGORITHM:
peek()
This function helps to see the data at the front of the
queue. The algorithm of peek() function is as follows

Algorithm

begin procedure peek

return queue[front]

end procedure

isfull()

SRSWTI 9
College of
Department of SRSWTI Engineering
Computer Engineering
College of
Engineering
As we are using single dimension array to implement
queue, we just check for the rear pointer toCollege
reach at of
Engineering
MAXSIZE to determine that the queue is full. In case we
maintain the queue in a circular linked-list, the algorithm
will differ. Algorithm of isfull() function

Algorithm

begin procedure isfull

if rear equals to MAXSIZE


return true
else
return false
endif

end procedure

isempty()
Algorithm of isempty() function

begin procedure isempty

if front is less than MIN OR front is greater than rear


return true
else
return false
endif

end procedure

If the value of front is less than MIN or 0, it tells that the


queue is not yet initialized, hence empty.

Algorithm for enqueue operation

SRSWTI 10
College of
Department of SRSWTI Engineering
Computer Engineering
College of
procedure enqueue(data) Engineering
if queue is full
return overflow
College of
endif Engineering
rear rear + 1

queue[rear] data

return true

end procedure

Algorithm for dequeue operation


procedure dequeue
if queue is empty
return underflow
end if
data = queue[front]
front front + 1
return true
end procedure

Applications of Queue
Queue, as the name suggests is used whenever we
need to have any group of objects in an order in which
the first one coming in, also gets out first while the others
wait for there turn, like in the following scenarios:

1. Serving requests on a single shared resource, like a


printer, CPU task scheduling etc.
2. In real life, Call Center phone systems will use
Queues, to hold people calling them in an order, until
a service representative is free.

3. Handling of interrupts in real-time systems. The


interrupts are handled in the same order as they

SRSWTI 11
College of
Department of SRSWTI Engineering
Computer Engineering
College of
Engineering
arrive, First come first served.
College of
Engineering
CONCLUSION : Queue is used when things dont have to be processed
immediately, but have to be processed in First In First
Out order like Breadth First Search. Queue data
structure adds elements using array and removed
elements also.

EXPERIMENT NO. 4
AIM : Implementation of Circular Queue using array.

PROBLEM : WAP to implement Circular Queue operation using array.


STATEMENT

RESOURCES : Equipment/Machines - P IV and Above, Printer, Turbo


REQUIRED C/C++.
Consumables Printer Pages for printouts.

THEORY : Circular Queue

In a normal Queue Data Structure, we can insert


elements until queue becomes full. But once if queue
becomes full, we can not insert the next element until all

SRSWTI 12
College of
Department of SRSWTI Engineering
Computer Engineering
College of
the elements are deleted from the queue. Engineering
College of
For example consider the queue below.

After inserting all the elements into the queue.


Engineering

Now consider the following situation after deleting three


elements from the queue...

This situation also says that Queue is Full and we can


not insert the new element because, 'rear' is still at last
position. In above situation, even though we have empty
positions in the queue we can not make use of them to
insert new element. This is the major problem in normal
queue data structure. To overcome this problem we use
circular queue data structure.
What is Circular Queue?
A Circular Queue can be defined as follows...
Circular Queue is a linear data structure in which the
operations are performed based on FIFO (First In First
Out) principle and the last position is connected back to
the first position to make a circle.

SRSWTI 13
College of
Department of SRSWTI Engineering
Computer Engineering
College of
Graphical representation of a circular Engineering
queue is as
follows... College of
Engineering

Implementation of Circular Queue

To implement a circular queue data structure using array,


we first perform the following steps before we implement
actual operations.

Step 1: Include all the header files which are


used in the program and define a
constant 'SIZE'with specific value.

Step 2: Declare all user defined functions used


in circular queue implementation.

Step 3: Create a one dimensional array with


above defined SIZE (int cQueue[SIZE])

Step 4: Define two integer variables 'front' and


'rear' and initialize both with '-1'. (int front = -1,
rear = -1)

Step 5: Implement main method by displaying


menu of operations list and make suitable function
calls to perform operation selected by the user on
circular queue.

SRSWTI 14
College of
Department of SRSWTI Engineering
Computer Engineering
College of
1) enQueue(value) - Inserting value Engineering
into the
Circular Queue College of
ALGORITHM:
In a circular queue, enQueue() is a functionEngineering
which is
used to insert an element into the circular queue. In a
circular queue, the new element is always inserted
at rear position. The enQueue() function takes one
integer value as parameter and inserts that value into the
circular queue. We can use the following steps to insert
an element into the circular queue...

Step 1: Check whether queue is FULL. ((rear == SIZE-1


&& front == 0) || (front == rear+1))

Step 2: If it is FULL, then display "Queue is FULL!!!


Insertion is not possible!!!" and terminate the function.

Step 3: If it is NOT FULL, then check rear == SIZE - 1


&& front != 0 if it is TRUE, then set rear = -1.

Step 4: Increment rear value by one (rear++),


set queue[rear] = value and check 'front == -1' if it
is TRUE, then set front = 0.

2) deQueue() - Deleting a value from the Circular


Queue

In a circular queue, deQueue() is a function used to


delete an element from the circular queue. In a circular
queue, the element is always deleted from front position.
The deQueue() function doesn't take any value as
parameter. We can use the following steps to delete an
element from the circular queue...

Step 1: Check whether queue is EMPTY. (front == -1


&& rear == -1)

Step 2: If it is EMPTY, then display "Queue is EMPTY!!!

SRSWTI 15
College of
Department of SRSWTI Engineering
Computer Engineering
College of
Deletion is not possible!!!" and terminate theEngineering
function.
College of
Step 3: If it is NOT EMPTY, then
display queue[front] as deleted element andEngineering
increment
the frontvalue by one (front ++). Then check
whether front == SIZE, if it is TRUE, then set front = 0.
Then check whether both front - 1 and rear are equal
(front -1 == rear), if it TRUE, then set
both frontand rear to '-1' (front = rear = -1).

3) display() - Displays the elements of a Circular


Queue

We can use the following steps to display the elements


of a circular queue...

Step 1: Check whether queue is EMPTY. (front == -1)

Step 2: If it is EMPTY, then display "Queue is


EMPTY!!!" and terminate the function.

Step 3: If it is NOT EMPTY, then define an integer


variable 'i' and set 'i = front'.

Step 4: Check whether 'front <= rear', if it is TRUE, then


display 'queue[i]' value and increment 'i' value by one
(i++). Repeat the same until 'i <= rear' becomes FALSE.

Step 5: If 'front <= rear' is FALSE, then display


'queue[i]' value and increment 'i' value by one (i++).
Repeat the same until'i <= SIZE - 1' becomes FALSE.

Step 6: Set i to 0.

Step 7: Again display 'cQueue[i]' value and


increment i value by one (i++). Repeat the same until 'i
<= rear' becomes FALSE.

SRSWTI 16
College of
Department of SRSWTI Engineering
Computer Engineering
College of
CONCLUSION : In a standard queue data structure re-bufferingEngineering
problem
occurs for each dequeue operation. To College solve this of
problem by joining the front and rear ends of aEngineering
queue to
make the queue as a 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.

SRSWTI 17
College of
Department of SRSWTI Engineering
Computer Engineering
College of
Engineering
EXPERIMENT NO. 5
College of
AIM : Implementations of singly Linked List. Engineering
PROBLEM : WAP to implement create, insert, delete and display
STATEMENT operations in linked list.

RESOURCES Equipment/Machines - P IV and Above, Printer, Turbo C/C+

REQUIRED +

: Consumables Printer Pages for printouts.

THEORY : Description

A linked list is a sequence of data structures, which are


connected via links.

Linked List is a sequence of links which contains items. Each


link contains a connection to another link. Linked list is the
second most-used data structure after array. Following are
the important terms to understand the concept of Linked List.

Link Each link of a linked list can store a data called


an element.

Next Each link of a linked list contains a link to the


next link called Next.

LinkedList A Linked List contains the connection link


to the first link called First.

Linked List Representation:


Linked list can be visualized as a chain of nodes, where
every node points to the next node.

SRSWTI 18
College of
Department of SRSWTI Engineering
Computer Engineering
College of
Engineering
College of
Engineering

As per the above illustration, following are the important


points to be considered.

Linked List contains a link element called first.

Each link carries a data field(s) and a link field called


next.

Each link is linked with its next link using its next link.

Last link carries a link as null to mark the end of the


list.

Types of Linked List:


Following are the various types of linked list.

Simple Linked List Item navigation is forward only.

Doubly Linked List Items can be navigated forward


and backward.

Circular Linked List Last item contains link of the first


element as next and the first element has a link to the
last element as previous.

Basic Operations:
Following are the basic operations supported by a list.

Insertion Adds an element at the beginning of the list.

Deletion Deletes an element at the beginning of the list.

Display Displays the complete list.

SRSWTI 19
College of
Department of SRSWTI Engineering
Computer Engineering
College of

Engineering
Search Searches an element using the given key.
College of
Delete Deletes an element using the given key.
Engineering
1. Static memory allocation may insert in wastage of memory
and shortage of memory. (Like in array implementations)

2. To outcome these problems, dynamic memory allocation is


used.

3. Linked list is a linear data structure which consists of


number of nodes created dynamically.

4. A linked list has no fix size but grows or shrinks as


elements are added or deleted from the list.

5. A singly linked list is a dynamic data structure. It may grow


or shrink. Growing or shrinking depends on operation made.

6. Every node of list has two fields, information and next


address. Next address field contains memory address
location of next node.

7. A doubly linked list maintains two links, to previous node


and next node. We can delete or insert a node given only a
pointer.

Operations on Singly Linked List:

Algorithm for inserting a node at the beginning

1. Allocate memory for the new node, temp=malloc ().

2. Assign the value of the data field of the new node, temp-
>info

3. Make the link field of the new node to point to the starting
node of the linked list, temp->next=start.

4. Then, set the external pointer (which was pointing to the

SRSWTI 20
College of
Department of SRSWTI Engineering
Computer Engineering
College of
Engineering
starting node) to point to the new node, start=temp.
College of
Algorithm for inserting a node at the end
Engineering
1. If the list is empty then create the new node, temp=malloc
().

2. If the list is not empty, then go to the last node and then
insert the new node after the last node, r=start; go till last
node then r->next=temp.

Algorithm for inserting node at the specified position

1. Allocate memory for the new node, temp=malloc ().

2. Assign value to the data field of the new node, temp->info.

3.Go till node R, also mark next node as S.

4.Make the next field of node temp to node S and next field of
node R to point to new node.

Algorithm for deleting the first node

1. Mark the first node as temp.

2. Then, make start point to the next node.

3. Make next field of temp, null.

4. Free temp.

Algorithm for deleting the last node

1. Mark the last node as temp & last but one node as R.

2. Make the next field of R as NULL.

3. Free temp.

Algorithm for deleting a middle node

1. Mark the node to be deleted as temp.

SRSWTI 21
College of
Department of SRSWTI Engineering
Computer Engineering
College of
2. Mark the previous node as R & next nodes Engineering
as S.
College of
3. Make the next field of R to point S.
Engineering
4. Make the next field of temp, NULL.

5. Free Temp.

CONCLUSION : A linked list is one of the widely-used concepts in


programming applications. So, with the use of linked list
elements are inserted, deleted, and displayed at the first
position, at the last position and at the specific position. In the
process of creating and managing slides in PowerPoint we
can use the concepts such as inserting and deleting nodes.

SRSWTI 22
College of
Department of SRSWTI Engineering
Computer Engineering
College of
EXPERIMENT NO. 6 Engineering
College of
AIM : Implementation of Stack using Linked List. Engineering
PROBLEM : WAP to implement stack operations using linked list.
STATEMENT

RESOURCES : Equipment/Machines - P IV and Above, Printer, Turbo C/C+


REQUIRED +
Consumables Printer Pages for printouts.

THEORY : Stack using Linked List


The major problem with the stack implemented using array is,
it works only for fixed number of data values. That means the
amount of data must be specified at the beginning of the
implementation itself. Stack implemented using array is not
suitable, when we don't know the size of data which we are
going to use. A stack data structure can be implemented by
using linked list data structure. The stack implemented using
linked list can work for unlimited number of values. That
means, stack implemented using linked list works for variable
size of data. So, there is no need to fix the size at the
beginning of the implementation. The Stack implemented
using linked list can organize as many data values as we
want.
In linked list implementation of a stack, every new element is
inserted as 'top' element. That means every newly inserted
element is pointed by 'top'. Whenever we want to remove an
element from the stack, simply remove the node which is
pointed by 'top' by moving 'top' to its next node in the list.
The next field of the first element must be always NULL.

Example

SRSWTI 23
College of
Department of SRSWTI Engineering
Computer Engineering
College of
Engineering
College of
Engineering

In above example, the last inserted node is 99 and the first


inserted node is 25. The order of elements inserted is 25, 32,
ALGORITHM
50 and 99.

1) push(value) - Inserting an element into the Stack


We can use the following steps to insert a new node into the
stack...
Step 1: Create a newNode with given value.
Step 2: Check whether stack is Empty (top == NULL)
Step 3: If it is Empty, then set newNode next = NULL.
Step 4: If it is Not Empty, then set newNode next = top.
Step 5: Finally, set top = newNode.

2) pop() - Deleting an Element from a Stack

We can use the following steps to delete a node from the


stack...

Step 1: Check whether stack is Empty (top == NULL).


Step 2: If it is Empty, then display "Stack is Empty!!!
Deletion is not possible!!!" and terminate the function

SRSWTI 24
College of
Department of SRSWTI Engineering
Computer Engineering
College of
Engineering
Step 3: If it is Not Empty, then define a Node pointer 'temp'
and set it to 'top'. College of
Step 4: Then set 'top = top next'. Engineering
Step 5: Finally, delete 'temp' (free(temp)).

3) display() - Displaying stack of elements


We can use the following steps to display the elements
(nodes) of a stack...
Step 1: Check whether stack is Empty (top == NULL).
Step 2: If it is Empty, then display 'Stack is Empty!!!' and
terminate the function.
Step 3: If it is Not Empty, then define a Node pointer 'temp'
and initialize with top.
Step 4: Display 'temp data --->' and move it to the next
node. Repeat the same until temp reaches to the first node in
the stack (temp next != NULL).
Step 5: Finally! Display 'temp data ---> NULL'.

CONCLUSION :

EXPERIMENT NO. 7
AIM : Implementations of Binary Search Tree menu driven

SRSWTI 25
College of
Department of SRSWTI Engineering
Computer Engineering
College of
program. Engineering
PROBLEM :
College of
WAP to insert element in tree, delete element from tree,
STATEMENT search an element and traverse binary tree. Engineering

RESOURCES : Equipment/Machines - P IV and Above, Printer, Turbo


REQUIRED C/C++.
Consumables Printer Pages for printouts.

THEORY : A binary tree is a finite set of elements that is either


empty or is partitioned into three disjoint subsets. The
first subset contains a single element called the root of
the tree. The other two subsets are themselves binary
tree, called the left and right subtrees of original trees.
Each element of a binary tree is called a node of the
tree. A binary tree of depth d is an almost complete
binary tree if:

1. Any node nd at level less than d-1 has two sons.


2. For any node nd in the tree with a right
descendant at level d, nd must have a left son and
every left descendant of nd is either a leaf at level
d or has two sons.

In a binary search tree, all the nodes that are left


descendants of node A have key values less than A; all
the nodes that are A's right descendants have key values
greater than (or equal to) A. Operations on binary search
tree can be finding a node, inserting a node, traversing
the tree, and deleting a node.

Finding a Node: Finding a node with a specific key is


the simplest of the major tree operations. The nodes in a
binary search tree correspond to objects containing
information The program compares the key value with
the value at the root. The key is less, so the program

SRSWTI 26
College of
Department of SRSWTI Engineering
Computer Engineering
College of
knows the desired node must be on the left side Engineering
of the
tree; otherwise on right side of the tree. WhenCollege
the value of
is matched it is returned to the calling program.Engineering

Inserting a Node: To insert a node we must first find the


place to insert it. This is much the same process as
trying to find a node that turns out not to exist, as
described in the section on Find. We follow the path from
the root to the appropriate node, which will be the parent
of the new node. Once this parent is found, the new
node is connected as its left or right child, depending on
whether the new node's key is less than or greater than
that of the parent.

Deleting a Node: Deleting a node is the most


complicated common operation required for binary
search trees. However, deletion is important in many tree
applications, and studying the details builds character.
You start by finding the node you want to delete, using
the same approach we saw in find () and insert(). Once
you've found the node, there are three cases to consider.

1. The node to be deleted is a leaf (has no children).


2. The node to be deleted has one child.
3. The node to be deleted has two children.

PROCEDURE : Find a Node:


1. Compare with the root node; if found return it and exit.
2. If less than the root, repeat the find procedure in left
subtree.
3. Else if greater than the root, repeat the find procedure in
right subtree.
4. Else return null.
Insert a Node:

SRSWTI 27
College of
Department of SRSWTI Engineering
Computer Engineering
College of
1. Find the proper position to insert a node. Engineering
College
2. If the new node key value is less than the parent node, of
make it its left child.
3. If the new node key value is greater thanEngineering
the parent
node makes it its right child.
CONCLUSION : In Binary tree each node has maximum of two child
nodes. It does not allow duplicate values. Searching in a
binary tree is faster with compare to other trees. It
provides six different traversals. It is used for graph
traversals and to convert an expression to postfix and
prefix forms. Almost for every high-bandwidth routers
binary tree stores router-tables.

EXPERIMENT NO. 08
AIM : Implementation of Quick Sort.

PROBLEM : WAP to arrange elements in ascending order using quick sort


STATEMENT technique.

RESOURCES : Equipment/Machines - P IV and Above, Printer, Turbo C/C++


REQUIRED Consumables Printer Pages for printouts.

THEORY : Quick Sort, as the name suggests, sorts any list very quickly.
Quick sort is not stable search, but it is very fast and requires
very less additional space. It is based on the rule of Divide and

SRSWTI 28
College of
Department of SRSWTI Engineering
Computer Engineering
College of
Engineering
Conquer(also called partition-exchange sort). This algorithm
divides the list into three main parts : College of
1. Elements less than the Pivot element
Engineering
2. Pivot element

3. Elements greater than the pivot element

In the list of elements, mentioned in below example, we have


taken 25 as pivot. So after the first pass, the list will be changed
like this.
6 8 17 14 25 63 37 52

Hnece after the first pass, pivot will be set at its position, with all
the elements smaller to it on its left and all the elements larger
than it on the right. Now 6 8 17 14 and 63 37 52 are considered
as two separate lists, and same logic is applied on them, and we
keep doing this until the complete list is sorted.

How Quick Sorting Works

Algorithm steps:

algorithm quicksort(A, lo, hi) is


if lo < hi then

SRSWTI 29
College of
Department of SRSWTI Engineering
Computer Engineering
College of
p := partition(A, lo, hi) Engineering
quicksort(A, lo, p)
quicksort(A, p + 1, hi)
College of
algorithm partition(A, lo, hi) is
Engineering
pivot := A[lo]
i := lo - 1
j := hi + 1
loop forever
do
i := i + 1
while A[i] < pivot

do
j := j - 1
while A[j] > pivot

if i >= j then
return j

swap A[i] with A[j]

CONCLUSION :
Quick sort is a highly efficient sorting algorithm and is based on
partitioning of array of data into smaller arrays. Using quick sort
method sorting elements in ascending or descending order.

EXPERIMENT NO. 09
AIM : Implementation of Binary Searching method.

PROBLEM : WAP to search an element using Binary search.


STATEMENT

RESOURCES : Equipment/Machines - P IV and Above, Printer, Turbo C/C++


REQUIRED Consumables Printer Pages for printouts.

THEORY : Binary search is the most popular Search algorithm.It is efficient


and also one of the most commonly used techniques that is used
to solve problems.
Binary search looks for a particular item by comparing the middle
most item of the collection. If a match occurs, then the index of
item is returned. If the middle item is greater than the item, then
the item is searched in the sub-array to the left of the middle

SRSWTI 30
College of
Department of SRSWTI Engineering
Computer Engineering
College of
item. Otherwise, the item is searched for in the Engineering
sub-array to the
right of the middle item. This process continues College of
on the sub-array
as well until the size of the subarray reduces toEngineering
zero.
How Binary Search Works?
For a binary search to work, it is mandatory for the target array to
be sorted. We shall learn the process of binary search with a
pictorial example. The following is our sorted array and let us
assume that we need to search the location of value 31 using
binary search.

First, we shall determine half of the array by using this formula

mid = low + (high - low) / 2


Here it is, 0 + (9 - 0 ) / 2 = 4 (integer value of 4.5). So, 4 is the
mid of the array.

Now we compare the value stored at location 4, with the value


being searched, i.e. 31. We find that the value at location 4 is 27,
which is not a match. As the value is greater than 27 and we
have a sorted array, so we also know that the target value must
be in the upper portion of the array.

We change our low to mid + 1 and find the new mid value again.
low = mid + 1
mid = low + (high - low) / 2
Our new mid is 7 now. We compare the value stored at location 7
with our target value 31.

SRSWTI 31
College of
Department of SRSWTI Engineering
Computer Engineering
College of
Engineering
College of
Engineering
The value stored at location 7 is not a match, rather it is more
than what we are looking for. So, the value must be in the lower
part from this location.

Hence, we calculate the mid again. This time it is 5.

We compare the value stored at location 5 with our target value.


We find that it is a match.

We conclude that the target value 31 is stored at location 5.


Binary search halves the searchable items and thus reduces the
count of comparisons to be made to very less numbers.

Algorithm steps:
Procedure binary_search
A sorted array
n size of array
x value to be searched

Set lowerBound = 1
Set upperBound = n

while x not found


if upperBound < lowerBound
EXIT: x does not exists.

set midPoint = lowerBound + ( upperBound - lowerBound ) / 2

if A[midPoint] < x

SRSWTI 32
College of
Department of SRSWTI Engineering
Computer Engineering
College of
set lowerBound = midPoint + 1 Engineering
if A[midPoint] > x
College of
set upperBound = midPoint - 1 Engineering
if A[midPoint] = x
EXIT: x found at location midPoint

end while

end procedure

Binary search is a fast search algorithm with run-time complexity


CONCLUSION :
of (log n). This search algorithm works on the principle of divide
and conquers. For this algorithm to work properly, the data
collection should be in the sorted form.

EXPERIMENT NO. 10
AIM : Implementation of Graph menu driven program (DFS & BFS)

PROBLEM : WAP to Implement Depth First Search and Breadth First


STATEMENT Search (DFS & BFS).

RESOURCES : Equipment/Machines - P IV and Above, Printer, Turbo C/C+


REQUIRED +
Consumables Printer Pages for printouts.

THEORY : In computer science, a graph is a kind of data structure,


specifically an abstract data type (ADT), that consists of a set
of nodes (also called vertices) and a set of edges that
establish relationships (connections) between the nodes. The
graph ADT follows directly from the graph concept from
mathematics.

Informally, G=(V,E) consists of vertices, the elements of V,


which are connected by edges, the elements of E. Formally, a
graph, G, is defined as an ordered pair, G=(V,E), where V is a

SRSWTI 33
College of
Department of SRSWTI Engineering
Computer Engineering
College of
Engineering
College
set (usually finite) and E is a set consisting of two elementof
subsets of V.
Engineering
Two main data structures for the representation of graphs are
used in practice. The first is called an adjacency list, and is
implemented by representing each node as a data structure
that contains a list of all adjacent nodes. The second is an
adjacency matrix, in which the rows and columns of a two-
dimensional array represent source and destination vertices
and entries in the array indicate whether an edge exists
between the vertices. Adjacency lists are preferred for sparse
graphs; otherwise, an adjacency matrix is a good choice.
Finally, for very large graphs with some regularity in the
placement of edges, a symbolic graph is a possible choice of
representation.

Review:
1. A graph G consists of two sets V and E. Set V is a finite
non empty set of vertices and E is a set of pairs of vertices
called edges.
2. There are two possible orders for visiting the vertices of the
graph, Depth First Search (DFS) and Breadth First Search
(BFS).
3. DFS of an undirected graph is roughly analogous to
preorder traversal of an ordered tree.
4. In DFS we traverse a single path of the graph as far as it
can go i.e. until it lists a node with no successors or a node all
of whose successors have already been visited.
5. In BFS all unvisited vertices adjacent to V are visited after
visiting the starting vertex V and marking it as visited. Next
the unvisited vertices adjacent to these vertices are visited
and so on until the entire graph has been traversed. BFS
uses queue to store the nodes of each level of the graph.
Algorithm for Depth First Search
1. Select any unvisited node in the graph. Mark this node as

SRSWTI 34
College of
Department of SRSWTI Engineering
Computer Engineering
College of
visited, push this on to the stack. Engineering
College
2. Find the adjacent node on TOS (top of stack), and which isof
not yet visited, mark this new node as visited & push on to
stack.
Engineering
3. Repeat step 2 until no new node to TOS node can b found,
when no new adjacent node can be found, pop TOS.
4. Repeat step 2 and 3 till stack becomes empty.
5. Repeat step 1 till any more nodes which are still unvisited-
USE ADJANCY MATRIX for finding adjacent nodes.

Algorithm for Breadth First Search


1. Select any unvisited node in the graph. Mark this node as
visited. Insert this node into the queue.
2. Find all the adjacent nodes (one by one) or node present in
the front end of the queue & which is not yet visited, mark this
node as visited & insert it in to the queue.
3. Repeat step 2, till queue becomes empty.
4. Repeat step 1, till any more nodes which are still unvisited.

CONCLUSION : DFS has less time and space complexity rather than BFS.
And in DFS solution can be found out by without much more
search. The DFS spanning tree is special in that there are
no cross edges. This makes it easy to modify DFS into
finding cut vertices (articulation points), bridges, 2-connected
components, and even strongly connected components in
directed graphs.

If there is a solution, then BFS will definitely find it out. And if


there are more than one solution, then BFS can find the
minimal one that requires less number of steps. Sometimes
BFS is better choice because the simplest implementation of
DFS is recursive, which introduces an overhead, and also
might cause code to hit the stack size limit for large graphs.

SRSWTI 35
College of
Department of SRSWTI Engineering
Computer Engineering
College of
Engineering
EXPERIMENT NO. 11
College of
AIM : Mini project Engineering
PROBLEM :
STATEMENT

RESOURCES : Equipment/Machines - P IV and Above, Printer, Turbo


REQUIRED C/C++
Consumables Printer Pages for printouts.

THEORY :

ALGORITHM: :

CONCLUSION :

EXPERIMENT NO. 12
AIM : Write a recursive function to implement Tower of Hanoi.

SRSWTI 36
College of
Department of SRSWTI Engineering
Computer Engineering
College of
PROBLEM : WAP to implement tower of Hanoi usingEngineering
recursive
STATEMENT function. College of
RESOURCES : Engineering
Equipment/Machines - P IV and Above, Printer, Turbo
REQUIRED C/C++, JDK1.5
Consumables Printer Pages for printouts.

THEORY : Recursion is the process of defining an object in terms of


itself.

Characteristics of Recursive Methods:

It calls itself.
When it calls itself, it does so to solve a smaller
problem.
There's some version of the problem that is
simple enough that the routine can solve it, and
return, without calling itself. In each successive
call of a recursive method to itself, the argument
becomes smaller reflecting the fact that the
problem has become "smaller" or easier. When
the argument or range reaches a certain minimum
size, a condition is triggered and the method
returns without calling itself.
In general, to solve a problem recursively, we must deal
with two cases:

1. The base case, where we can solve the problem


directly, and
2. The recursive case, where we solve the problem
in terms of easier sub problems.
When we say that sub problems must be "easier," we
mean that they must be closer to the base case.

The Towers of Hanoi is an ancient puzzle consisting of a


number of disks placed on three columns. All the disks

SRSWTI 37
College of
Department of SRSWTI Engineering
Computer Engineering
College of
Engineering
start out on column A. The object of the puzzle is to
College
transfer all the disks from column A to column C. Only of
one disk can be moved at a time, and no disk Engineering
can be
placed on a disk that's smaller than itself. In the Towers
of Hanoi, we solve the problem of moving n disks in
terms of the easier problem of moving n 1 disk.

ALGORITHM: : 1. Start
2. If n==1, move the single disk from A to C and stop.
3. Move the top n1 disks from S to I.
4. Move the remaining (largest) disk from S to D.
5. Move the top n-1 from I to D.
6. Stop.

CONCLUSION : The Tower of Hanoi is used as a Backup rotation scheme


when performing computer data Backups where multiple
tapes/media are involved. Recursion adds clarity and
reduces the time needed to write and debug code i.e. it
reduces time complexity. Recursion performs better in
solving problems based on tree structures.

SRSWTI 38

Das könnte Ihnen auch gefallen