DSA

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 31

Experiment 1 Aim: Implement ADT Stack using arrays Theory: stack: a more restricted List with the following

constraints: elements are stored by order of insertion from "bottom" to "top" items are added to the top only the last element added onto the stack (the top element) can be accessed or removed stacks are straightforward to implement in several different ways, and are very useful push: add an element to the top pop: remove and return the element at the top peek: return (but not remove) top element pop or peek on an empty stack causes an exception other operations: isEmpty, size push(a) push(b) pop() Algorithm

push(o) if t = S.length 1 then throw FullStackException else tt+1 S*t+ o

pop()

if isEmpty() then throw EmptyStackException else tt1 return S[t + 1]

Conclusion: Successfully implemented stack using arrays

Experiment 2 Aim: Write program to Accept an expression in infix form convert it to postfix

Theory: Infix Expression :

Any expression in the standard form like "2*3-4/5" is an Infix(Inorder) expression.

Postfix Expression :

The Postfix(Postorder) form of the above expression is "23*45/-".

Infix to Postfix Conversion :

In normal algebra we use the infix notation like a+b*c. The corresponding postfix notation is abc*+ Algorithm

Scan the Infix string from left to right. Initialise an empty stack. If the scannned character is an operand, add it to the Postfix string. If the scanned character is an operator and if the stack is empty Push the character to stack. If the scanned character is an Operand and the stack is not empty, compare the precedence of the character with the element on top of the stack (topStack). If topStack has higher precedence over the scanned character Pop the stack else Push the scanned character to stack. Repeat this step as long as stack is not empty and topStack has precedence over the character. Repeat this step till all the characters are scanned. (After all characters are scanned, we have to add any character that the stack may have to the Postfix string.) If stack is not empty add topStack to Postfix string and Pop the stack. Repeat this step as long as stack is not empty. Return the Postfix string.

Conclusion: Accepted an expression in infix form and converted into postfix form

Experiment 3 Aim: Implement ADT Stack using Linked List Theory: stack: a more restricted List with the following constraints: elements are stored by order of insertion from "bottom" to "top" items are added to the top only the last element added onto the stack (the top element) can be accessed or removed A stack implemented using linked nodes or a linked list the front element of the list is the top of the stack implementing the operations: push: insert at front pop: remove and return front element

peek: return front element clear: set front to null

Algorithm

push(o) if t = S.length 1 then throw FullStackException else tt+1 S*t+ o

pop() if isEmpty() then throw EmptyStackException else tt1 return S[t + 1]

Conclusion: Successfully implemented stack using Linked List

Experiment 4 Aim: Write a Program to emulate linked list

Theory: A singly linked list is a concrete data structure consisting of a sequence of nodes . Each node stores Element and link to the next node They can be used to implement several other common abstract data structures, including stacks, queues, associative arrays, and symbolic expressions, though it is not uncommon to implement the other data structures directly without using a list as the basis of implementation. The principal benefit of a linked list over a conventional array is that the list elements can easily be inserted or removed without reallocation or reorganization of the entire structure because the data items need not be stored contiguously in memory or on disk. Linked lists allow insertion and removal of nodes at any point in the list, and can do so with a constant number of operations if the link previous to the link being added or removed is maintained during list traversal.

Algorithm

Inserting at the Head 1.Allocate a new node 2. Insert new element 3. Have new node point to old head 4. Update head to point to new node Removing at the Head 1.Update head to point to next node

in the list 2. Allow garbage collector to reclaim the former first node

Inserting at the Tail 1.Allocate a new node 2. Insert new element 3. Have new node point to null 4. Have old last node point to new node 5. Update tail to point to new node Removing at the Tail 1.Locate the second last node 2.Update the last to the second last node 2. Allow garbage collector to reclaim the former last node

Conclusion: Successfully implemented Linked List in Java

Experiment 5 Aim: Write a Program to Implement Queue ADT using LL

