Professional Documents
Culture Documents
CS-250 Data Structures
CS-250 Data Structures
CS-250
Data Structures and Algorithms
PREPARED BY
Lab manual is prepared by Dr. Naima Iltaf and Lab Engr. Misbah Ghalib under the supervision of Head of Department Dr.
Naveed Iqbal Rao in year 2014.
GENERAL INSTRUCTIONS
a. Students are required to maintain the lab manual with them till the end of the semester.
b. All readings, answers to questions and illustrations must be solved on the place provided. If more space is
required then additional sheets may be attached.
c. It is the responsibility of the student to have the manual graded before deadlines as given by the instructor
d. Loss of manual will result in re submission of the complete manual.
e. Students are required to go through the experiment before coming to the lab session. Lab session details will
be given in training schedule.
f. Students must bring the manual in each lab.
g. Keep the manual neat clean and presentable.
h. Plagiarism is strictly forbidden. No credit will be given if a lab session is plagiarized and no re submission
will be entertained.
i. Marks will be deducted for late submission
VERSION HISTORY
Student has
demonstrated on
Student has basic accurate
Student failed to Student has basic
R3 knowledge of understanding of the
demonstrate a clear understanding, but asked
understanding. Provides lab objective and
Demonstration understanding of questions were not
fundamental answers to concepts. All the
the assigned task answered.
asked questions questions are
answered completely
and correctly
Complete working
program is copied
R5 Most of working program Most of working Complete working
indicating no effort
is copied. Minor program is contributed program is
Perseverance on student’s part
contribution by the by the student. Minor contributed by the
and plagiarism resulting in a total
student copied components student
score of zero for all
rubrics
Complete working
program is copied
Most of working Most of working Complete working
R3 indicating no effort
program is copied. program is contributed program is
on student’s part
Plagiarism Minor contribution by by the student. Minor contributed by the
resulting in a total
the student copied components student
score of zero for all
rubrics
Poor presentation;
Well-organized, clear
cannot explain topic; Presentation lacks clarity Presentation
R5 presentation; good
scientific and organization; little acceptable; adequate
use of scientific
Presentation terminology lacking use of scientific terms use of scientific terms;
vocabulary and
skills or confused; lacks and vocabulary; poor acceptable
terminology; good
understanding of understanding of topic understanding of topic
understanding of topic
topic
At the end of the course the students will be able to: PLOs BT Level*
Instructor
Max. Marks Obtained
Date Experiment Sign
Marks
R1 R2 R3 R4 R5
Grand Total
4. Constructors:
It is convenient if an object can initialize itself when it is first created, without need to make a
separate call to its member functions. C++ provides a non-static member function called as
constructor that is automatically called when object is created. After objects are created, their
members can be initialized by using constructors.
<class-name> (list-of-parameters);
# include<iostream.h>
class maths{
int a;
public:
maths();
void showdata();
};
maths :: maths(){
cout<<”\n this is a constructor”;
a=100;
}
#include <iostream>
using namespace std;
class student {
int rno;
char name[10];
double fee;
public:
student()
{
cout << "Enter the RollNo:";
cin >> rno;
cout << "Enter the Name:";
cin >> name;
cout << "Enter the Fee:";
cin >> fee;
}
void display()
{
cout << endl << rno << "\t" << name << "\t" << fee;
}
};
int main()
{
student s; // constructor gets called automatically when
// we create the object of the class
s.display();
return 0;
}
#include <iostream>
using namespace std;
class student {
int rno;
char name[50];
double fee;
public:
student();
void display();
};
student::student()
{
cout << "Enter the RollNo:";
cin >> rno;
void student::display()
{
cout << endl << rno << "\t" << name << "\t" << fee;
}
int main()
{
student s;
s.display();
return 0;
}
#include <iostream>
private:
double length;
};
return 0;
}
<class-name>: : ~ <class-name>()
{
It is not possible to define more than one destructor. The destructor is only one way to destroy the
object created by the constructor. Hence destructor can-not be overloaded. Destructor neither
requires any argument nor returns any value. It is automatically called when the object goes out of
scope. Destructors release memory space occupied by the objects created by the constructor. In
destructor, objects are destroyed in the reverse of object creation.
First Example
#include <iostream>
using namespace std;
class Test {
public:
Test() { cout << "\n Constructor executed"; }
return 0;
}
Second Example
#include <iostream>
using namespace std;
class Test {
public:
Test() { cout << "\n Constructor executed"; }
main()
{
Test t, t1, t2, t3;
return 0;
}
6. Arrays:
An array is a collection of individual values, all of the same data type, stored in adjacent memory
locations. Using the array name together with an integral valued index in square brackets refers to
the individual values. Multi-dimensional arrays have additional indices for each additional
dimension. The index indicates the position of the individual component value within the
collection of values. The index is also called the subscript.
In C++, the first array element always has subscript 0. The second array element has subscript 1,
etc. The base address of an array is its beginning address in memory.
int main()
{
intArr[100],n,temp;
cout<<"Enter number of elements you want to insert ";
cin>>n;
for(inti=0;i<n;i++)
{
cout<<"Enter element "<<i+1<<":";
cin>>Arr[i];
}
temp=Arr[0];
Arr[0]=Arr[n-1];
Arr[n-1]=temp;
for(i=0;i<n;i++)
cout<<Arr[i]<<" ";
getch();
return 0;
}
Exercise 1.1:
Write a program with constructor function and another for destruction function.
Exercise 1.2:
Write a program to search an element (given by user) in a two dimensional array.
9. Web Resources:
http://www.tutorialspoint.com/cplusplus/cpp_constructor_destructor.htm
http://www.cplusplus.com/doc/tutorial/arrays/
http://www.tutorialspoint.com/cplusplus/cpp_pointers.htm
11. Summary:
This lab session introduces the concepts of constructors and destructors, arrays and pointers in
C++. This lab is designed to revise the concepts of arrays and pointers which will be used in
implementing the concepts of data structures.
4. Linked Lists: A linked list is a data structure consisting of a group of nodes which together
represent a sequence. Under the simplest form, each node is composed of a datum and a reference
(in other words, a link) to the next node in the sequence; more complex variants add additional
links. This structure allows for efficient insertion or removal of elements from any position in the
sequence.
last
first
class Node {
public:
int data;
Node* next; //pointer
};
head
|
|
+---+---+ +---+---+ +----+------+
| 1 | o----->| 2 | o-----> | 3 | NULL |
+---+---+ +---+---+ +----+------+
return 0;
}
class Node {
public:
int data;
Node* next;
};
int main()
{
Node* head = NULL;
Node* second = NULL;
Node* third = NULL;
// Function call
printList(head);
return 0;
}
5.
Insertion: To insert data in a linked list, a record is created holding the new item. The nextpointer
of the new record is set to link it to the item which is to follow it in the list. The nextpointer of the
item which is to precede it must be modified to point to the new item.
if(head == NULL)
{
head = tmp;
tail = tmp;
}
else
{
tail->next = tmp;
tail = tail->next;
}
}
6. Deletion:To deleted data from list, The nextpointer of the item immediately preceding the one to
be deleted is altered, and made to point to the item following the deleted item.
Write a program to display string using linked list. Take a string of character from user and
split the string in character, and then insert each character into linked list.
Example:
String = “RPI”
head R P I NULL
Exercise 2.2:
Consider a scenario where a firm wants to maintain the data of its employees. The data
containing employee number, name, and salary and department # are saved in a singly linked
list. Create following functions for the employee list.
InsertAtFront: Insertion of a record at the front.
InsertAtEnd: Insertion of a record at the end.
Insert: Insertion of a record at any position in the list
DeleteFirst: Deletion of first record.
DeleteLast: Deletion of last record.
Delete: Deletion of a record at any position in the list.
Search: Searching any record based on employee number and dept no.
Display: Displaying all records.
Write a program to split a single linked list in two separate lists and display the both lists.
8. Web Resources:
http://www.cprogramming.com/tutorial/lesson15.html
http://www.cs.cmu.edu/~adamchik/15-121/lectures/Linked%20Lists/linked%20lists.html
http://www.sourcetricks.com/2008/07/c-singly-linked-lists.html
9. Video Resources:
http://www.youtube.com/watch?v=pBrz9HmjFOs
http://www.youtube.com/watch?v=o5wJkJJpKtM
10. Summary:
This lab session introduces the concepts of single linked lists. It also helps students in
implementing singly linked lists using dynamic allocation.
4 Doubly Linked Lists:A doubly linked list is a data structure consisting of a group of nodes which
. together represent a sequence and are connected to each other in both directions (Bi-directional). In
Doubly linked list, each node has two pointers. One pointer to its successor (NULL if there is none) and
one pointer to its predecessor (NULL if there is none) which enables bi-directional
traversing.
Head
5 Insertion:To insert data in a doubly linked list, a record is created holding the new item. The next
. pointer of the new record is set to link it to the item which is to follow it in the list. The pre-pointer of the
new record is set to link it to the item which is to before it in the list.
6 Deletion: In deletion process, element can be deleted from three different places. When the node is
. deleted, the memory allocated to that node is released and the previous and next nodes of that node are
linked.
Write a menu driven program to perform insertion, deletion and display functions for doubly linked
list.
Using the Exercise 5.1, write a function MoveToFront( ) with one argument of data type
integer. This function will first search the linked list and compare the Data member of the
node with the given number as argument. If the search finds the number in the list then this
function will move that node to the start of the list as shown in the example below. The order
of the remaining nodes is to remain unchanged. If no node in the list contains the integer,
MoveToFront( ) should leave the list unchanged. Assume that the list contains no duplicate
values. The structure definition of the doubly linked list is
structListNode{
ListNode *pre;
int Data;
ListNode *Next;
}*head;
The function declaration of MoveToFront function is Void MoveToFront(int);
Example:
The two diagrams below illustrate the effect of the call MoveToFront( 5).
Before the call:
9 Video Resource:
. http://www.youtube.com/watch?v=5s0x8bc9DvQ
http://www.youtube.com/watch?v=JdQeNxWCguQ
4. Stack:
Stack is a memory portion, which is used for storing the elements. The elements are stored based
on the principle of LIFO (Last In, First Out). In stack insertion and deletion of elements take place
at the same end (Top). The last element inserted will be the first to be retrieved.
• This end is called Top
• The other end is called Bottom
Data4 Top
Data3
Data2
Data1 Bottom
5. Top:The stack top operation gets the data from the top-most position and returns it to the user
without deleting it. The underflow state can also occur in stack top operation if stack is empty.
6. Push:The push operation adds a new element to the top of the stack, or initializes the stack if it is
empty. If the stack is full and does not contain enough space to accept the given item, the stack is
then considered to be in an overflow state.
7. Pop:The pop operation removes an item from the top of the stack. A pop either returns previously
inserted items, or NULL if stack is empty.
8. Underflow:When stack contains equal number of elements as per its capacity and no more
elements can be added, the status of stack is known as overflow.
a) Stack Class definition: This class contains private data members i.e. a structure of node
describe the type data to be stored in element and a top pointer to node.
class ListStack{
private:
struct node
{
intnum;
node *next;
}*top;
public:
ListStack()
{
top=NULL;
}
void push();
void pop();
void display();
};
b) Push( ) function:This function creates a new node and ask the user to enter the data to be
saved on the newly created node.
void ListStack::push()
{
node *newNode;
newNode= new node;
cout<<“Enter number to add on stack";
cin>>newNode->num;
newNode->next=top;
top=newNode;
}
void ListStack::pop()
{
node *temp;
temp=top;
if(top==NULL)
cout<<"Stack UnderFlow"<<endl;
else
{
cout<<"deleted Number from the stack =";
cout<<top->num;
top=top->next;
delete temp;
}
}
d) Main( ) function:
Description: To convert a number from decimal to binary, you simply divide by two and push
reminder to stack until quotient is reached to zero, then use pop operation to display the binary
representation of number. For example, to convert (35)10 to binary, you perform the following
computation.
35/2 = 1
17/2 = 1
8/2 = 0
4/2 = 0
2/2 = 0
If you examine the remainders from the last division to the first one, writing them down as you go, you
will get the following sequence: 100011. i.e. (100011)2=(35)10
Write a program to compare opening and closing brackets in expression. This program takes an
expression in the form of string and scan it character by character. Finally the output of the program is
the valid or invalid expression.
Algorithm: To do this comparison a stack ADT can be used to keep track of the scope delimiters
encountered while scanning the expression.
13. Summary:
This lab introduces the concepts of stacks. This lab is designed to implement the concepts of
stacks using both static and dynamic implementation.
Exercise 5.1:
In this Exercise, you have to take a string expression as input from user. Using this infix expression,
you have to convert it into its equivalent postfix notation.
Example: a + ( b * c )
Read an Expression Stack Output
a a
+ + a
( +( a
b +( ab
* +(* ab
c +(* abc
) + abc*
abc*+
Two stacks are required, one for numbers and the other for operators. The algorithm is:
For each item in the infix expression (no parentheses) from the right to the left
o If the item is a number then push it on the number stack.
o If the item is an operator (+,-,*, or /) and: the operator stack is empty or the operator on
the top of the stack is higher in priority (* and / are higher in priority than + or -), then
Pop an operator from the operator stack.
Pop two numbers off the number stack.
Calculate using second number-operator-first number.
Push the result on the number stack.
Push the item on the operator stack.
o Else push the item on the operator stack.
After the loop, while the operator stack is not empty
o Pop an operator from the operator stack.
o Pop two numbers off the number stack.
o Calculate using second number-operator-first number.
o Push the result on the number stack.
The answer is the last item in the number stack.
Exercise 5.2:
Write a C++ code to evaluate the infix expression without parenthesis given by user.
Example: 3+4-5/2
Infix String Operand Stack Operator Stack Value
3 3
+ 3 +
4 34 +
- 34 +-
5 345 +-
/ 345 +-/
2 3452 +-/
34 +- / 2 5 -> 5/2 , Push 2
342 +-
3 + - 2 4 -> 4-2, Push 2
32 +
5 + 2 3 -> 3+2, Push 5
13. Summary:
This lab introduces different real world applications of stacks and their implementation using
static stacks in C++.
4. Queue:
A queue is a particular kind of collection in which the entities in the collection are kept in order
and the principal (or only) operations on the collection are the addition of entities to the rear
terminal position and removal of entities from the front terminal position. This makes the queue a
First-In-First-Out (FIFO) data structure. In a FIFO data structure, the first element added to the
queue will be the first one to be removed. This is equivalent to the requirement that once an
element is added, all elements that were added before have to be removed before the new element
can be invoked. A queue is an example of a linear data structure.
Dynamic: A queue can be implemented as a linked list, and expand or shrink with each enqueue
or dequeue operation.
Front Back
5. Enqueue:TheEnqueue ( ) operation adds a new item to the end of the queue, or initializes the
queue if it is empty.
6. Dequeue:TheDequeue ( ) operation removes an item from the front of the queue. A Dequeue
operation on an empty stack results in an underflow.
class DynQueue{
private:
structqueueNode
{
intnum;
queueNode *next;
};
queueNode *front;
queueNode *rear;
public:
DynQueue();
~DynQueue();
void enqueue();
void dequeue();
bool isEmpty();
void displayQueue();
void makeNull();
};
b) Constructor:
DynQueue::DynQueue()
{
front = NULL;
rear = NULL;
}
c) Enqueue() function:
void DynQueue::enqueue()
{
queueNode *ptr;
ptr = new queueNode;
cout<<"Enter Data";
cin>>ptr->num;
ptr->next= NULL;
if (front == NULL)
{
front = ptr;
rear = front;
d) Dequeue( ) Function:
void DynQueue::dequeue()
{
queueNode *temp;
temp = front;
if(isEmpty())
cout<<"Queue is Empty";
else
{
cout<<"data deleted="<<temp->num;
front = front->next;
delete temp;
}
}
8. Exercises:
Exercise 6.1:
Write a menu driven program to perform different operations with queue such aEnqueue ( ),
In this Exercise, you have to take a single string as input. Using this input string, you have to create
multiple queues in which each queue will comprise of separate word appeared in input string. At the
end, you will again concatenate all queues to a single queue.
Example:
Exercise 4.3:
Write a program to demonstrate a printer queue in which jobs for printing are added on the basis of
priority. Each printing job should have name (e.g. A, B, C, D …..) and priority value (e.g. 1=High,
2=Medium, 3=Low). If two jobs has same priority then FIFO rule should be applied.
front A B A C rear
1 2 2 3
11. Summary:
This lab session introduces the concepts of queues. This lab helps students in implementing queues
using dynamic allocation.
5. Recursive Call:A function call in which the function being called is the same as the one making
the call.
6. Base Case:
7. Recursive Case:A recursive function definition also contains one or more recursive cases;
meaning input(s) for which the program recurs (calls itself).
The job of the recursive cases can be seen as breaking down complex inputs into simpler ones. In
a properly-designed recursive function, with each recursive call, the input problem must be
simplified in such a way that eventually the base case must be reached.
For example, the factorial function can be defined recursively by the equations 0! = 1 and, for all
n > 0, n! = n (n − 1)! None of equation by itself constitutes a complete definition, the first is the
base case, and the second is the recursive case.
Exercise 7.1:
Write a function to calculate triangular number using recursion.
Int trinum(int x);
trinum(4)=10 i.e. 4+3+2+1+0=10
Exercise 7.2:
Create a recursive function for Fibonacci series and a program for calculating it. In
mathematics, the Fibonacci numbers are the numbers in the following integer sequence:
0, 1, 1, 2, 3, 5, 8, 13, 21
By definition, the first two Fibonacci numbers are 0 and 1, and each subsequent number is the
sum of the previous two. In mathematical terms, the sequence Fn of Fibonacci numbers is
defined by the recurrence relation F(n) = F(n-1) + F(n-2) with seed values F(0) = 0 and F(1)
=1
Exercise 7.4:
Write a program to reverse a number.
9. Web References:
http://www.cplusplus.com/articles/D2N36Up4/
http://www.danzig.us/cpp/recursion.html
http://www.learncpp.com/cpp-tutorial/710-recursion/
11. Summary:
This lab introduces students with the concepts of recursion. It allows them to understand the
implementation of recursion and its practical uses.
5. Algorithm:In this problem, there are pegs say A, B and C. There are n discs on peg A of different
diameters and are placed one above the other such that always a smaller disc is placed above the larger disc.
The two pegs B and C are empty. All the discs from peg A are to be transferred to peg C using peg B as
temporary storage. The rules to be followed while transferring the discs are
If there is only one disc, move that disc from A to C. If there are two discs, move the first disc from A to B,
move the second from A to C, then move the disc from B to C. In general, to move n discs from A to C, the
recursive technique consists of three steps:
6. Pseudo code:
MoveDisc(whichDisc, frompeg, topeg)
{
Cout<<"Move ring"+ whichDisc+"frompeg"+frompeg+"topeg"+topeg);
}
MoveTower( height, frompeg, topeg, usingpeg) Mission : go from A to C
{
MoveTower( height-1, frompeg,usingpeg, topeg); First going(with n-1 discs) from A to B using C
MoveDisc( height, frompeg, topeg); Printing the nth disc
MoveTower( height-1, usingpeg, topeg,frompeg); Then going from B to C using A
}
Exercise 7.5:
Write a recursive function to implement the algorithm of tower of Hanoi.
8. Web References:
http://en.wikipedia.org/wiki/Tower_of_Hanoi
http://www.dsalgo.com/2013/02/towers-of-hanoi.html
9. Video Link:
www.youtube.com/watch?v=5QuiCcZKyYU
www.youtube.com/watch?v=5_6nsViVM00
10. Summary:
This lab introduces students with practical resolution of a well-known problem using concepts of
Data Structure and Algorithms.
Pseudo code:
6. Insertion Sort:This algorithm takes one value at a time and builds up another sorted list of values.
It helps if you can imagine what you do when you play a game of cards: you pick a card and insert
it to an already sorted list of cards.
Pseudo code:
insertionSort(array A)
{This procedure sorts in ascending order.}
begin
for i := 1 to length(A)-1 do
begin
value := A[i];
j := i - 1;
done := false;
repeat
{ To sort in descending order simply reverse
the operator i.e. A[j] < value }
if A[j] > value then
begin
A[j + 1] := A[j];
j := j - 1;
if j < 0 then
done := true;
end
7. Bubble Sort:This algorithm looks at pairs of entries in the array, and swaps their order if needed.
After the first step of the algorithm the maximal value will "bubble" up the list and will occupy the
last entry. After the second iteration, the second largest value will "bubble" up the list and will
occupy the next to last entry, and so on.
Pseudo code:
8. Merge Sort:This recursive algorithm belongs to the very important divide-and-conquer paradigm.
It consists of the following steps:
Divide-the elements to be sorted into two groups of equal (or almost equal) size.
Conquer - Sort each of these smaller groups of elements (by recursive calls).
Merge - Combine the two sorted groups into one large sorted list.
Pseudo code:
funcmergesort( var a as array )
if ( n == 1 ) return a
l1 = mergesort( l1 )
l2 = mergesort( l2 )
9. Exercises:
Exercise 8.1:
Exercise 8.2:
12. Summary:
This lab introduces students with the concepts of sorting. It also helps them in implementing
different sorting algorithms such as bubble, merge, insertion and selection sort.
Pseudocode:
LINEAR(DATA,N, ITEM,LOC)
Set DATA[N+1] = ITEM
Set LOC = 1
Repeat while DATA[LOC] !=ITEM
Set LOC = LOC +1
If LOC = N+1, then Set LOC =0
Exit.
Pseudo code:
BINARY(DATA,LB,UB,ITEM,LOC)
Exercise 9.1:
Exercise 9.2:
Write a program to search an element linearly from the entered numbers. Also, indicate its
position in case the element is found or unavailability.
Write a program to demonstrate binary search. Use character array and store 10 names. This
program prompts the user to enter ten names. They are stored in ascending order the
name[15][10] the fn[15] is used to store the name which we want to search.
8. Web Resources:
http://algorithms.openmymind.net/search/linear.html
http://www.csit.parkland.edu/~mbrandyberry/CS1Java/Lessons/Lesson27/BinarySearch.htm
9. Video Links:
www.youtube.com/watch?v=vohuRrwbTT4
http://tune.pk/video/2451896/binary-search-tree-implementation-in-cc
10. Summary:
This lab introduces students with the search algorithms. It helps students in implementing binary
search and linear search algorithms.
The Key value in the left child is not more than the value of root
The key value in the right child is more than or identical to the value of root
All the sub-trees, i.e. left and right sub-trees follow the two rules mention above.
5. Minimum:The minimum element of a binary search tree is the last node of the left roof
6. Maximum: The maximum element is the last node of the right roof.
7. Exercises:
Exercise 10.1:
Write a menu driven program for inserting and deleting an element of binary search tree.
8. Web References:
http://www.personal.kent.edu/~rmuhamma/Algorithms/MyAlgorithms/binarySearchTree.htm
https://www.cs.auckland.ac.nz/~jmor159/PLDS210/niemann/s_bin.htm
http://www.sanfoundry.com/cpp-program-implement-binary-tree-2/
9. Video References:
www.youtube.com/watch?v=COZK7NATh4k
www.youtube.com/watch?v=5vwVuLMzqxQ
10. Summary:
This lab introduces students with the concepts of Binary search tree, its practical usages and its
implementation.
5. Graph Traversing:Traversing a graph consists of visiting each vertex only one time. We can
traverse the graph by two ways:
Depth first search
Breadth first search
6. Breadth First Search: Breadth-first search (BFS) is a graph search algorithm that begins at the root
node and explores all the neighbouring nodes. Then for each of those nearest nodes, it explores their
unexplored neighbour nodes, and so on, until it finds the goal.
Pseudo code:
----------------------------------------------------------------------------------------------------------------
procedure BFS(Graph,v):
create a queue Q
enqueue v onto Q
mark v
while Q is not empty:
t ← Q.dequeue()
for all edges e in G.incidentEdges(t) do
o ← G.opposite(t,e)
if o is not marked:
mark o
enqueue o onto Q
7. Depth First Search: Depth-first search (DFS) is an algorithm for traversing or searching a tree,
tree structure, or graph. One starts at the root (selecting some node as the root in the graph case) and
explores as far as possible along each branch before backtracking.
Exercise 11.1:
Create the following class Graph. Implement all function listed in class and test using menu
driven program.
class Graph
{
private:
structGNode
{
int data;
GNode *ptr;
bool visited;
};
GNode *GList;
public:
graph();
void Create();
voidInsertVertex(int);
voidInsertEdge();
voidDisplayVertices();
voidDeleteVertex();
voidDeleteEdges();
boolSearchVertex();
boolSearchEdge();
voidBFSTraversal();
voidDFSTraversal();
};
Write a function called DelAllMinEdges( ). This function will first search all the edges in the
graph and will delete all those edges having minimum weight. Consider that graph is
implemented using Adjacency List. Consider the following structure for both Vertices and
Edges
StructGNode
{
int weight;
GNode *ptr;
}*GList;
Note: In the following example DelAllMinEdges( ) will delete the edge between vertex 4 to 3
and 1to 4 because of minimum weight.
9. Web References:
http://www3.cs.stonybrook.edu/~algorith/files/graph-data-structures.shtml
http://interactivepython.org/runestone/static/pythonds/Graphs/graphintro.html
https://www.cs.auckland.ac.nz/~jmor159/PLDS210/mst.html
11. Summary:
This lab introduces students with the concepts of graphs and their implementation.
9. Dijkstra Algorithm:
1. Assign to every node a tentative distance value: set it to zero for our initial node and to infinity
for all other nodes.
2. Mark all nodes unvisited. Set the initial node as current. Create a set of the unvisited nodes
called the unvisited set consisting of all the nodes except the initial node.
3. For the current node, consider all of its unvisited neighbours and calculate
their tentative distances.
4. When we are done considering all of the neighbours of the current node, mark the current node
as visited and remove it from the unvisited set. A visited node will never be checked again; its
distance recorded now is final and minimal.
5. If the destination node has been marked visited (when planning a route between two specific
nodes) or if the smallest tentative distance among the nodes in the unvisited set is infinity
(when planning a complete traversal), then stop. The algorithm has finished.
6. Set the unvisited node marked with the smallest tentative distance as the next "current node"
and go back to step 3.
10. Exercises:
Exercise 12.1:
Write a program, which reads an adjacency matrix representation of a graph and applies
Kruskal’s algorithm to find minimum spanning tree of the input graph.
Exercise 12.2:
Consider the following graph and calculate the shortest path using Dijkstra Algorithm from
V0 to V3. Show all the steps involved in the calculations.
13. Summary:
This lab introduces students with MST and DijkstraAlgorithm. It also helps students in solving the
shortest path algorithm using Dijkstra Algorithm.
5. Hashing Function:A simple function is applied to the key to determine its place in the collection.
6. Hash Table: A hash table is simply an array that is addressed via a hash function. Here Hash
Table is an array with 8 elements. Each element is a pointer to a linked list of numeric data. The
hash function for this example simply divides the data key by 8, and uses the remainder as an
index into the table. This yields a number from 0 to 7. Since the range of indices for Hash Table
is 0 to 7, we are guaranteed that the index is valid.
7. Exercises:
Exercise 13.1:
Write a program to prepare the hashing table as shown above. Take the elements through the
keyboard and map them in hash table.
Write a function deleteNode deletes and frees a node from the table.
Exercise 13.3:
8. Web Resources:
https://www.cs.auckland.ac.nz/software/AlgAnim/hash_func.html
http://datastructuresnotes.blogspot.com/2009/03/hashing-hash-data-structure-and-hash.html
9. Video Resources:
www.youtube.com/watch?v=MfhjkfocRR0
http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-046j-introduction-to-
algorithms-sma-5503-fall-2005/video-lectures/lecture-7-hashing-hash-functions/
10. Summary:
This lab introduces students with hash functions, hash tables, their uses and their implementation.
TASK:
Build the Huffman coding tree for the following sequence of characters:
EIEIOEIEIOEEIOPPEEEEPPSSTTEEEPPPPTTSSEIEIOEIEIOEEIOPPEEEEEEEPPPPTTSS
Steps:
For a given sequence of letters:
1. Count the frequency of occurrence for the letters in the sequence.
2. Sort the frequencies into increasing order.
3. Build the Huffman coding tree:
_ choose the two smallest values, make a (sub) binary with these values.
_ accumulate the sum of these values
_ replace the sum in place of original two smallest values and repeat from 1.
_ construction of tree is a bottom-up insertion of sub-trees at each iteration.
4. Making the codes: Traverse tree in top-down fashion
_ Assign a 0 to left branch and a 1 to the right branch
_ Accumulate 0s and 1s for each character from root to end vertex.
_ This is the Huffman code for that character.
Confucius