You are on page 1of 116

National University of Technology

Islamabad, Pakistan

Electrical Engineering Department

Lab Manual

Data Structures & Algorithms


(EE-2006)

Name: _____________________________________________

Roll No: ___________ CMS No: ___________

Semester: __________ Group: ___________


List of Experiments
Introduction to Code Blocks IDE, basic C programming including data types,
Experiment No: 1
operators, and conditional statements.
Experiment No: 2 Loops, functions and arrays

Experiment No: 3 Strings, pointers and Structures

Experiment No: 4 Implementation of single linked list

Experiment No: 5 Implementation of double linked list

Experiment No: 6 Open-Ended Lab - I

Experiment No: 7 Implementation of stack

Experiment No: 8 Implementation of queue

Experiment No: 9 Implementation of tree data structure – I

Experiment No: 10 Implementation of searching algorithms

Experiment No: 11 Midterm Exam

Experiment No: 12 Implementation of sorting algorithms – I

Experiment No: 13 Open-Ended Lab – II

Experiment No: 14 Implementation of sorting algorithms - II

Experiment No: 15 Implementation of graph data structure

Experiment No: 16 End Semester Exam


National University of Technology
Islamabad, Pakistan

Electrical Engineering Department

EE-2006 Data Structures and Algorithms Semester: V

EXPERIMENT NO.1:

Introduction to C and Code Blocks IDE, basic C Programming including

Data types, Operators and Conditional Statements

OBJECTIVE:

 Introduction to Code Blocks IDE Environment


 How to create new project and Compile C Programs with GCC Compiler
 Variables, Data Types and Operations in C
 Conditional Statements (IF,IF-ELSE,SWITCH)

Date of Experiment: ________________

Submitted on: ________________

CMS no. ________________

Obtained Marks: _______

Remarks: _____________

Instructor’s Signature:
______________________
1. C Programming Language

The C programming language is a general purpose, high level language (generally denoted
as structured language). C programming language was at first developed by Dennis M.
Ritchie at AT&T Bell Labs. C is one of the most commonly used programming languages. It
is simple and efficient therefore it becomes best among all. Many software’s &
applications as well as the compilers for other programming languages are written in C also
operating systems like UNIX, DOS, and Windows 95 were written in C.

C has now become a widely used professional language for various reasons −

 Easy to learn
 Structured language
 It produces efficient programs
 It can handle low-level activities
 It can be compiled on a variety of computer platforms

Fig. 1 A Translation Hierarchy for C


Fig. 2 C program compiled in to Assembly and then assembled in binary machine code
2. Code Blocks IDE
1. Launch the Code Blocks IDE

2. In the Code Blocks IDE, choose File | New |Project

3. In the New from Template wizard, choose Console Application


4. In the Console Application wizard, choose C language and proceed

5. Now write the Project name and set the path of Project folder and proceed
6. Now choose the GCC C compiler from dropdown menu and click finish

7. The IDE by default create a source C file named main.c


8. Now choose Build | Build and Run

9. After Successful Build and Run the output “Hello World” will be displayed on the screen
3. Variables
During programming we need to store data. This data is stored in variables. Variables are
locations in memory for storing data. The memory is divided into blocks and there is a
numerical address for each location of a memory block. It is difficult for us to handle these
numerical addresses in our programs. So we give a name to these locations and these
names are variables. We call them variables because they can contain different values at
different times. In C every variable has the following attributes.
 Name
 Type
 Size
 Value

4. Data Types
A variable must have a data type associated with it, for example it can have data types like
integers, decimal numbers and characters. The variable of type integer stores the integer
values and a character type variable store character value. The primary difference in these
data types is their size in memory.
5. Arithmetic operators
An operator is the symbol that tells the compiler to perform the specific mathematical or
logic functions. C language is rich in built-in operators and provides the following types of
operators.
 Arithmetic operators
 Relational operators
 Logical operators
 Bitwise operators
 Assignment operators
6. Conditional Statements
Conditional statements allow user to make decision, based upon the result of a condition.
These statements are called decision making statements or conditional statements. C
support following conditional statements
 IF statement
 IF-ELSE statement
 ELSE-IF statement
 SWITCH

(1). IF statement:
IF statement is used to execute the some lines of code, if a test condition is true
otherwise if condition is false, execute nothing.

(2). IF-ELSE statement:


IF –ELSE statement is used to execute some lines of code, if a condition is true
otherwise if condition is false, execute some other lines of code.
(3). ELSE-IF statement:
ELSE-IF is a like doing another IF for a true or false value

(4). SWITCH:
A switch statement allows a variable to be tested for equally against a list of values. Each
value is called a case, and the variable being switched on is checked for each switch case.
LAB TASK
National University of Technology
Islamabad, Pakistan

Electrical Engineering Department


EE-2006 Data Structure and Algorithms Semester: V

EXPERIMENT NO.2:

Loops, Functions and Arrays

OBJECTIVE:

 For, while and do while loops in C


 Functions in C
 Creating user defined functions and calling them in main program

Date of Experiment: ________________

Submitted on: ________________

CMS: ________________

Obtained Marks:

Remarks:

Instructor’s Signature:
LOOPS:
There are situations, when a block of code needs to be executed several number of times. In
general, statements are executed sequentially. The first statement is executed first,
followed by second and so on. A loop statement allows us to execute a statement or group
of statements multiple times. Given below is the general form of a loop statement in most
of the programming languages.

C programming language provides the following types of loops:

 FOR Loop
 WHILE Loop
 DO-WHILE Loop

1. FOR Loop:

Whenever we need to execute certain action multiple times, we need to wrap statements
inside the loop.
Initial Expression

for ( i=0 ; i < 5 ; i++ ) Update Expression


{
Test Expression
Printf(“Hello World!!!!! \n”);

} Body of the loop

In the above program we have printed the string “Hello World!!!!!” 5 times.
2. WHILE Loop:

A WHILE loop in C programming repeatedly executes a target statements as long as the


given condition is true. The syntax of while loop is shown below.

while (condition)
{
Statements;
}

Example Code:

/////////////////////////////////////////////////////////////////////

#include<stdio.h>

int main()
{

int a = 10;

while (a < 20)


{
Printf(“Value of a = %d \n”,a );
a++;
}
return 0;
}

/////////////////////////////////////////////////////////////////////

You can also make an infinite loop using while(1) statement. The syntax of infinite
loop is
while(1)
{
Statements;
}
3. DO-WHILE Loop:

Unlike for and while loops, which test the loop condition at the top of the loop, the do-
while loop in C programming checks its condition at the bottom of the loop. A do-while loop
is similar to while loop, except the fact that it is guaranteed to execute at least one time.

do {

statements;

} while(condition);

Example code

/////////////////////////////////////////////////////////////////////

#include <stdio.h>