Theory: The Queue ADT stores arbitrary objects Insertions and deletions follow the first-in first-out scheme Insertions are at the rear of the queue and removals are at the front of the queue Main queue operations: enqueue(object): inserts an element at the end of the queue object dequeue(): removes and returns the element at the front of the queue front and rear simply read the value which is located respectively in the head and in the tail of the queue

Algorithm

enqueue(o)

if size() = N 1 then throw FullQueueException else Q*r+ o r (r + 1) mod N dequeue()

if isEmpty() then

throw EmptyQueueException else o Q*f+ f (f + 1) mod N return o

Conclusion: Successfully implemented Queue using Linked List in Java

Experiment 6

Aim: Write a Program to Implement vector ADT

Theory: The Vector ADT extends the notion of array by storing a sequence of arbitrary objects An element can be accessed, inserted or removed by specifying its rank (number of elements preceding it) An exception is thrown if an incorrect rank is specified (e.g., a negative rank)

Algorithm

Extendable Array

Allocate new array of larger size Copy old array to new array

Deallocate old array and use new array

Conclusion: Successfully implemented Queue using Linked List in Java

Experiment 7 Aim: Design and implement a list interface in JAVA Theory: The List ADT models a sequence ofpositions storing arbitrary objects It establishes a before/after relation between positions Accessor methods: first(), last() , prev(p), next(p)

Update methods: replace(p, e) insertBefore(p, e), insertAfter(p, e), insertFirst(e), insertLast(e) remove(p) The Position ADT models the notion of place within a data structure where a single object is stored It gives a unified view of diverse ways of storing data, such as a cell of an array a node of a linked list Just one method: object element(): returns the element stored at the position

Algorithm

Inserting at the Head 1.Allocate a new node 2. Insert new element 3. Have new node point to old head 4. Update head to point to new node Removing at the Head 1.Update head to point to next node in the list 2. Allow garbage collector to reclaim the former first node

Inserting at the Tail 1.Allocate a new node 2. Insert new element 3. Have new node point to null 4. Have old last node

point to new node 5. Update tail to point to new node Removing at the Tail 1.Locate the second last node 2.Update the last to the second last node 2. Allow garbage collector to reclaim the former last node

Conclusion: Successfully implemented Queue using Linked List in Java

Experiment 8 Aim: Design and implement ADT for a sequence Theory: The Sequence ADT is a basic, general purpose, data structure for storing an ordered collection of elements The Sequence ADT is the union of the Vector and List ADTs .Elements accessed by Rank, or Position Generic methods: Vector- based methods: 1. elemAtRank(r), 2. replaceAtRank(r, o), 3. insertAtRank(r, o), 4. removeAtRank(r) List- based methods:

1. first(), last(), prev(p), 2. next(p), replace(p, o), 3. insertBefore(p, o), 4. insertAfter(p, o), 5. insertFirst(o), 6. insertLast(o), 7. remove(p) Bridge methods: atRank(r), rankOf(p)

Conclusion: Successfully created sequences.

Experiment 9 Aim: Write a Program in JAVA to evaluate a post fix expression

ALGORITHM :

STEP 1 : Read the given postfix expression into a string called postfix. STEP 2 : Read one character at a time & perform the following operations : 1. If the read character is an operand, then convert it to float and push it onto the stack. 2. If the character is not an operand, then pop the operator from stack and assign to OP2. Similarly, pop one more operator from stack and assign to OP1. 3. Evaluate the result based on operator x.

4. Push the result (based on operator x) onto the stack. STEP 3 : Repeat STEP 2 till all characters are processed from the input string.

STEP 4 : Return the result from this procedure or algorithm and display the result in main program.

Conclusion: Accepted a postfix and evaluated successfully

Experiment 10 Aim: Write a Program to implement Linked List using iterator Theory: An iterator abstracts the process of scanning through a collection of elements Methods of the Object. Iterator ADT: object object() boolean hasNext() object nextObject()

Extends the concept of Position by adding a traversal capability .Implementation with an array or singly linked list . An iterator is typically associated with an another data structure We can augment the Stack, Queue, Vector, List and Sequence ADTs with method: ObjectIterator elements() Two notions of iterator : snapshot: freezes the contents of the data structure at a given time dynamic: follows changes to data structure

Algorithm

Inserting at the Head 1.Allocate a new node 2. Insert new element 3. Have new node point to old head 4. Update head to point to new node Removing at the Head 1.Update head to point to next node in the list 2. Allow garbage collector to reclaim the former first node

Inserting at the Tail 1.Allocate a new node 2. Insert new element 3. Have new node point to null 4. Have old last node

point to new node 5. Update tail to point to new node Removing at the Tail 1.Locate the second last node 2.Update the last to the second last node 2. Allow garbage collector to reclaim the former last node

Conclusion: Successfully implemented iterator in linked list

Experiment 11 Aim: Write a Program to Implement double link list to demonstrate forward and reverse movement

Theory: Doubly linked lists are like singly linked lists, except each node has two pointers -- one to the next node, and one to the previous node. This makes life nice in many ways: You can traverse lists forward and backward. You can insert anywhere in a list easily. This includes inserting before a node, after a node, at the front of the list, and at the end of the list. You can delete nodes very easily.

Algorithm

Inserting at the Head 1.Allocate a new node 2. Insert new element 3. Have new node point to old head 4. Update head to point to new node Removing at the Head 1.Update head to point to next node in the list 2. Allow garbage collector to reclaim the former first node

Inserting at the Tail 1.Allocate a new node 2. Insert new element 3. Have new node point to null 4. Have old last node point to new node 5. Update tail to point

to new node Removing at the Tail 1.Locate the second last node 2.Update the last to the second last node 2. Allow garbage collector to reclaim the former last node

Conclusion: Successfully implemented Double Linked List

Experiment 12 Aim: Implement towers of Hanoi using recursion Theory: The Tower of Hanoi consists of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape. The objective of the puzzle is to move the entire stack to another rod, obeying the following rules: Only one disk may be moved at a time. Each move consists of taking the upper disk from one of the rods and sliding it onto another rod, on top of the other disks that may already be present on that rod. No disk may be placed on top of a smaller disk.

Algorithm

1)Move the top N-1 disks from Source to Auxiliary tower,

2)Move the Nth disk from Source to Destination tower,

3)Move the N-1 disks from Auxiliary tower to Destination tower.

Conclusion: Used Recursion to transfer Disks from source to destination peg.

Experiment 13 Aim: Implement a binary tree ADT using link list Theory: A binary tree is composed of zero or more nodes Each node contains: A value (some sort of data item) A reference or pointer to a left child (may be null), and A reference or pointer to a right child (may be null) A binary tree may be empty (contain no nodes) If not empty, a binary tree has a root node Every node in the binary tree is reachable from the root node by a unique path A node with neither a left child nor a right child is called a leaf In some binary trees, only the leaves contain a value

Algorithm

def to_list(tree): if tree is None: return None else: return [tree.key, tree.left, tree.right]

Conclusion: Created a Binary tree using linked list successfully

Experiment 14 Aim: Implement the height ( ) and depth ( ) in a binary tree Theory: A binary tree is composed of zero or more nodes The height of a tree is the length of the path from the root to the deepest node in the tree. A (rooted) tree with only one node (the root) has a height of zero. The depth of a node n is the length of the path from the root to the node. The set of all nodes at a given depth is sometimes called a level of the tree. The root node is at depth zero. If h = height of a binary tree, max no of leaves = 2h max no of nodes = 2h + 1 - 1

Algorithm

1. Traverse all left nodes recursively say h1 2. Traverse all right nodes recursively say h2 3. Find max(h1,h2)

Conclusion: Successfully found height and depth of tree