int main ()
{

int a = 20;

do {

printf(“Value of a = %d \n”,a);
a = a + 1;

} while(a < 20);

return 0;

/////////////////////////////////////////////////////////////////////
Functions:
A function is a group of statements that together perform a task. Every C program has at
least one function, which is main (). You can divide up your code in to separate functions.
How you divide up your code among different functions is up to you, but logically the
division is such that each function performs a specific task. A function declaration tells the
compiler about a function’s name, return type and parameters

Example Code

/////////////////////////////////////////////////////////////////////

#include <stdio.h>

int max(int num1, int num2);

int main () {

int a = 10;
int b = 20;
int c;

c = max(a,b);
printf(“Max Value = %d”,c);
return 0;

int max (int num1, int num2 )


{

Int result;

If(num1 > num2)

result = num1;

else

result = num2;

return result;

/////////////////////////////////////////////////////////////////////
ARRAYS:
Array is a container which can hold fix number of items and these items should be of same
type. Most of the data structure makes use of array to implement their algorithms.
Following are important terms to understand the concepts of array.

 Element (Each item stored in an array is called an element)


 Index (Each location of an element in an array has a numerical index which is used to
identify the element)

An array can be declared in various ways. Let take an example of array declaration in C.

As per above shown illustration, following are the important points to be considered.

1. Array index starts with 0.


2. Array length is 10 which mean it can store 10 elements.
3. Each element can be accessed via its index.

Operations:

 Traverse (Print all the elements one by one).


 Insertion (Add an element at given index).
 Deletion (Delete an element at given index from an array).
 Search (Search an element using given index or by given value).
 Update (Update an element at given index)

(1). Insertion Operation:


In insertion operation user can insert one or more data elements in to an array. Depending
on user’s choice or requirement, new element can be added at any location of an array
(Starting, Middle and End).
Let an Array is a linear unordered array of N elements and K is a positive integer such that
K <= N. Algorithm to insert an item at Kth index of an Array is shown below.

Algorithm
1. Start
2. Set J=N
3. Set N=N+1
4. Repeat Steps 5 and 6 while J >= K
5. Set Array[J+1] = Array[J]
6. Set J=J-1
7. Set Array[K]= Item
8. Stop

Example Code

/////////////////////////////////////////////////////////////////////

#include <stdio.h>

int main () {

int Array[] = {1,2,3,4,5};


int Data = 100;
int k=3;
int n=5;
int i=0 , j=n;

printf(“Data in an Array is :”); // Entering data in to Structure

for(i=0 ; i < n ; i++)


{
printf(“Array[%d] = %d \n”, i , Array[i]);
}
n = n + 1;
while( j >= k)
{
Array[j+1] = Array [j];
j = j – 1;
};
Array[k] = Data;
printf(“The updated Array is :”);
for(i=0 ; i < n ; i++)
{
printf(“Array[%d] = %d \n”, i , Array[i]);
}
return 0;
}
/////////////////////////////////////////////////////////////////////

(2). Deletion Operation:


Deletion refers to removing an existing element from the array and re-organizing all
elements of an array.

Let an Array is a linear unordered array of N elements and K is a positive integer such that
K <= N. Algorithm to remove an item at Kth index of an Array is shown below.

Algorithm
1. Start
2. Set J=K
3. Repeat Steps 4 and 5 while J < N
4. Set Array[J-1] = Array[J]
5. Set J=J+1
6. Set N=N-1
7. Stop

Example Code

/////////////////////////////////////////////////////////////////////

#include <stdio.h>

int main () {

int Array[] = {1,2,3,4,5};


int k=3;
int n=5;
int i,j;

printf(“Data in an Array is :”); // Entering data in to Structure

for(i=0 ; i < n ; i++)


{
printf(“Array[%d] = %d \n”, i , Array[i]);
}
J = k;
while( j < n)
{
Array[j-1] = Array [j];
j = j + 1;
};
n = n – 1;
printf(“The updated Array is :”);
for(i=0 ; i < n ; i++)
{
printf(“Array[%d] = %d \n”, i , Array[i]);
}
return 0;
}
/////////////////////////////////////////////////////////////////////

(3). Search Operation:


In search operation, user can perform searching of a specific element in an array based on
its value or its index.

Let an Array is a linear unordered array of N elements and K is a positive integer such that
K <= N. Algorithm to find an item in an Array is shown below.

Algorithm
1. Start
2. Set J=0
3. Repeat Steps 4 and 5 while J < N
4. If Array[J] = Item then goto step 6
5. Set J=J+1
6. Print J, Item
7. Stop

Lab Task-1 (Write a C code for above algorithm)

/////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////

(4). Update Operation:


Update operation refers to updating an existing element from the array at a given index.

Let an Array is a linear unordered array of N elements and K is a positive integer such that
K <= N. Write down the algorithm to update an element in an array.

Algorithm
1.
2.
3.
4.
5.

Lab Task-2 (Write down the C code for update operation in an array)

/////////////////////////////////////////////////////////////////////

Types of Arrays

Array a kind of data structure that can store a fixed size sequential collection of elements of
the same type. An array is used store a collection of data, but it is often more useful to think
of an array as a collection of variables of the same data type. For example: if the user wants
to store marks of 100 students. This can be done by creating 100 variables individually but,
this process is rather tedious. This type of problem can be handled in C programming using
arrays. All arrays consist of contiguous memory locations. The lowest address corresponds
to the first element and the highest address to the last element. Arrays are of two types:
1. One-Dimensional Arrays.
2. Multi-Dimensional Arrays.

1-D Arrays:
To declare an array in C, programmer specifies the type of the elements and the number of
elements required by an array as follows

int Array [10];


Size

Data Type Name

The data type of an array can be valid C data type like int, float, single, double etc. The size
of an array must be integer constant greater than zero. The Example code below takes 5
integers as an input from user to store in an array and then print the array contents on
screen.

Example Code

/////////////////////////////////////////////////////////////////////

#include <stdio.h>

int main () {

int Array[5]; // Declaring the Array of size 5


int i,j;

for(i=0 ; i<5 ; i++)


{
Printf(“Enter the Array Element: %d \n”, i);
Scanf(“%d”, &Array[i]); // Taking input from user and stores in an Array
}

for(j=0 ; j<5 ; j++)


{
Printf(“Array[%d]=%d\n” , j , Array[j]); //Printing the Array elements on Screen
}

return 0;

/////////////////////////////////////////////////////////////////////
Multi-Dimensional Arrays:
C programming language allows programmers to create arrays of arrays known as multi
dimensional arrays. The simplest form of multi dimensional array is the two-dimensional
array. A two dimensional array is, in essence, a list of one dimensional arrays. The two
dimensional array can be declared as follows

Type ArrayName [x][y]

Where type can be any valid C data type and ArrayName will be a valid C identifier. A two
dimensional array can be considered as a table which will have x number of rows and y
number of columns. A two dimensional array, which contains three rows and four columns
can be shown as follows.

Thus, every element in the array a is identified by an element name of the form a[ i ][ j ],
where 'a' is the name of the array, and 'i' and 'j' are the subscripts that uniquely identify
each element in 'a'.

Example Code

/////////////////////////////////////////////////////////////////////

#include <stdio.h>

int main () {

int Array[5][5]; // Declaring the Array of size 5


int i,j,x,y;

for(i=0 ; i<5 ; i++)


{
for(j=0 ; j<5 ; j++)
{
Printf(“Enter the Array Element: %d %d \n”, i, j);
Scanf(“%d”, &Array[i][j]); // Taking input from user and stores in an Array
}
}
for(x=0 ; x<5 ; x++)
{
for(y=0 ; y<5 ; y++)
{
Printf(“Array[%d][%d]=%d\n” , x, y, Array[x][y]); //Printing the Array elements on Screen
}
}
return 0;

/////////////////////////////////////////////////////////////////////

Note: In 1-D Array single for loop will be used for storing or reading array elements and in
2-D Array two for loops will be used in nested form.

LAB TASK
National University of Technology
Islamabad, Pakistan

Electrical Engineering Department

EE-2006 Data Structures and Algorithms Semester: V

EXPERIMENT NO.3:

Strings, Pointers and Structures

OBJECTIVE:

Date of Experiment: ________________

Submitted on: ________________

CMS: ________________

Obtained Marks:

Remarks:

Instructor’s Signature: ______________________________


STRINGS:
Strings are actually one dimensional array of characters terminated by a null character (\0).
Thus a null terminated string contains the characters that comprise the string followed by a
null. The following declaration and initialization create a string consisting of the word
"Hello". To hold the null character at the end of the array, the size of the character array
containing the string is one more than the number of characters in the word "Hello."

char Text[6] = {‘H’, ‘E’,‘E’, ‘L’,‘0’, ‘\0’ }

Following is the memory presentation of the above defined string

The program below allows user to read the string from user as an input and display on the
screen. String variable Name can only take a word. It is because when white space is
encountered, the scanf() function terminates. Here program will ignore second word
because, scanf() function takes only string before the white space.

Example Code

/////////////////////////////////////////////////////////////////////

#include <stdio.h>

int main () {

char Name[30];
printf(“Enter the string : ”);
scanf(“%s”,&Name);
printf(“Your entered string is %s”,Name);
return 0;

}
/////////////////////////////////////////////////////////////////////
Output:
Enter your string: FEAS RIPHAH
Your entered string is FEAS

/////////////////////////////////////////////////////////////////////
C language provides two basic functions gets() and puts() to read and write the strings. Now
re-write the above code by using gets() and puts() functions instead of scanf() and printf()
functions. Now the output of the program will shows both the words in the string. By using
gets() function user can enter white spaces in the string while entering the string as an input
to the program.

You can perform different type of string operations manually like: finding the length of the
string, concatenating two strings, copy one string to other string etc. For programmers ease,
many built in functions are available under header file <string.h>. Few commonly used string
handling functions are

 Strlen() // Computes and returns the length of the given string


 Strcpy() // Copy the whole string in to another string
 Strcat() // Concatenate (Joins) two separate strings in to single string
 Strlwr() // Converts the lower case alphabets in to upper case in a
string
 Strupr() // Converts the upper case alphabets in to lower case in a
string
 Strcmp() // Compare two strings

POINTERS:
As we know, every variable is a memory location and every memory location has its address
defined which can be accessed using ampersand (&) sign, which denotes an address in
memory. A pointer is a variable whose value is the address of another variable, i.e direct
address of the memory location. Like any variable and constant, you must declare a pointer
before using it to store any variable address. The general type of pointer variable
declaration is

type *variable_name;

Here, type is the pointer’s base type; it must be a valid C data type and variable_name is the
name of the pointer variable. The asterisk (*) used to declare a pointer is the same asterisk
used for multiplication. However, in this statement the asterisk is being used to designate a
variable pointer as a pointer.

Example Code

/////////////////////////////////////////////////////////////////////

#include <stdio.h>
int main () {

int a = 10;
int *b; // pointer variable declaration

b = &a; // store address of variable a in pointer variable


printf(“Address of variable a : \n ”, &a);
printf(“Address stored in variable b : \n ”, b);
printf(“Value stored in *b variable \n ”, *b);
return 0;

}
/////////////////////////////////////////////////////////////////////

Null Pointer:

It is always a good practice to assign a NULL value to a pointer variable in case you do not
have an exact address to be assigned. This is done at the time of variable declaration. A
pointer that is assigned NULL is called a null pointer. The NULL pointer is a constant with a
value of zero defined in several standard libraries.

Pointer to Pointer:

A pointer to a pointer is the form of multiple indirection, or a chain of pointers. Normally, a


pointer contains the address of a variable. When we define a pointer to a pointer, the first
contains the address of the second pointer, which points to the location that contains the
actual value as show below

A variable that is a pointer to a pointer must be declared by placing double asterisk sign (**)
with variable name.

Example Code

/////////////////////////////////////////////////////////////////////

#include <stdio.h>
int main () {

int a = 10;
int *b; // pointer variable declaration
int **c; // pointer to pointer variable declaration

b = &a;
c = &b;

printf(“Value of variable a : \n ”, a);


printf(“Value available at *b : \n ”, *b);
printf(“Value available at **c \n ”, **c);
return 0;

}
/////////////////////////////////////////////////////////////////////

STRUCTURE:

Arrays allow defining type of variables that can hold several data items of the same kind.
Similarly structure is another user defined data type available in C that allows combining
data items of different kinds. Structures are used to represent a record. Suppose you want
to keep track of your books in a library. You might want to track the following attributes
about each book

 Title
 Author
 Book ID
 Book Price

To define a structure, you must use a struct statement. The struct statement defines a new
data type, with more than one member

Struct Book {

Char title[50];
Char author[50];
Int book_id;
float price;
};

To access any member of a structure, we use the member access operator (.).

Example Code

/////////////////////////////////////////////////////////////////////
#include <stdio.h>

struct Book
{
Char Title[50];
Char Author[50];
Int Book_Id;
float Price;
};

int main () {

struct Book B1;

printf(“Enter the Title :”); // Entering data in to Structure


gets(B1.Title);
printf(“Enter the Author :”);
gets(B1.Author);
printf(“Enter the Book_Id :”);
scanf(“%d”,&B1.Book_Id);
printf(“Enter the Price :”);
scanf(“%f”,&B1.Price);

puts(B1.Title); // Printing the Structure data


puts(B1.Author);
printf(“%d\n”,B1.Book_Id);
printf(“%f”,B1.Price);
return 0;
}
/////////////////////////////////////////////////////////////////////
LAB TASK
National University of Technology
Islamabad, Pakistan

Electrical Engineering Department

EE-2006 Data Structure and Algorithms Semester: V

EXPERIMENT NO.04:

Implementation of Single Linked List

OBJECTIVE:

 Understand the concept of Linked list


 Implement single linked list in C
 Operations on single linked list (Add node, edit node, delete node)

Date of Experiment: ________________

Submitted on: ________________

CMS: ________________

Obtained Marks:

Remarks:

Instructor’s Signature:
______________________________
LINKED LIST:
A linked list is a sequence of data structures which are connected together via links. Linked
list is a sequence of links which contains items. Each link contains a connection to another
link. Linked list the second most used data structure after array. Linked list is a dynamic data
structure whose length can be increased or decreased at run time. Linked list basically
consists of memory blocks that are located at random memory locations. Now, one would
ask how are they connected or how then can be traversed, Well they connected through
pointers. Usually a block in a linked list is represented through a structure. How linked lists
are different from arrays, consider the following points:

 An array is a static data structure. This means the length of an array cannot be
altered at run time. While, a linked list is a dynamic data structure.
 In an array, all the elements are kept at consecutive memory locations while in a
linked list the elements (nodes) may be kept at any location but still connected to
each other.

Linked lists are preferred in those applications where volume of the data is not known. For
example, In an employee management system, one cannot use arrays as they are of fixed
length while any number of new employees can join.

Following are the most important points to be considered:

 Linked list contains a link element called first.


 Each node contains a data fields and a link field called next.
 The next field of last node contains NULL to mark the end of the list.

TYPES:
There are three types of linked lists

1. Singly Linked List (Item Navigation forward only).


2. Doubly Linked List (Items can be navigated forward and backward way).
3. Circular Linked List (Last item contains link of first element as next and the first
element has link to last element as previous).

Singly Linked List:


Linked list basically consists of memory blocks that are located at random memory locations.
Now, one would ask how are they connected or how then can be traversed, Well they are
connected through pointers. Usually a block in a linked list is represented through a
structure like this:

Struct node
{

Int value;
Struct node *next;
};

The structure shown above contains two items in it. One is value which contains the data
and the second item is a pointer to a structure which contains the address of the next node
(memory block) of the linked list.

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

 Insertion (Adding a new node in a linked list)


 Deletion (Deleting a node)
 Display (Displaying the elements of the linked list)
 Search (Searching an element in the linked list)

Insertion:

Adding a new node in linked list is a more than one step activity. First create a new node
using the same structure and find the location where it has to be inserted.

Let we are inserting a node B(new node) between node A(left node) and node C(right node).
Then point B.next to C node.

Now next of the left node (A node) should point to the new node (B node).
This will put a new node (B node) in the middle of the two nodes. The now list should be
look like.

Using the same way a new node can be inserted at any place (beginning, middle and end) of
a linked list.

Deletion:

Deletion is also a more than one step process. First locate the target node to be removed by
searching.

The left (previous node) of the target node now should point to the next node of the target
node.

This will remove the link that was pointing to target node. Now we shall remove to what
target node is pointing. Put a NULL to a Target node next field like targetnode.next = NULL;

We need to use the deleted node we can keep that in memory otherwise we can simply
deallocate memory and wipe off the target node completely.
Example Code (Singly Linked List)

/////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h> printf(“\n Restored List :”);
display_list();
struct node printf(“\n”);
{ struct node *found_link = find(4);
int data;
int key; if(found_link!=Null)
struct node *next; {
}; printf(“Element Found”);
printf(“(%d,%d)”,found_link-
struct node *head = NULL; >key,found_link->data);
struct node *current = NULL; printf(“\n”);
}
int main() else
{ {
printf(“Element not found”);
insert_first(1,5); }
insert_first(2,10); printf(“\n”);
insert_first(3,15); sort();
insert_first(4,4); printf(“Linked List after sorting :”);
insert_first(5,20); display_list();
insert_first(6,50); reverse(&head);
printf(“Linked List after reversing :”);
printf(“Original Linked List is :”); display_list();
display_list(); }

while(!is_empty()) void display_list()


{ {
struct node *temp = delete_first();
printf(“\n Deleted Value :”); struct node *ptr = head;
printf(“(%d,%d)”,temp->key,temp->data);
} printf(“\n[”);
printf(“\n Linked List After Deletion of All while(ptr!=NULL)
items :”); {
display_list(); printf(“(%d,%d)”,ptr->key,ptr->data);
ptr = ptr -> next;
insert_first(1,5); }
insert_first(2,10); printf(“]”);
insert_first(3,15); }
insert_first(4,4);
insert_first(5,20); void insert_first(int key, int data)
insert_first(6,50); {
struct node *link = (struct node*) else
malloc(sizeof(struct node)); {
current = current -> next;
link->key = key; }
link-> data = data; }
link->next = head; return current;
head = link; }
}
struct node* delete(int key)
{
struct node* delete_first()
{ struct node* current = head;
struct node *temp_link = head; struct node* previous= NULL;
head = head -> next;
return temp_link; if(head == NULL)
} {
return NULL;
bool is_empty() }
{ while(current->key != key)
return head == NULL; {
} if(current->next==NULL)
{
int length() return NULL;
{ }
int i=0; else
struct node *current; {
for (current = head; current != NULL; previous = current;
current = current -> next) current = current -> next;
{ }
i++; }
} if(current == head)
return i; {
} head = head -> next;
}
struct node* find(int key) else
{ {
struct node* current = head; previous -> next = current -> next;
if(head==NULL) }
{ return current;
return NULL; }
}
while(current->key != key) void sort()
{ {
if(current->next ==NULL) int i,j,k;
{ int temp_data,temp_key;
return NULL; struct node *current;
} struct node *next;
int size = length();
k = size;

for(i=0 ; i<size-1 ; i++,k--)


{
current = head;
next = head -> next;
for(j=1 ; j < k ; j++)
{

if(current->data > next->data)


{
temp_data = current -> data;
current->data = next->data;
next->data = temp_data;

temp_key = current -> key;


current->key = next->key;
next->key = temp_key;
}
current = current -> next;
next = next -> next;
}
}
}

void reverse(struct node** head_ref)


{
struct node* prev = NULL;
struct node* current = *head_ref;
struct node* next;
while(current != NULL)
{
next = current -> next;
current->next = prev;
prev = current;
current = next;
}
*head_ref = prev;
}
///////////////////////////////////////////////////////////////////////

OUTPUT
National University of Technology
Islamabad, Pakistan

Electrical Engineering Department

EE-2006 Data Structure and Algorithms Semester: V

EXPERIMENT NO.05:

Implementation of Double Linked List

OBJECTIVE:

 Understand the concept of Double Linked list


 Implement Double linked list in C
 Operations on Double linked list (Add node, edit node, delete node)

Date of Experiment: ________________

Submitted on: ________________

CMS: ________________

Obtained Marks:

Remarks:

Instructor’s Signature:
______________________________
Double Linked List is a variation of linked list in which navigation is possible in both ways
either forward or backward easily as compared to single linked list. Following are the
important terms to understand the concept of double linked list

 Node ---- Each node of a linked list can store a data called an element.
 Next ---- Each node of a linked list contains a link to a next node called Next.
 Prev ---- Each node of a linked list contains a link to a previous node called Prev.

Following are the basic operations

 Insertion ---- Add an element at the beginning of a list


 Deletion ---- Delete an element at the beginning of a list
 Insert Last ---- Add an element in the end of the list
 Delete Last ---- Delete an element from the end of the list
 Insert After ---- Add an element after an item of the list
 Delete ---- Delete an element from the list using a key
 Display Forward ---- Displaying complete list in forward manner
 Display Backward ---- Displaying complete list in backward manner

Example Code

/////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

struct node
{
int data;
int key;
struct node *next;
struct node *prev;
};
struct node *head = NULL; {
struct node *last = NULL; struct node *link = (struct node*)
struct node *current = NULL; malloc(sizeof(struct node));
link->key = key;
bool isEmpty() link->data = data;
{
return head == NULL; if(isEmpty())
} {
last = link;
int length () }
{ else
int count = 0; {
struct node *current; head->prev = link;
for(current = head ; current != NULL ; }
current = current->next) link->next = head;
{ head = link;
count++; }
}
return count; void insertLast(int key, int data)
} {
struct node *link = (struct node*)
void displayForward() malloc(sizeof(struct node));
{ link->key = key;
struct node *ptr = head; link->data = data;
printf(“\n [ ”);
while(ptr != NULL) if(isEmpty())
{ {
printf(“(%d,%d)”,ptr->key,ptr->data); last = link;
ptr = ptr->next; }
} else
printf(“ ] ”); {
} last->next = link;
link->prev = last;
void displayBackward() }
{ last = link;
struct node *ptr = last; }
printf(“\n [ ”);
while(ptr != NULL) struct node* deleteFirst()
{ {
printf(“(%d,%d)”,ptr->key,ptr->data); struct node *temp = head;
ptr = ptr->prev;
printf(“ ”); if(head->next == NULL)
} {
printf(“ ] ”); last = NULL;
} }
else
void insertFirst(int key, int data) {
head->next->prev = NULL; else
} {
head = head->next; current->prev->next = current->next;
return temp; }
} if(current==last)
{
struct node* deleteLast() last=current->prev;
{ }
struct node *temp = last; else
{
if(head->next == NULL) current->next->prev = current->prev;
{ }
head = NULL; return current;
} }
else
{ bool insertAfter(int key, int newKey, int
last->prev->next = NULL; data)
} {
last = last->prev; struct node *current = head;
return temp; if(head==NULL)
} {
return false;
struct node* delete(int key) }
{
struct node *current = head; while(current->key != key)
struct node *previous= NULL; {
if(current->next == NULL)
if(head==NULL) {
{ return false;
return NULL; }
} else
while(current->key != key) {
{ current = current->next;
if(current->next == NULL) }
{ }
return NULL;
} struct node *new = (struct node*)
else malloc(sizeof(struct node));
{ new->key = key;
previous = current; new->data= data;
current = current->next;
} if(current == last)
} {
if(current==head) new->next = NULL;
{ last = new;
head=head->next; }
} else
{
new->next = current->next;
current->next->prev = new;
}
new->prev = current;
current->next = new;
return true;
}

int main()
{
insertFirst(1,10);
insertFirst(2,20);
insertFirst(3,30);
insertFirst(4,100);
insertFirst(5,40);
insertFirst(6,50);

printf(“\n List (First to Last)”);


displayForward();

printf(“\n”);
printf(“\n List (Last to First)”);
displayBackward();

printf(“\n List, After deleting first entry”);


deleteFirst();
displayForward();

printf(“\n List , After deleting last entry”);


deleteLast();
displayForward();

printf(“\n List, Insert an Entry after key(4)”);


insertAfter(4,7,80);
displayForward();

printf(“\n List After delete key(4)”);


delete(4);
displayForward();
}
/////////////////////////////////////////////////////////////////////
Output
National University of Technology
Islamabad, Pakistan

Electrical Engineering Department

EE-2006 Data Structure and Algorithms Semester: V

EXPERIMENT NO.6 (OPEN ENDDED LAB-I):

Circular Linked List

OBJECTIVE:

 Understand the concept of Circular Linked list


 Implement Circular linked list in C
 Operations on Circular linked list (Add node, display list, delete node)

Date of Experiment: ________________

Submitted on: ________________

CMS: ________________

Obtained Marks:

Remarks:

Instructor’s Signature: ______________________________


Circular Linked List:
Circular linked list is a variation of linked list first element points to the last element and last
element points to first element. Both singly and doubly linked list can be made in to as
circular linked list.

Singly Linked List as Circular Linked List:


Recall the single linked list which we have studied in lab 9. In a single linked list the next field
of last node has NULL, if that next field have the address of first node then it will become
circular linked list. Circular linked list using single linked is shown below.

Doubly Linked List as Circular Linked List:


In a doubly linked list, the next field of the last node points to the first node and the prev
field of the first node points to the last node making the circular in both directions.

Basic Operations:
Following are the important operations supported by a circular linked list.

 Insert
 Delete
 Display
Example Code (Circular Linked List using Singly Linked List)
/////////////////////////////////////////////////////////////////////

#include <stdio.h> {
#include <stdlib.h> head=link;
#include <string.h> head->next=head;
#include <stdbool.h> }
else
struct node { {
int data; link->next=head;
int key; head=link;
struct node *next; }
}; }
struct node * deleteFirst()
struct node *head = NULL; {
struct node *current = NULL; struct node *temp = head;
if(head->next==head)
bool isEmpty() {
{ head=NULL;
return head == NULL; return temp;
} }
head=head->next;
int length() return temp;
{ }
int Count = 0; void printList()
if(head==NULL) {
{ struct node *ptr = head;
return 0; printf(“\n [ ”);
} if(head != NULL)
current = head->next; {
while(ptr->next != NULL)
while(current != head) {
{ printf(“(%d,%d)”,ptr->key,ptr->data);
Count++; ptr=ptr->next;
current = current->next; }
} }
return Count; Printf(“ ] ”);
} }
void insertFirst(int key, int data) int main()
{ {
struct node *link = (struct node*) insertFirst(1,100);
malloc(sizeof(struct node)); insertFirst(2,200);
link->key=key; insertFirst(3,300);
link->data=data; insertFirst(4,400);
insertFirst(5,500);
if(isEmpty()) insertFirst(6,600);
printf(“Origninal List: ”);
printList();
while(!isEmpty())
{
struct node *temp=deleteFirst();
printf(“\n Deleted Value: ”);
printf(“(%d,%d)”,temp->key,temp->data);
}
Printf(“\n List After deleteing all items :”);
printList();
}
/////////////////////////////////////////////////////////////////////
Output:

/////////////////////////////////////////////////////////////////////

Lab Task: implement circular linked list with the help of double linked list (write down
the main alteration needed in above code)
National University of Technology
Islamabad, Pakistan

Electrical Engineering Department

EE-2006 Data Structure and Algorithms Semester: V

EXPERIMENT NO.07:

Implementation of Stack

OBJECTIVE:

 Understand the concept of Stack


 Implementation of Stack using Array
 Stack operations (Push & Pop)
 Implementation of Stack using Linked List

Date of Experiment: ________________

Submitted on: ________________

CMS: ________________

Obtained Marks:

Remarks:

Instructor’s Signature: ______________________________


A stack is an abstract data type (ADT), commonly used in most programming languages. It is
name stack as it behaves like a real world stack. A real world stack allows operations at one
end only. Stack ADT allows all data operations at one end only. At any given time, we can
only access the top element of a stack. Stack is a LIFO (Last in First Out) data structure. Here
the element inserted at last, is accessed first. In stack terminology, insertion operation is
called push and removal operation is called pop operation.

A stack can be implemented by means of Array, Structure, Pointer and Linked List. Stack can
either be a fixed size one or it may be of dynamic size. Stack operations may involve the
initializing the stack, using it and then de-initializing but the primary operations of stack are

 PUSH ----- Inserting an element on the stack


 POP ------- Removing an element from the stack

To use the stack efficiently we need to check the status of stack as well. For this purpose
following functionality is added to stacks.

 Peek ------ Get the top data element of the stack, without removing it.
 Empty --- Check if stack is EMPTY
 Full ------- Check if stack is FULL

The process of putting a new data element onto stack is known as Push operation. Push
operation involves the following steps

1. Check if stack if full


2. If stack is full then exit
3. If stack is not full, increment top to point next empty space
4. Add data element
5. Return success
Accessing the content while removing it from stack, is known as pop operation. In array
implementation of pop operation, data element is not actually removed, instead top is
decremented to a lower position in stack to point to next value. But in linked list
implementation of pop actually removes data element and de-allocates memory space. The
pop operation involves the following steps

1. Check if stack is empty


2. If stack is empty then exit
3. If stack is not empty, access the data element at which top is pointing
4. Decrease the value of top by 1
5. Return success

Example Code (Stack using Array)


/////////////////////////////////////////////////////////////////////
#include <stdio.h>
#define Max 10
int Stack[Max];
int Top = -1;

int main() {

push(10);
push(20);
push(30);
push(40);
push(50);
printf(“Element at the Top of the Stack : %d \n”, peek());
printf(“Elements : \n”);
while(!is_empty())
{
int data = pop();
printf(“%d\n”, data);
}
printf(“Stack Full : %s \ n”,is_full()?”True”:”False”);
printf(“Stack Empty : %s \ n”,is_empty()?”True”:”False”);
return 0;
}
int is_empty() {
if(Top == -1)
return 1;
else
return 0;
}
int is_full() {
if(Top == Max )
return 1;
else
return 0;
}
int peek() {
return stack[Top];
}
int pop() {
int data;
if(!is_empty()) {
data = Stack[Top];
Top = Top – 1;
return data;
}
else {
printf(“Stack is Empty !!!!!\n”);
}
}

int push(int data) {

if(!is_full()) {
Top = Top + 1;
Stack[Top] = data;
}
else
{
printf(“Stack is Full….. \n”);
}
}
/////////////////////////////////////////////////////////////////////
Task : Run the above code and take the snapshot of output window and attach it.

Example Code (Stack using Linked List)


////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <stdlib.h>

struct node
{
Int info;
struct node *ptr
}*top,*top1,*temp;

int top_element();
void push(int data);
void pop();
void empty();
void display();
void destroy();
void stack_count();
void create();
int count = 0;

void main()
{
int no, choice, e;

printf(“\n 1---> Push”);


printf(“\n 2---> Pop”);
printf(“\n 3---> Top”);
printf(“\n 4---> Empty”);
printf(“\n 5---> Exit”);
printf(“\n 6---> Display”);
printf(“\n 7---> Stack Count”);
printf(“\n 8---> Destroy Stack”);

create();
while(1)
{
printf(“\n Enter the choice : ”);
scanf(“%d”, &choice);
switch(choice)
{
case 1:
printf(“Enter the data to be pushed : ”); Printf(“\n No of elements in stack :
scanf(“%d”, &no); %d”,count);
push(no); }
break; void push(int data)
case 2 : {
pop(); if(top==NULL)
break; {
case 3 : top = (struct node *) malloc(sizeof(struct
if(top==NULL) node));
printf(“No Elements in Stack”); top->ptr = NULL;
else top->info = data;
{ }
e = top_element(); else
printf(“\n Top Element = %d”,e); {
} temp = (struct node *)
break; malloc(sizeof(struct node));
case 4 : temp->ptr = top;
empty(); temp->info = data;
break; }
case 5 : count++;
exit(0); }
case 6 : void display()
display(); {
break; top1 = top;
case 7 : if(top1==NULL)
stack_count(); {
break; printf(“Stack is Empty”);
case 8 : return ;
destroy(); }
break; while(top1 != NULL)
default : {
printf(“Wrong Choice, Please Re-Enter printf(“%d“,top->info);
your choice”); top = top->ptr;
break; }
} }
} void pop()
} {
void create() top1=top;
{ if(top1==NULL)
top = NULL; {
} printf(“\n Error : Trying to poping an
void stack_count() empty stack”);
{ return;
}
else
top1 = top1->ptr;
printf(“\n Popped Value : %d”, top->info);
free(top);
top = top1;
count--;
}
int top_element()
{
return(top->info);
}
void empty()
{
if(top==NULL)
printf(“\n Stack is Empty”);
else
printf(“\n Stack is not Empty with %d elements”, count);
}
void destroy()
{
top1=top;
while(top1 != NULL)
{
top1=top->ptr;
free(top);
top=top1;
top1 = top1->ptr;
}
free(top1);
top=NULL;
printf(“\n All Stack elements destroyed”);
count=0;
}
/////////////////////////////////////////////////////////////////////
Task : Run the above code and take the snapshot of output window and attach it.
National University of Technology
Islamabad, Pakistan

Electrical Engineering Department

EE-2006 Data Structure and Algorithms Semester: V

EXPERIMENT NO.08:

Implementation of Queue

OBJECTIVE:

 Understand the concept of Queue


 Implementation of Queue using Array
 Queue operations (enqueue and dequeue)
 Implementation of Queue using Linked List

Date of Experiment: ________________

Submitted on: ________________

CMS: ________________

Obtained Marks:

Remarks:

Instructor’s Signature: ______________________________

Queue is an abstract data structure, somewhat similar to stack. In contrast to stack, queue is
opened at both ends. One end is always used to insert data and the other is used to remove
data. Queue follows FIFO (First In First Out) methodology. In Fifo the data items stored first
will be accessed first. A real world example of queue can be a single lane one way road,
where the vehicle enters first, exits first.

Same as stack, queue can also be implemented using array, linked list, pointer, and
structures. Queue operations may involve initializing or defining the queue, utilizing it and
then erasing it from memory. Here we shall try to understand basic operations associated
with queues.

 Enqueue() ---------- Add or store an item to the queue


 Dequeue() ---------- Remove or access an items from the queue

Few more functions are required to make above mentioned queue operation efficient.
These are

 Peek() ---------- Get the element at front of the queue without removing it
 Isfull() ---------- Checks if queue is full
 Isempty() ---------- Check if queue is empty

In queue, we always dequeue data, pointed by front pointer and while enqueing data in
queue we take help of rear pointer.

1. Enqueue Operation:

As queue maintains two data pointers, front and rear, its operations are
comparatively more difficult to implement than stack. The following steps should be
taken to enqueue data into a queue

 Check if queue is full.


 If queue is full, produce overflow error and exit.
 If queue is not full, increment rear pointer to point next empty space.
 Add data element to the queue location, where rear is pointing.
 Return success.
2. Dequeue Operation:

Accessing data from queue is a process of two tasks, access the data where front is
pointing and remove the data after access. The steps are

 Check if queue is empty.


 If queue is empty, produce underflow error and exit.
 If queue is not empty, access data where front is pointing.
 Increment front pointer to point next available data element.
 Return success.

Example Code (Queue using Array)


////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX 6
int Queue[MAX];
int front=0;
int rear=0;
int Count=0;

int peek()
{ insert(3);
return Queue[front]; insert(4);
} insert(5);

bool isEmpty() // front : 0


{ // rear : 4
return Count==0; // --------------------------------
} // index : 0 1 2 3 4
// --------------------------------
bool isFull() // Queue:1 2 3 4 5
{
return Count==MAX; insert(6);
}
// front : 0
int size() // rear : 5
{ // --------------------------------
return Count; // index : 0 1 2 3 4 5
} // --------------------------------
// Queue:1 2 3 4 5 6
void insert(int data)
{ if(isFull())
if(!isFull()) {
{ printf(“Queue is Full”);
if(rear==MAX-1) }
{ Int num = remove();
rear=-1; printf(“Element removed = %d \n”,num);
}
Queue[++rear]=data; // front : 1
Count++; // rear : 5
} // --------------------------------
} // index : 1 2 3 4 5
// --------------------------------
int remove() // Queue:2 3 4 5 6
{
int data=Queue[front++]; insert(7);
if(front==MAX)
{ // front : 1
front=0; // rear : -1
} // --------------------------------
Count--; // index : 0 1 2 3 4 5
return data; // --------------------------------
} // Queue:7 2 3 4 5 6

int main() // As Queue is full


{ insert(8);
insert(1); insert(9);
insert(2);
printf(“Element at front = %d\n”,peek());
printf(“--------------------------------------\n”);
printf(“Index : 5 4 3 2 1 0 \n”);
printf(“--------------------------------------\n”);
printf(“Queue : ”)
while(!isEmpty())
{
int n=remove();
printf(“%d”,n);
}
}
////////////////////////////////////////////////////////////////////
Task: Take the snapshot of the output window and attach it.

Example Code(Queue using Linked List)


////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <stdlib.h>

struct node
{
int info;
struct node *ptr;
}*front,*rear,*temp,*front1;

int frontelement();
void enq(int data);
void deq();
void empty();
void display();
void create();
void queuesize();

int count = 0;

void create()
{
front = rear = NULL;
}
void queuesize()
{
printf("\n Queue size : %d", count);
}
void enq(int data)
{
if (rear == NULL)
{
rear = (struct node *)malloc(sizeof(struct rear->ptr = NULL;
node)); rear->info = data;
front = rear; else
} {
Else printf("\n Dequed value : %d", front-
{ >info);
temp=(struct node *)malloc(sizeof(struct free(front);
node)); front = NULL;
rear->ptr = temp; rear = NULL;
temp->info = data; }
temp->ptr = NULL; count--;
rear = temp; }
} int frontelement()
count++; {
} if ((front != NULL) && (rear != NULL))
void display() return(front->info);
{ else
front1 = front; return 0;
if ((front1 == NULL) && (rear == NULL)) }
{ void empty()
printf("Queue is empty"); {
return; if ((front == NULL) && (rear == NULL))
} printf("\n Queue empty");
while (front1 != rear) else
{ printf("Queue not empty");
printf("%d ", front1->info); }
front1 = front1->ptr; void main()
} {
if (front1 == rear) int no, ch, e;
printf("%d", front1->info); printf("\n 1 - Enque");
} printf("\n 2 - Deque");
void deq() printf("\n 3 - Front element");
{ printf("\n 4 - Empty");
front1 = front; printf("\n 5 - Exit");
if (front1 == NULL) printf("\n 6 - Display");
{ printf("\n 7 - Queue size");
printf("\n Error: Trying to display elements create();
from empty queue"); while (1)
return; {
} printf("\n Enter choice : ");
else scanf("%d", &ch);
if (front1->ptr != NULL) switch (ch)
{ {
front1 = front1->ptr; case 1:
printf("\nDequed value : %d",front->info); printf("Enter data : ");
free(front); scanf("%d", &no);
front = front1; enq(no);
} break;

case 2:
deq();
break;
case 3:
e = frontelement();
if (e != 0)
printf("Front element : %d", e);
else
printf("\n No front element in Queue as queue is empty");
break;
case 4:
empty();
break;
case 5:
exit(0);
case 6:
display();
break;
case 7:
queuesize();
break;
default:
printf("Wrong choice, Please enter correct choice ");
break;
}
}
}
////////////////////////////////////////////////////////////////////
Task: Take the snapshot of the output window and attach it.

LAB TASK:
Write down the algorithms for Enqueue and Dequeue in the boxes given below
National University of Technology
Islamabad, Pakistan

Electrical Engineering Department

EE-2006 Data Structure and Algorithms Semester: V

EXPERIMENT NO.9:

Implementation of Tree Data Structure

OBJECTIVE:

 Understand the concept of Tree Data Structure


 Understand the concept of Tree Traversal (inorder, preorder, postorder)
 Understand the concept of Binary Search Tree
 Implementation of Binary Search Tree
 Operation on BST (Insert, Search, Inorder, Preorder, Postorder)

Date of Experiment: ________________

Submitted on: ________________

CMS: ________________

Obtained Marks:

Remarks:

Instructor’s Signature: ______________________________


Tree represents nodes connected by edges. In this lab we will focus on binary tree and
binary search tree. Binary tree is a special data structure used for data purposes. A binary
tree has a special condition that each node can have two children at maximum. A binary
tree have benefits of both an ordered array and a linked list as search is as quick as in sorted
array and insertion or deletion are as fast as in linked list. Figure below gives brief
information about the tree.

Following are the important terms need to be remembered.

 Root Node at the top of the tree is root node. There is only one root per
tree and one path from root node to any node.
 Path Path refers to sequence of nodes along the edges of the tree.
 Parent Any node except root node has one edge upward to a node called
parent node.
 Child Node below a given node connected by its edge downward is called
its child node.
 Leaf Node which does not have any child node is called leaf node.
 Subtree Sub tree represents the descendants of a node.
 Visiting Visiting refers to checking value of the node.
 Traversing Traversing means passing through nodes in a specific order.

Tree Traversal:
Tree traversal is the process to visit all the nodes of a tree and may print their values too if
needed. Because all the nodes are connected via edges we always start from the root node,
we cannot random access a node in tree. There are three ways to traverse the tree

 In-order Traversal
 Pre-order Traversal
 Post Order Traversal
Inorder Traversal:

In this method, the left sub tree is visited first, then root and then right sub tree. Consider
the figure given below. We start from A, and following inorder traversal, we move to its left
sub tree B. B is also traversed inorder and the process goes on until all the nodes are visited.
The output of inorder traversal of this tree will be D-B-E-A-F-C-G.

Preorder Traversal:

In this traversal method, the root is visited first, and then left sub tree and finally right sub
tree. Consider the figure shown below. We start from A and following preorder traversal, we
first visited A itself and then move to its left sub tree B. B is also traversed pre ordered and
the process goes on until all the nodes are visited. The output of preorder traversal of this
tree will be A-B-D-E-C-F-G.

Postorder Traversal:

In this traversal method, the root is visited last, hence the name. First we traverse left sub
tree, then right sub tree and finally root. Consider the figure shown below. We start from A
and following the postorder traversal, we first visit left sub tree B. B is also traversed post
ordered and the process goes on until all the nodes are visited. The output of postorder
traversal of this tree will be D-E-B-F-G-C-A.
Binary Search Tree:
A binary search tree is a tree in which all nodes follows the below mentioned properties

 The left sub tree of a node has value less than or equal to its parent node’s value
 The right sub tree of a node has value greater than or equal to its parent node’s
value.

Thus, a binary search tree divides all its sub trees in to two segments (left sub tree and right
sub tree). An example of BST is shown below.

Operations:

 Search
 Insert
 Preorder Traversal
 Inorder Traversal
 Postorder Traversal

Re call the linked list, we have same nodes (represented by structures) in tree as well but
there is one more next pointer in tree node. Tree nodes have two next pointers named
leftChild and rightChild.
Example Code
////////////////////////////////////////////////////////////////////

#include <stdio.h>
#include <stdlib.h>

struct node {
int data;
struct node *leftChild;
struct node *rightChild;
};

struct node *root = NULL;

void insert(int data) {


struct node *tempNode = (struct node*) malloc(sizeof(struct node));
struct node *current;
struct node *parent;
tempNode->data = data;
tempNode->leftChild = NULL;
tempNode->rightChild = NULL;
//if tree is empty
if(root == NULL) {
root = tempNode;
}
else
{
current = root;
parent = NULL;

while(1) {
parent = current;
//go to left of the tree
if(data < parent->data) {
current = current->leftChild;

//insert to the left


if(current == NULL) {
parent->leftChild = tempNode;
return;
}
}
//go to right of the tree
else {
current = current->rightChild;

//insert to the right


if(current == NULL) { void inorder_traversal(struct node* root) {
parent->rightChild = tempNode; if(root != NULL) {
return; inorder_traversal(root->leftChild);
} printf("%d ",root->data);
} inorder_traversal(root->rightChild);
} }
} }
}
void post_order_traversal(struct node* root)
struct node* search(int data) { {
struct node *current = root; if(root != NULL) {
printf("Visiting elements: "); post_order_traversal(root->leftChild);
post_order_traversal(root->rightChild);
while(current->data != data) { printf("%d ", root->data);
if(current != NULL) }
printf("%d ",current->data); }
int main() {
//go to left tree int i;
if(current->data > data) { int array[7] = { 27, 14, 35, 10, 19, 31, 42 };
current = current->leftChild; for(i = 0; i < 7; i++)
} insert(array[i]);
//else go to right tree i = 31;
else { struct node * temp = search(i);
current = current->rightChild;
} if(temp != NULL) {
printf("[%d]Element found.",temp->data);
//not found printf("\n");
if(current == NULL) { }
return NULL; else
} {
} printf("[ x ] Element not found(%d).\n", i);
}
return current; i = 15;
} temp = search(i);
if(temp != NULL) {
void pre_order_traversal(struct node* printf("[%d Element found.", temp->data);
root) { printf("\n");
if(root != NULL) { }
printf("%d ",root->data); else
pre_order_traversal(root->leftChild); {
pre_order_traversal(root->rightChild); printf("[ x ] Element not found
} (%d).\n", i);
} }
printf("\nPreorder traversal: ");
pre_order_traversal(root);

printf("\nInorder traversal: ");


inorder_traversal(root);

printf("\nPost order traversal: ");


post_order_traversal(root);

return 0;
}
////////////////////////////////////////////////////////////////////
Output

////////////////////////////////////////////////////////////////
National University of Technology
Islamabad, Pakistan

Electrical Engineering Department

EE-2006 Data Structure and Algorithms Semester: V

EXPERIMENT NO.10:

Implementation of Searching Algorithms (Linear Search & Binary Search)

OBJECTIVE:

 Understand the concept of Searching Algorithms


 Implement Linear Search Algorithm in C
 Implementation of Binary Search in C

Date of Experiment: ________________

Submitted on: ________________

CMS: ________________

Obtained Marks:

Remarks:

Instructor’s Signature: ______________________________


1. Linear Search:

Linear search is a very simple search algorithm. In this type of search, a sequential
search is made over all items one by one. Every item is checked and if match founds
then that particular item is returned otherwise search continues till the end of the data
collection.

Algorithm
1. Start
2. Set i = 1;
3. If i > n then go to step 8
4. If A[i] = value then go to step 7
5. Set i = i + 1;
6. Go to step 3
7. Print Element value found at index i and go to step 9
8. Print Element not found
9. Stop

A code skeleton is written below and you have to write the linear search function by
yourself and then merge it in the program given below. After that execute the code and
write down the output of the program.

Example Code

/////////////////////////////////////////////////////////////////////
#include <stdio.h>
#define Max 10
int Array[Max] = {4,6,3,2,1,9,7,0,10,11};

int main () {
int location;
printf(“Input Array : ”);
display();
location = Search(10);
if(location != -1)
printf(“\n Element Found at location : %d”,(location+1));
else
printf(“Element Not Found”);
return 0;
}
////////////////////// Array Display Function ///////////////////////
Void display ()
{
int i;
printf(“ [ ”);

for (i=0 ; i<Max-1 ; i++)


{
printf(“%d”,Array[i]);
}
Printf(“ ] ”);
}
////////////////////// Linear Search Function (Lab Task) ///////////////////////////
int search(int data)
{

}
/////////////////////////////////////////////////////////////////////

Output

/////////////////////////////////////////////////////////////////////

2. Binary Search:

Binary search is a fast search algorithm with run time complexity of O (log n). Binary
search works on the principle of divide and conquer. For this algorithm to work properly
the data should be in sorted form. Binary search algorithm searches a particular item by
comparing the middle most item of data collection. If match occurs then index of item is
returned. If middle item is greater than item then item is searched in sub array to the
right of the middle item otherwise item will be searched in sub array to the left of the
middle item. This process continues on sub array as well until the size of sub array
reduces to zero.

Let we have a sorted array and we need to search the location of value 31.

Now, we will determine the half of the array by formula

Mid = (high - low)/2 // Mid = 0 + (9 - 0)/2 = 4.5 and after rounding Mid = 4

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

Now we change our low value to mid+1 and find new mid value again. Our new mid is 7
now. Now we compare the value stored at location 7 with our target value 31.

The value at location 7 is not a match, rather it is less that what we are looking for. So
the value must be in the lower part from this location.

So now we calculate the new mid and it will be 5.

We compare the value at location 5 with the target value and finally match is found.
Lab-Task: Write down the algorithm for binary search in the given box below.

Algorithm

Example Code

/////////////////////////////////////////////////////////////////////
#include <stdio.h>
#define Max 10
int Array[Max] = {4,6,3,2,1,9,7,0,10,11};

int main () {
int location;
printf(“Input Array : ”);
display();
location = Search(10);
if(location != -1)
printf(“\n Element Found at location : %d”,(location+1));
else
printf(“Element Not Found”);
return 0;
}
////////////////////// Array Display Function ///////////////////////
Void display ()
{
int i;
printf(“ [ ”);

for (i=0 ; i<Max-1 ; i++)


{
printf(“%d”,Array[i]);
}
Printf(“ ] ”);
}
////////////////////// Binary Search Function ///////////////////////////
int Search(int data)
{
int lower=0;
int upper=Max-1;
int mid = -1;
int comparison = 0;
int index = -1;

while(lower <= upper) {


printf(“Comparison %d\n”, (comparison+1));
printf(“Lower point : %d, Array[%d]=%d\n”,lower,lower,Array[lower]);
printf(“Upper point : %d, Array[%d]=%d\n”,upper,upper,Array[upper]);
comparison++;
mid = (upper – lower)/2;

if(Array[mid]==data)
{
index = mid;
break;
} else
{
If(Array[mid] < data) {
lower = mid + 1;
}
else
{
upper = mid - 1;
}
}
}
Printf(“Total Comparisons Made : %d”,comparison);
return index;
}
/////////////////////////////////////////////////////////////////////
National University of Technology
Islamabad, Pakistan

Electrical Engineering Department

EE-2006 Data Structure and Algorithms Semester: IV

EXPERIMENT NO.11:

Implementation of Sorting Algorithms-I (Bubble Sort, Insertion Sort, Selection Sort)

OBJECTIVE:

 Understand the concept of Sorting


 Understand the Sorting Algorithms
 Implementation of Bubble Sort Algorithm in C
 Implementation of Insertion Sort Algorithm in C
 Implementation of Selection Sort Algorithm in C

Date of Experiment: ________________

Submitted on: ________________

CMS: ________________

Obtained Marks:

Remarks:
Instructor’s Signature:
______________________________

Sorting refers to arranging data in a particular format. Sorting algorithm specifies the way to
arrange data in a particular order. Importance of sorting lies in the fact that data searching
can be optimized to a very high level if data is stored in a sorted manner. Sorting is also used
to represent the data in a more readable format. Some of the basic examples of sorting are

 Telephone Directory
 Dictionary

In-place and Not-in-place Sorting:


Sorting algorithms may require some extra space for comparison and temporary storage of
few data elements. Those algorithms which do not require any extra space and sorting is
said to be happened in-place or for example, with in the array itself. This is called in-place
sorting. But in some sorting algorithms, the program requires space which more than or
equal to the elements being sorted. Sorting which uses equal or more space are called not-
in-place sorting.

Stable and Not Stable Sorting:


If a sorting algorithm, after sorting the contents, does not change the sequence of similar
content in which they appear, it is called stable sorting.

If a sorting algorithm, after sorting the contents, changes the sequence of similar content in
which they appear, it is called unstable sorting.

Bubble Sort Algorithm:


Bubble sort is a simple sorting algorithm. This sorting algorithm is a comparison based
algorithm in which each pair of adjacent elements is compared and elements are swapped if
they are not in order. This algorithm is not suitable for large data sets as its average and
worst case complexity are of O(n2) where n is number of items. To understand how bubble
sort algorithm works, we take an unsorted array

Algorithm starts with very first two elements, comparing them to check which one is
greater, in this case value 33 is greater than 14, so it is already in sorted positions. Next two
values 33 and 27 will be compared, we find that 33 is greater than 27 so these two values
must be swapped and the new array will be

Then we will compare next two values 33 and 35 and we find that both are already at sorted
positions. Then we move to next two values 35 and 10. As 10 is smaller than 35 and these
two values will be swapped. We find that we reach at the end of the array. After first
iteration the array should look like

Notice that after each iteration, at least one value moves at the end and when there is no
swap required, bubble sort learns that array is completely sorted.

Algorithm
1. Start
2. For all elements of an Array
3. If Array[i] > Array[i+1]
4. Swap (Array[i] , Array [i+1])
5. End if
6. End for
7. Stop

Example Code

/////////////////////////////////////////////////////////////////////

#include <stdio.h>
#define Max 10

int Array[Max] = {1,8,4,6,0,3,5,2,7,9};

int main () {
printf(“Input Array :”);
display();
printf(“\n”);
Bubble_Sort();
Printf(“Output Array :”);
display();
return 0;
}
////////////////////// Array Display Function ///////////////////////
Void display ()
{
int i;
printf(“ [ ”);
for (i=0 ; i<Max-1 ; i++)
{
printf(“%d”,Array[i]);
}
Printf(“ ] ”);
}
////////////////////// Bubble Sort Function ///////////////////////
Void Bubble_Sort ()
{
int i,j;
int temp;

for(i=0 ; i < Max-1 ; i++)


{
for(j=0 ; j < Max-1-i ; j++)
{
Printf(“Items Compared : [%d %d]”,Array[j], Array[j+1]);
if(Array[j] > Array[j+1])
{
temp = Array[j];
Array[j] = Array[j+1];
Array[j+1] = temp;
Printf(“Swapped : [%d %d]”,Array[j], Array[j+1]);
} else
{
Printf(“ Not Swapped\n”);
}
}
Printf(“Iteration # = %d”,(i+1));
display();
}
}
/////////////////////////////////////////////////////////////////////

Insertion Sort:
In an insertion sort, a sub list is maintained which is always sorted. For example, the lower
part of an array is maintained to be sorted. A element which is to be inserted in the sorted
sub list, has to find the its appropriate place and insert it there. The array is searched
sequentially and unsorted items are moved and inserted in to sorted sub list (in the same
array). The algorithm is not suitable for large data sets as its worst case complexity are of
O(n2) where n are number of elements. We take an unsorted array for example

Insertion sort compares the first two elements. It finds that both 14 and 33 are already in
ascending order. For now, 14 is in sorted sub list.

Insertion sort moves ahead and compares 33 with 27 and finds that 33 is not on correction
position. 33 will be swapped with 27 and also it checks with all the elements of sorted sub
list. Here we see that sorted sub list has only one element 14 and 27 is greater than 14.
Hence sorted sub list remains sorted after swapping.

By now we have 14 and 27 in the sorted sub list. Next it compares 33 with 10 and it is found
that these values are not in sorted order so swap them.

After swapping 10 is added in the sorted sub list but in sub list 27 and 10 is not in the proper
order so 27 and 10 will swapped.
Again we find that 14 and 10 in unsorted order and we swap them. By end of the third
iteration we have a sorted sub list of 3 items.

This process goes until all the unsorted values are covered in sorted sub list.

Algorithm
1. Start
2. If it is the first element, it is already sorted. Return 1;
3. Pick next element
4. Compare with all elements in the sorted sub list
5. Find appropriate position
6. Insert the value
7. Repeat until list is sorted
8. Stop

Example Code

/////////////////////////////////////////////////////////////////////

#include <stdio.h>
#define Max 10
int Array[Max] = {1,8,4,6,0,3,5,2,7,9};

int main () {

printf(“Input Array :”);


display();
Insertion_Sort();
Printf(“Output Array :”);
display();
return 0;
}
////////////////////// Array Display Function ///////////////////////
Void display ()
{
int i;
printf(“ [ ”);
for (i=0 ; i<Max-1 ; i++)
{
printf(“%d”,Array[i]);
}
Printf(“ ] ”);
}
////////////////////// Insertion Sort Function ///////////////////////
Void Insertion_Sort ()
{
int i, value, position;

for(i=0 ; i < Max ; i++)


{
value = Array[i];
position = i;

while(position > 0 && Array[position-1] > value)


{
Array[position] = Array[position-1];
Position--;
Printf(“Item moved : %d\n”,Array[position]);
}
if(position != i) {
printf(“Item inserted : %d at position : %d\n”,value, position);
Array[position] = value;
}
Printf(“Iteration %d #”,i);
display();
}
}
/////////////////////////////////////////////////////////////////////

Selection Sort:

In selection sort, whole list is divided in to two parts, sorted part at left end and unsorted
part at right end. Initially sorted part is empty and unsorted part is entire list. Selection sort
algorithm first find the minimum value in the whole array and swapped with the left most
element (first element of the array). That element becomes part of sorted array and this
process continues moving unsorted array boundary by one element to the right. This
algorithm is not suitable for the large data sets as its worst case complexity is O(n2) where n
is the number of elements. We take an unsorted array for example

For the first position in sorted list, the whole array is scanned sequentially. We search the
whole array and find that 10 is the minimum value and it will be swapped with the value
which is on the first location of an array (value 14). After first iteration the array will be
For the second position where 33 is residing, we start scanning rest of the list in linear
manner. We find that 14 is second lowest value in an array and it should be at the second
place so we swap these values. After two iterations the new array will be

The same process will continue on the rest of the element in an array until the whole array
is sorted.

Algorithm
1. Start
2. Set Min to location 0
3. Search the Min element in the Array
4. Swap the value at location Min
5. Increment Min to point to next element
6. Until Array is sorted
7. Stop

Example Code

/////////////////////////////////////////////////////////////////////

#include <stdio.h>
#define Max 10
int Array[Max] = {1,8,4,6,0,3,5,2,7,9};

int main () {

printf(“Input Array :”);


display();
Selection_Sort();
Printf(“Output Array :”);
display();
return 0;
}
////////////////////// Array Display Function ///////////////////////
Void display ()
{
int i;
printf(“ [ ”);
for (i=0 ; i<Max-1 ; i++)
{
printf(“%d”,Array[i]);
}
Printf(“ ] ”);
}
////////////////////// Selection Sort Function ///////////////////////
Void Selection_Sort ()
{
int I,j ,Min;

for(i=0 ; i < Max-1 ; i++)


{
Min = i;
for(j=i+1; j<Max; j++ )
{
if(Array[j] < Array[Min])
{
Min = j;
}
}
if(Min != i)
{
Printf(“Items Swapped : [%d %d]\n”,Array[i],Array[Min]);

int temp = Array[Min];


Array[Min] = Array[i];
Array[i] = temp;
}
Printf(“iterations # = %d”,(i+1));
display();
}
}
/////////////////////////////////////////////////////////////////////

Lab Task:

1. What is difference between adaptive and non-adaptive sorting algorithms?

2. Bubble sort and insertion sort algorithms falls in which category of sorting? (in-
place,not-in-place,stable,unstable)
3. What is the purpose of sorting? (Real Life Example)
National University of Technology
Islamabad, Pakistan

Electrical Engineering Department

EE-2006 Data Structure and Algorithms Semester: V

EXPERIMENT NO.12 (Open Ended Lab-II):

OBJECTIVE:

Date of Experiment: ________________

Submitted on: ________________

CMS: ________________

Obtained Marks:

Remarks:

Instructor’s Signature: ______________________________


National University of Technology
Islamabad, Pakistan

Electrical Engineering Department

EE-2006 Data Structure and Algorithms Semester: V

EXPERIMENT NO.13:

Implementation of Sorting Algorithms-II (Merge Sort, Shell Sort, Quick Sort)

OBJECTIVE:

 Implementation of Merge Sort Algorithm in C


 Implementation of Shell Sort Algorithm in C
 Implementation of Quick Sort Algorithm in C

Date of Experiment: ________________

Submitted on: ________________

CMS: ________________

Obtained Marks:

Remarks:

Instructor’s Signature: ______________________________


Merge Sort:

Merge sort is a sorting technique based on divide and conquer. Its worst case complexity is
O(n log n). Merge sort first divides the array in to equal halves and then combines them in a
sorted manner. To understand merge sort, we take an unsorted array.

Merge sort divides the whole array in to equal halves unless the atomic values are achieved.
As we have an array of size 8, so merge sort first divides it in two arrays each of size 4.

This does not change the sequence of appearance of items in the original. Now we divide
these two arrays in to two halves.

We further divide these arrays and we achieve atomic value which can no more be divided.

Now, we combine them in exactly same manner they were broken down. We first compare
the element for each list and then combine them in to another list in sorted manner. We see
that 14 and 19 are in sorted positions. We compare 27 and 10 and in the target list of two
values we put 10 first, followed by 27. We change the order 19 and 35. 42 and 44 are placed
in order.

In next iteration of combining phase, we compare lists of two data values, and merge them
in to a list of found data values placing all in sorted order.

After the final merging the array will be


Algorithm
1. Start
2. If there is only one element in an array then it is already sorted, return.
3. Divide the list recursively in to two halves until it can no more be divided.
4. Merge the smaller arrays in to new array in sorted order
5. Stop

Example Code

/////////////////////////////////////////////////////////////////////
#include <stdio.h>
#define Max 10
int Array[Max] = {14,19,10,27,26,31,33,35,44,42};
int temp[Max];

int main () {
printf(“Input Array : ”);
display();
Sort(0,Max);
Printf(“Output Array : ”);
display();
return 0;
}
////////////////////// Array Display Function ///////////////////////
Void display ()
{
int i;
printf(“ [ ”);

for (i=0 ; i<Max-1 ; i++)


{
printf(“%d”,Array[i]);
}
Printf(“ ] ”);
}
////////////////////// Merging Function ///////////////////////////
Void merging(int low, int mid, int high)
{
Int i,i1,i2;
For(i1=low,i2=mid+1,i=low; i1 <= mid && i2 <= high; i++)
{
If(Array[i1] <= Array[i2])
temp[i] = Array[i1++];
else
temp[i] = Array[i2++];
}
While(i1 <= mid)
temp[i++] = Array[i1++];

While(i2 <= high)


temp[i++] = Array[i2++];

for(i=low ; i <= high ; i++)


Array[i] = temp[i];
}
////////////////////// Sort Function ///////////////////////////
void Sort(int low, int high)
{
Int mid;
If(low < high)
{
mid = (low+high)/2;
Sort(low,mid);
Sort(mid+1,high);
Merging(low,mid,high);
}
else
{
Return;
}
}
/////////////////////////////////////////////////////////////////////

Shell Sort:

Shell sort is highly efficient sorting algorithm and is based on insertion sort algorithm. This
algorithm avoids large shifts as in case of insertion sort if smaller value is very far right and
have to move to far left. This algorithm uses insertion sort on widely spread elements first to
sort them and then sorts the less widely spaced elements. The worst case complexity of
algorithm is O(n) and n is the number of elements. This spacing is termed as interval. This
interval is based on Knuth’s formula.

H=H∗3+1 Where H is interval with initial value 1

To understand the shell sort algorithm, we consider an unsorted array. For ease of
understand we take interval of 4 and we make the virtual sub list of all the values located at
the interval of 4 positions.
We compare the values in each sub list and swap them if needed in the original array. After
this step, the new array will be

Now at this stage we consider the interval value 2 and this will generate two sub lists.

We compare and swap the values if needed in the original array. After this the new array
will be

After that we will sort the rest of the array using interval value 1. The step by step depiction
is shown below.
Algorithm
1. Start
2. Initialize the value of H
3. Divide the array in to smaller sub arrays of equal interval H
4. Sort these sub arrays using insertion sort algorithm
5. Repeat until complete list is sorted
6. Stop

Example Code

/////////////////////////////////////////////////////////////////////
#include <stdio.h>
#define Max 7
int Array[Max] = {4,6,3,2,1,9,7};
int temp[Max];

int main () {
printf(“Input Array : ”);
display();
Shell();
Printf(“Output Array : ”);
display();
return 0;
}
////////////////////// Array Display Function ///////////////////////
Void display ()
{
int i;
printf(“ [ ”);

for (i=0 ; i<Max-1 ; i++)


{
printf(“%d”,Array[i]);
}
Printf(“ ] ”);
}
////////////////////// Shell Sort Function ///////////////////////////
Void Shell ()
{
Int inner, outer;
Int Value;
Int interval = 1;
Int elements = Max;
Int i = 0;

While(interval <= elements/3)


{
Interval = interval*3 + 1;
}

While( interval > 0 )


{

Printf(“Iterations %d #”,i);
display();

for(outer = interval ; outer < elements ; outer++)


{
Value = Array[outer];
Inner = outer;

While(inner > interval-1 && Array[inner-interval] > value)


{
Array[inner] = Array[inner - interval];
Inner -= interval;
Printf(“Item moved : %d \n”, Array[inner]);
}
Array[inner] = Value;
Printf(“Item inserted : %d”, at position : %d\n”,Value,inner);
}
interval = (interval – 1)/3
i++;
}
}
/////////////////////////////////////////////////////////////////////

Quick Sort:

Quick sort is a highly efficient sorting algorithm and is based on partitioning of array of data
in to smaller arrays. A large array is partitioned in to two arrays one of which holds values
smaller than specified value say pivot based on which the partition is made and another
array holds values greater than pivot value. The quick sort partitions an array and them calls
itself recursively twice to sort the resulting two sub array. This algorithm is quite efficient for
large data sets as its worst case complexity are of O (n log n) where n is the number of
elements. The Example of Quick sort is shown below and first element (54) is chosen as a
pivot.

Algorithm
1. Start
2. Choose pivot from median(First, Mid, Last) or [Highest index value
recommended]
3. Take two variables to point left and right
4. Left points to the low index
5. Right points to the high index
6. While value at left is less than the pivot move right
7. While value at right is greater than the pivot move left
8. If both step 6 and step 7 does not match swap left and right
9. If left >= right, the point where they met is new pivot
10. Recursively sort the left and right part of the pivot
11. Stop

Example Code

/////////////////////////////////////////////////////////////////////
#include <stdio.h>
#define Max 7
int Array[Max] = {4,6,3,2,1,9,7};

int main () {
printf(“Input Array : ”);
display();
Quicksort(0,Max-1);
Printf(“Output Array : ”);
display();
return 0;
}
////////////////////// Array Display Function ///////////////////////
Void display ()
{
int i;
printf(“ [ ”);

for (i=0 ; i<Max-1 ; i++)


{
printf(“%d”,Array[i]);
}
Printf(“ ] ”);
}
////////////////////// Swapping Function ///////////////////////////
Void Swap(int num1, int num2)
{
Int temp = Array[num1];
Array[num1] = Array[num2];
Array[num2] = temp;
}
////////////////////// Partition Function ///////////////////////////
int partition(int left, int right, int pivot)
{
int leftpointer = left-1;
int rightpointer = right;

while(true)
{
While(array[++leftpointer]<pivot) {
}
While(rightpointer > 0 && Array[--rightpointer] > pivot) {
}
If(leftpointer >= rightpointer)
{
Break;
}
Else
{
Printf(“Item Swapped : %d,%d\n”, Array[leftpointer],Array[rightpointer]);
swap(leftpointer,rightpointer);
}
}
Printf(“Pivot Swapped : %d,%d\n”,Array[leftpointer],Array[right]);
swap(leftpointer,right);
printf(“Updated Array : ”);
display();
return leftpointer;
}
////////////////////// Quick Sort Function ///////////////////////////
Void Quicksort(int left, int right)
{
If(right-left <= 0)
{
Return;
}
Else
{
Int pivot = Array[right];
Int partitionpoint = partition(left,right,pivot);
Quicksort(left,partitionpoint-1);
Quicksort(partitionpoint+1,right);
}
}
/////////////////////////////////////////////////////////////////////
Lab Task:

Write down the best, average and worst case complexity in the table below for sorting
algorithms mentioned in the table.

Sorting Algorithm Best Average Worst


Bubble Sort
Insertion Sort
Selection Sort
Merge Sort
Shell Sort
Quick Sort

National University of Technology


Islamabad, Pakistan

Electrical Engineering Department

EE-2006 Data Structure and Algorithms Semester: V

EXPERIMENT NO.14:

Implementation of Graph Data Structure

OBJECTIVE:

 Understand the concept of Graph Data Structure


 Understand the concept of Graph Traversal
 Implementation of depth first traversal
 Implementation of breadth first traversal

Date of Experiment: ________________

Submitted on: ________________

CMS: ________________
Obtained Marks:

Remarks:

Instructor’s Signature: ______________________________

A graph is a visual representation of a set of objects where some pairs of objects are
connected by links. The interconnected objects are represented by points termed as
vertices, and the links that connect the vertices are called edges. A graph is a pair of sets
(V,E), where V is the set of vertices and E is the set of edges connecting the pairs of vertices.
Take a look at the following graph shown below

By examine the above graph we will get

V = {a,b,c,d,e} E = {ab,ac,cd,bd,de}

Mathematical graphs can be represented in data structure. We can represent a graph using
an array of vertices and a two dimensional array of edges. In graph data structure some
important terms are

 Vertex  Each node of the graph is represented as a vertex. In the figure given
below labeled circle represents vertices (A to G).
 Edge  Edge represents a path between two vertices or a line between two
vertices. In the figure given below, lines from A to B, B to C are
edges.
 Adjacency  Two nodes or vertices are adjacent if they are connected to each
other through an edge. In the figure given below B is
adjacent to A.
 Path  Path represents a sequence of edges between two vertices. In figure
given below ABCD represents a path from A to D.
Basic Operations:

 Add Vertex
 Add Edge
 Display Vertex

There are two ways to traverse the graph

 Depth First Traversal


 Breadth First Traversal

Depth First Traversal:


This method traverses a graph in a depthward motion and uses a stack to remember to get
the next vertex to start a search when a dead end occurs in any iteration.

Consider the above graph, DFS algorithm traverses from A to B to C to D first then to E, then
to F and at last to G. it employs following rules.

 Visit adjacent unvisited vertex. Mark it visited, display it and also push it in a stack.
 If no adjacent vertex found, pop up a vertex from stack. It will pop up all the vertices
from the stack which do not have adjacent vertices.
 Repeat rule 1 and rule 2 until stack is empty.
Example Code
////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX 5

struct Vertex { //add edge to edge array


char label; void addEdge(int start,int end) {
bool visited; adjMatrix[start][end] = 1;
}; adjMatrix[end][start] = 1;
}
//stack variables
//display the vertex
int stack[MAX]; void displayVertex(int vertexIndex) {
int top = -1; printf("%c ",lstVertices[vertexIndex]->label);
//graph variables }
//array of vertices
struct Vertex* lstVertices[MAX]; //get the adjacent unvisited vertex
int getAdjUnvisitedVertex(int vertexIndex) {
//adjacency matrix int i;
int adjMatrix[MAX][MAX];
for(i = 0; i<vertexCount; i++) {
//vertex count if(adjMatrix[vertexIndex][i] == 1 &&
int vertexCount = 0; lstVertices[i]->visited == false) {
return i;
//stack functions }
}
void push(int item) {
stack[++top] = item; return -1;
} }

int pop() { void depthFirstSearch() {


return stack[top--]; int i;
}
//mark first node as visited
int peek() { lstVertices[0]->visited = true;
return stack[top];
} //display the vertex
displayVertex(0);
bool isStackEmpty() {
return top == -1; //push vertex index in stack
} push(0);

//graph functions while(!isStackEmpty()) {


//get the unvisited vertex of vertex which is
//add vertex to the vertex list at top of the stack
void addVertex(char label) { int unvisitedVertex =
struct Vertex* vertex = (struct Vertex*) getAdjUnvisitedVertex(peek());
malloc(sizeof(struct Vertex));
vertex->label = label; //no adjacent vertex found
vertex->visited = false; if(unvisitedVertex == -1) {
lstVertices[vertexCount++] = vertex; pop();
} }else {
lstVertices[unvisitedVertex]->visited = true;
displayVertex(unvisitedVertex); //stack is empty, search is complete, reset the
push(unvisitedVertex); visited flag
} for(i = 0;i < vertexCount;i++) {
}

lstVertices[i]->visited = false;
}
}
int main() {
int i, j;
for(i = 0; i<MAX; i++) // set adjacency {
for(j = 0; j<MAX; j++) // matrix to 0
adjMatrix[i][j] = 0;
}
addVertex('S'); // 0
addVertex('A'); // 1
addVertex('B'); // 2
addVertex('C'); // 3
addVertex('D'); // 4

addEdge(0, 1); // S - A
addEdge(0, 2); // S - B
addEdge(0, 3); // S - C
addEdge(1, 4); // A - D
addEdge(2, 4); // B - D
addEdge(3, 4); // C - D

printf("Depth First Search: ");


depthFirstSearch();
return 0;
}
////////////////////////////////////////////////////////////////////
Output:
////////////////////////////////////////////////////////////////////

Breadth First Traversal:


This method traverses a graph in a breadthwards motion and uses a queue to remember to
get the next vertex to start a search when a dead end occurs in any iteration.
In the figure given above, BFS algorithm traverses from A-B-E-F-C-G-D. It employs following
rules.

 Visit adjacent unvisited vertex. Mark it visited, display it and insert it in a queue.
 If no adjacent vertex found, remove the first vertex from queue.
 Repeat 1 and 2 until queue is empty.
Example Code
////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#define MAX 5

struct Vertex {
char label;
bool visited;
};

//queue variables
int queue[MAX];
int rear = -1;
int front = 0;
int queueItemCount = 0;

//graph variables
//array of vertices
struct Vertex* lstVertices[MAX];

//adjacency matrix
int adjMatrix[MAX][MAX];

//vertex count
int vertexCount = 0;

//queue functions
void insert(int data) { }
queue[++rear] = data;
queueItemCount++; //get the adjacent unvisited vertex
} int getAdjUnvisitedVertex(int vertexIndex) {
int i;
int removeData() {
queueItemCount--; for(i = 0; i<vertexCount; i++) {
return queue[front++]; if(adjMatrix[vertexIndex][i] == 1 &&
} lstVertices[i]->visited == false)
return i;
bool isQueueEmpty() { }
return queueItemCount == 0;
} return -1;
}
//graph functions
void breadthFirstSearch() {
//add vertex to the vertex list int i;
void addVertex(char label) {
struct Vertex* vertex = (struct Vertex*) //mark first node as visited
malloc(sizeof(struct Vertex)); lstVertices[0]->visited = true;
vertex->label = label;
vertex->visited = false; //display the vertex
lstVertices[vertexCount++] = vertex; displayVertex(0);
}
//insert vertex index in queue
//add edge to edge array insert(0);
void addEdge(int start,int end) { int unvisitedVertex;
adjMatrix[start][end] = 1;
adjMatrix[end][start] = 1; while(!isQueueEmpty()) {
} //get the unvisited vertex of vertex which
is at front of the queue
//display the vertex int tempVertex = removeData();
void displayVertex(int vertexIndex) {
printf("%c ",lstVertices[vertexIndex]->label); //no adjacent vertex found
while((unvisitedVertex =
getAdjUnvisitedVertex(tempVertex)) != -1) {
lstVertices[unvisitedVertex]->visited =
true;
displayVertex(unvisitedVertex);
insert(unvisitedVertex);
}
}
//queue is empty, search is complete,
reset //the visited flag
for(i = 0;i<vertexCount;i++) {
lstVertices[i]->visited = false;
}
}
int main() {
int i, j;
for(i = 0; i<MAX; i++) // set adjacency {
for(j = 0; j<MAX; j++) // matrix to 0
adjMatrix[i][j] = 0;
}
addVertex('S'); // 0
addVertex('A'); // 1
addVertex('B'); // 2
addVertex('C'); // 3
addVertex('D'); // 4

addEdge(0, 1); // S - A
addEdge(0, 2); // S - B
addEdge(0, 3); // S - C
addEdge(1, 4); // A - D
addEdge(2, 4); // B - D
addEdge(3, 4); // C - D
printf("\nBreadth First Search: ");
breadthFirstSearch();
return 0;

You might also like