Experiment 15 Aim : Write a Program to implement pre order , post order traversal techniques

Theory: A binary tree is defined recursively: it consists of a root, a left subtree, and a right subtree To traverse (or walk) the binary tree is to visit each node in the binary tree exactly once Tree traversals are naturally recursive Since a binary tree has three parts, there are six possible ways to traverse the binary tree: root, left, right right, left, root root, right, left left, root, right left, right, root

Algorithm

Pre order 1. Visit the root. 2. Traverse the left subtree.

3. Traverse the right subtree.

postorder,: 1. Traverse the left subtree. 2. Traverse the right subtree. 3. Visit the root.

inorder (symmetric), 1. Traverse the left subtree. 1. Visit the root. 2. Traverse the right subtree.

Conclusion: Successfully traversed through the tree

Experiment 16 Aim : Write a Program to Implement a priority queue. Theory: A priority queue stores a collection of entries Each entry is a pair (key, value) Main methods of the Priority Queue ADT insert(k, x) removeMin() inserts an entry with key k and value x removes and returns the

We can use a priority queue to sort a set of comparable elements 1. Insert the elements one by one with a series of insert operations

2. Remove the elements in sorted order with a series of removeMin operations

Algorithm

PQ-Sort(S, C) Input sequence S, comparator C for the elements of S Output sequence S sorted in increasing order according to C P priority queue with comparator C while S.isEmpty () e S.removeFirst () P.insert (e, 0) while P.isEmpty() e P.removeMin().key() S.insertLast(e)

Conclusion: Successfully created priority Queue

Experiment 17 Aim : Write a Program to implement graph ADT and show traversal techniques in graphs . Theory: A graph is a pair (V, E), where V is a set of nodes, called vertices E is a collection of pairs of vertices, called edges Vertices and edges are positions and store elements

Typical higher-level operations associated with graphs are: finding a path between two nodes, like depth-first search and breadth-first search

Algorithm

Algorithm BFS(G) Input graph G Output labeling of the edges and partition of the vertices of G for all u G.vertices() setLabel(u, UNEXPLORED) for all e G.edges() setLabel(e, UNEXPLORED) for all v G.vertices() if getLabel(v) = UNEXPLORED BFS(G, v) Algorithm BFS(G, s) L0 new empty sequence L0.insertLast(s) setLabel(s, VISITED) i0 while Li.isEmpty() Li +1 new empty sequence for all v Li.elements() for all e G.incidentEdges(v) if getLabel(e) = UNEXPLORED w opposite(v,e)

if getLabel(w) = UNEXPLORED setLabel(e, DISCOVERY) setLabel(w, VISITED) Li +1.insertLast(w) else setLabel(e, CROSS) i i +1 Algorithm BFS(G) Algorithm DFS(G) Input graph G Output labeling of the edges of G as discovery edges and back edges for all u G.vertices() setLabel(u, UNEXPLORED) for all e G.edges() setLabel(e, UNEXPLORED) for all v G.vertices() if getLabel(v) = UNEXPLORED DFS(G, v) Algorithm DFS(G, v) Input graph G and a start vertex v of G Output labeling of the edges of G in the connected component of v as discovery edges and back edges setLabel(v, VISITED) for all e G.incidentEdges(v)

if getLabel(e) = UNEXPLORED w opposite(v,e) if getLabel(w) = UNEXPLORED setLabel(e, DISCOVERY) DFS(G, w) else setLabel(e, BACK)

Conclusion: Successfully created graph end executed traversal techniques

Experiment 18 Aim : Write a Program to find minimum spanning tree using Kruskal & Prims Algorithm . Theory: Minimum spanning tree (MST) ==Spanning tree of a weighted graph with minimum total edge weight A priority queue stores the edges outside the cloud Key: weight and Element: edge At the end of the algorithm We are left with one cloud that encompasses the MST (A tree T which is our MST) A priority queue stores the vertices outside the cloud Key: distance Element: vertex Locator-based methods insert(k,e) returns a locator and replaceKey(l,k) changes the key of an item We store three labels with each vertex: Distance, Parent edge in MST,Locator in priority queue

Algorithm

KruskalMST(G) for each vertex V in G do define a Cloud(v) of {v} let Q be a priority queue. Insert all edges into Q using their weights as the key T while T has fewer than n-1 edges do edge e = T.removeMin() Let u, v be the endpoints of e if Cloud(v) Cloud(u) then Add edge e to T Merge Cloud(v) and Cloud(u) return T Prim(G) Q new heap-based priority queue s a vertex of G for all v G.vertices() if v = s setDistance(v, 0) else setDistance(v, ) setParent(v, ) l Q.insert(getDistance(v), v) setLocator(v,l)

while Q.isEmpty() u Q.removeMin() for all e G.incidentEdges(u) z G.opposite(u,e) r weight(e) if r < getDistance(z) setDistance(z,r) setParent(z,e) Q.replaceKey(getLocator(z),r)

Conclusion: Successfully created MST using Prim and Kruskals algorithms

Experiment 19 Aim : Write a Program to demonstrate Merge sort and Quick Sort . Theory: Divide- and conquer is a general algorithm design paradigm: Divide: divide the input data S in two or more disjoint subsets S1, S2. Recur: solve the subproblems recursively Conquer: combine the solutions for S1, S2, , into a solution for S

Algorithm

mergeSort(S, C) Input sequence S with n

elements, comparator C Output sequence S sorted according to C if S.size() > 1 (S1, S2) partition(S, n/2) mergeSort(S1, C) mergeSort(S2, C) S merge(S1, S2)

Algorithm merge(A, B) Input sequences A and B with n/2 elements each Output sorted sequence of A B S empty sequence while A.isEmpty() B.isEmpty() if A.first().element() < B.first().element() S.insertLast(A.remove(A.first())) else S.insertLast(B.remove(B.first())) while A.isEmpty() S.insertLast(A.remove(A.first())) while B.isEmpty() S.insertLast(B.remove(B.first())) return S partition(S, p) Input sequence S, position p of pivot Output subsequences L, E, G of the

elements of S less than, equal to, or greater than the pivot, resp. L, E, G empty sequences x S.remove(p) while S.isEmpty() y S.remove(S.first()) if y < x L.insertLast(y) else if y = x E.insertLast(y) else { y > x } G.insertLast(y) return L, E, G

Conclusion: Successfully implemented merge and quick sort

Experiment 19 Aim : Write a Program to demonstrate Bucket and Radix Sort . Theory: Let be S be a sequence of n (key, element) entries with keys in the range *0, N 1+ Bucket-sort uses the keys as indices into an auxiliary array B of sequences (buckets) Phase 1: Empty sequence S by moving each entry (k, o) into its bucket B[k] Phase 2: For i = 0, , N 1, move the entries of bucket B*i+ to the end of sequence S

Radix-sort is a specialization of lexicographic-sort that uses bucket-sort as the stable sorting algorithm

in each dimension Radix-sort is applicable to tuples where the keys in each dimension I are integers in the range *0, N 1+

Algorithm

bucketSort(S, N) Input sequence S of (key, element) items with keys in the range *0, N 1+ Output sequence S sorted by increasing keys B array of N empty sequences while S.isEmpty() f S.first() (k, o) S.remove(f) B[k].insertLast((k, o)) for i 0 to N 1 while B[i].isEmpty() f B*i+.first() (k, o) B*i+.remove(f) S.insertLast((k, o)) radixSort(S, N)

Input sequence S of d-tuples such that (0, , 0) (x1, , xd) and (x1, , xd) (N 1, , N 1) for each tuple (x1, , xd) in S Output sequence S sorted in

lexicographic order for i d downto 1 bucketSort(S, N)

Conclusion: Successfully implemented radix and bucket sort

You might also like