Cspl302 Data Structure and Algorithms Lab
Cspl302 Data Structure and Algorithms Lab
Cspl302 Data Structure and Algorithms Lab
LTPC
0042
Course Pre-requisite:
Course Objective:
• To enable students write programs using various data structures, analyse and understand the
benefits of choosing the right data structure.
Course Outcomes:
LIST OF EXPERIMENTS
1. Searching Algorithms (With the Number of Key Comparisons) - Sequential, Binary and Fibonacci
Search Algorithms on an Ordered List
2. Sorting Algorithms: Insertion Sort, Selection Sort, Bubble Sort, Quick Sort, Heap Sort and Merge
Sort.
4. Application of Stack for Converting an Arithmetic Expression into Postfix Form and Evaluation of
Postfix Expression.
5. Implementation of Queue, Circular Queue, Priority Queue, Dequeue and Their Operations.
6. Implementation of Singly Linked List, Doubly Linked List, Circular Linked List.
1
Ex. No:1 Searching Algorithms (With the Number of Key Comparisons) - Sequential, Binary
Date: and Fibonacci Search Algorithms on an Ordered List
Algorithm:
1. Start
5. Assign 0 to found
7. If Ai = search then
found = 1
Print position i
Stop
8. If found = 0 then
Stop
Program
#include <stdio.h>
#include <conio.h>
main()
clrscr();
scanf("%d", &n);
2
for(i=0; i<n; i++)
scanf("%d", &a[i]);
scanf("%d", &val);
found = 0;
if (a[i] == val)
found = 1;
break;
if (found == 0)
getch();
Output
23 6 12 5 0 32 10
Result
3
1b.Binary Search
Algorithm
1. Start
i. Print mid
ii. Stop
i. lower = mid + 1
d. else
i. upper = mid – 1
8. Stop
Program
#include <stdio.h>
void main()
scanf("%d", &n);
a[i] = 2 * i;
4
printf("%4d", a[i]);
scanf("%d", &val);
upper = n;
lower = 0;
found = -1;
att++;
if (a[mid] == val)
found = 1;
break;
upper = mid - 1;
else
lower = mid + 1;
if (found == -1)
Output
0 2 4 6 8 10 12 14 16 18
5
1c.Fibonacci Search
Algorithm:
1. Input a sorted array A[i] with n numbers and target element which we want to search for.
2. Start by generating a series of Fibonacci numbers until you find a number that is greater
3. If F(k) = 0, then stop and print the message as element not found.
6. Compare
k = k-1, offset = i,
Program:
#include <stdio.h>
return (a > b) ? b : a;
int Fm2 = 0;
int Fm1 = 1;
6
Fm2 = Fm1;
Fm1 = Fm;
Fm = Fm2 + Fm1;
Fm = Fm1;
Fm1 = Fm2;
Fm2 = Fm - Fm1;
offset = i;
Fm = Fm2;
Fm2 = Fm - Fm1;
} else
return i;
return offset + 1;
return -1;
int main(){
int arr[10] = {6, 11, 19, 24, 33, 54, 67, 81, 94, 99};
n = 10;
7
key = 67;
if(pos >= 0)
else
printf("\nUnsuccessful Search");
OUTPUT:
8
Ex.No.2 Sorting Algorithms: Insertion Sort, Selection Sort, Bubble Sort, Quick Sort, Heap
Sort and Merge Sort.
Algorithm
1. Start
9. Stop
Program
/* Insertion Sort */
void main()
scanf("%d",&n);
scanf("%d", &a[i]);
temp = a[i];
j = i - 1;
a[j+1] = a[j];
9
j = j - 1;
a[j+1] = temp;
p++;
Output
After Pass 1: 8 34 64 51 32 21
After Pass 2: 8 34 64 51 32 21
After Pass 3: 8 34 51 64 32 21
After Pass 4: 8 32 34 51 64 21
After Pass 5: 8 21 32 34 51 64
Sorted List : 8 21 32 34 51 64
10
2b.Selection Sort
Aim: Arrange the list of numbers in ascending order using Selection Sort.
Algorithm:
begin:
begin:
position = i
begin:
position = j
end if
end
swap(array[position], a[i])
end
end
Program
#include <stdio.h>
#include <conio.h>
void main()
scanf("%d", &num);
scanf("%d", &arr[i]);
11
}
pos = i;
pos = j;
if(pos != i)
temp = arr[i];
arr[i] = arr[pos];
arr[pos] = temp;
getch();
Output:
12
2c.bubble Sort
Algorithm
1. Start
5. Stop
Program
#include <stdio.h>
main()
scanf("%d", &n);
scanf("%d", &a[i]);
t = a[j];
13
a[j] = a[j+1];
a[j+1] = t;
p++;
Output
Enter 8 elements: 8 6 10 3 1 2 5 4
After Pass 1 : 6 8 3 1 2 5 4 10
After Pass 2 : 6 3 1 2 5 4 8 10
After Pass 3 : 3 1 2 5 4 6 8 10
After Pass 4 : 1 2 3 4 5 6 8 10
After Pass 5 : 1 2 3 4 5 6 8 10
After Pass 6 : 1 2 3 4 5 6 8 10
After Pass 7 : 1 2 3 4 5 6 8 10
Sorted List : 1 2 3 4 5 6 8 10
Result
14
2d. Quick sort
Algorithm
1. Start
8. Stop
Program
#include<stdio.h>
#include<conio.h>
main()
int arr[30];
int i, size;
scanf("%d", &size);
scanf("%d", &arr[i]);
qsort(arr,0,size-1);
printf("%d\t", arr[i]);
getch();
15
void qsort(int arr[20], int fst, int last)
pivot = fst;
i = fst;
j = last;
while(i < j)
i++
while(arr[j]>arr[pivot])
j—
if(i<j)
tmp=arr[i];
arr[i]=arr[j]
arr[j]=tmp
tmp=arr[pivot];
arr[pivot]=arr[j];
arr[j]=tmp
qsort(arr,fst,j-1)
qsort(arr,j+1,last)
16
Output
127
-1
04
-2
-2 -1 0 1 2 3 4 7
Result
Thus the array was sorted using quick sort‟s divide and conquers method.
17
2e. Heap sort
Algorithm:
1. Build Max Heap: Create a max heap by visualizing all the elements of the array in a binary
tree. This process ensures that the largest element is at the root of the heap.
2. Repeat the following steps until the heap contains only one element:
i. Swap: Remove the root element and put it at the end of the array (nth position). Put
the last item of the tree (heap) in the vacant place.
ii. Remove: Reduce the size of the heap by 1.
iii. Heapify: Heapify the root element again so that we have the highest element at the
root.
3. Obtain Sorted Array: The sorted array is obtained by reversing the order of the elements in
the input array
Program:
#include <iostream>
int j, temp;
temp = a[i];
j = 2*i;
while (j <= n)
j = j+1;
break;
a[j/2] = a[j];
j = 2*j;
18
}
a[j/2] = temp;
return;
int i, temp;
temp = a[i];
a[i] = a[1];
a[1] = temp;
MaxHeapify(a, 1, i - 1);
int i;
MaxHeapify(a, i, n);
int main()
int n, i;
cin>>n;
n++;
int arr[n];
19
for(i = 1; i < n; i++)
cin>>arr[i];
Build_MaxHeap(arr, n-1);
HeapSort(arr, n-1);
cout<<"->"<<arr[i];
return 0;
Expected Output:
Enter element 1: 4
Enter element 2: 2
Enter element 3: 1
Enter element 4: 5
Enter element 5: 0
20
2f. Merge sort
Algorithm
1. Start
9. Stop
Program
#include <stdio.h>
#include <conio.h>
int size;
main()
int i, arr[30];
scanf("%d", &size);
scanf("%d", &arr[i]);
part(arr, 0, size-1);
printf("%d ",arr[i]);
21
getch();
int mid;
if (max-min == (size/2)-1)
int tmp[30];
int i, j, k, m;
j = min;
m = mid + 1;
tmp[i] = arr[j];
j++;
22
}
else
tmp[i] = arr[m];
m++;
tmp[i] = arr[k];
i++;
else
tmp[i] = arr[k];
i++;
arr[k] = tmp[k];
Output
23
Merge sorted list : 1 2 13 15 24 26 27 38
Result
Thus array elements was sorted using merge sort's divide and conquer method.
24
Ex.No.3 Implementation of Stack and Its Operations.
Date:
Algorithm :
Step 5. The stack represented by linked list is traversed to display its content.
PROGRAM:
#include<stdio.h>
#include<conio.h>
#define SIZE 5
int stack[SIZE],top=-1;
void push();
25
void pop();
void display();
void main()
int choice;
int isempty();
int length();
clrscr();
while(1)
printf(“\n 1.Push”);
printf(“\n 2. POP”);
printf(“\n 3.Display”);
printf(“\n 5.Quit”);
scanf(“\n %d”,&choice);
switch(choice)
case 1: push();
break;
case 2: pop();
break;
case 3: display();
break;
break;
case 5: exit(0);
break;
26
}
void push()
int n;
if(top==SIZE-1)
else
scanf(“%d”,&n);
top++;
stack[top]=n;
void pop()
int n;
if(isempty())
printf(“\nStack is empty”);
top=-1;
else
n=stack[top];
--top;
27
}
void display()
int i,temp=top;
if(isempty())
return;
for(i=temp;i>=0;i--)
printf(“%d \n”,stack[i]);
int isempty()
return (top==-1);
int length()
return (top+1);
Output:
1.Push
2. POP
3.Display
4. Length
5.Quit
28
1.Push
2. POP
3.Display
4. Length
5.Quit
1.Push
2. POP
3.Display
4. Length
5.Quit
1.Push
2. POP
3.Display
4. Length
5.Quit
1.Push
2. POP
3.Display
4. Length
5.Quit
40
30
20
29
10
1.Push
2. POP
3.Display
4. Length
5.Quit
1.Push
2. POP
3.Display
4. Length
5.Quit
1.Push
2. POP
3.Display
4. Length
5.Quit
Result: Thus the above program was executed successfully and verified.
30
Ex.no: 4
4a.
Aim: To convert infix expression to its postfix form using stack operations.
Algorithm
1. Start
3. Initialize top = -1
6. If character is an operator
8. If the stack [top] operator has higher or equal priority than the inputoperator,
9. Else
12. If the character is a right parenthesis, pop all the operators from the stack andprint it
Program
#include <stdio.h>
#include <conio.h>
#include <string.h>
#define MAX 20
char stack[MAX];
char pop();
31
switch(symbol)
case '+':
case '-':
return 2;
break;
case '*':
case '/':
return 4;
break;
case '^':
case '$':
return 6;
break;
case '(':
case ')':
case '#':
return 1;
break;
switch(symbol)
case '+':
case '-':
case '*':
case '/':
case '^':
case '$':
32
case '(':
case ')':
return 1;
break;
default:
return 0;
int i,symbol,j = 0;
stack[++top] = '#';
for(i=0;i<strlen(infix);i++)
symbol = infix[i];
if(isoperator(symbol) == 0)
else
postfix[j] = symbol;
j++;
if(symbol == '(')
push(symbol);
while(stack[top] != '(')
postfix[j] = pop();
j++;
33
pop(); //pop out (.
Else
push(symbol);
else
postfix[j] = pop();
j++;
push(symbol);
while(stack[top] != '#')
postfix[j] = pop();
j++;
postfix[j] = '\0';
main()
char infix[20],postfix[20];
clrscr();
gets(infix);
34
convertip(infix, postfix);
puts(postfix);
getch();
top++;
stack[top] = item;
char pop()
char a;
a = stack[top];
top--;
return a;
Output
Result: Thus the given infix expression was converted into postfix form using stack
35
4b.
Algorithm
1. Start
3. Initialize top = -1
6. If character is an operator
8. Apply operator on the elements and push the result onto the stack,
Program
#include <stdio.h>
#include <conio.h>
struct stack
}s;
main()
int top;
float a[50];
char pf[50];
float d1,d2,d3;
int i;
clrscr();
s.top = -1;
gets(pf);
36
for(i=0; pf[i]!='\0'; i++)
switch(pf[i])
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
s.a[++s.top] = pf[i]-'0';
break;
case '+':
d1 = s.a[s.top--];
d2 = s.a[s.top--];
s.a[++s.top] = d1 + d2;
break;
case '-':
d2 = s.a[s.top--];
d1 = s.a[s.top--];
s.a[++s.top] = d1 - d2;
break;
case '*':
d2 = s.a[s.top--];
d1 = s.a[s.top--];
s.a[++s.top] = d1*d2;
break;
37
case '/':
d2 = s.a[s.top--];
d1 = s.a[s.top--];
s.a[++s.top] = d1 / d2;
break;
getch();
Output
Result: Thus the given postfix expression was evaluated using stack.
38
Ex.No: 7
Aim: Implementation of BinaryTree and Binary Tree Traversal techniques (in order, pre
Description :
Trees: A tree is a nonlinear hierarchical data structure that consists of nodes connected by
edges.
Node : A node is an entity that contains a key or value and pointers to its child nodes.
The last nodes of each path are called leaf nodes or external nodes that do not contain a
link/pointer to child nodes.The node having at least a child node is called an internal node.
Height of a Node :The height of a node is the number of edges from the node to the deepest
leaf (ie. the longest path from the node to a leaf node).
Depth of a Node :The depth of a node is the number of edges from the root to the node.
Height of a Tree:The height of a Tree is the height of the root node or the depth of the
deepest node.
A) Binary Tree
#include<stdio.h>
#include<stdlib.h>
EleType data;
}BiTNode,*BiTree;
EleType data;
39
scanf("%c",&data);
if('#' == data)
*T = nullptr;
else{
(*T) = (BiTree)malloc(sizeof(BiTNode));
if(!(*T)){
exit(-1);
(*T)->data = data;
return true;
printf("%c",data);
if(T == nullptr)
return false;
visite(T->data);
proOrderTraverse(T->lchild);
proOrderTraverse(T->rchild);
return true;
if(T == nullptr)
return false;
inOrderTraverse(T->lchild);
40
visite(T->data);
inOrderTraverse(T->rchild);
return true;
if(T == nullptr)
return false;
postOrderTraverse(T->lchild);
postOrderTraverse(T->rchild );
visite(T->data);
return true;
int main(){
BiTree T;
createBitTree(&T);
proOrderTraverse(T);
printf("\n");
inOrderTraverse(T);
printf("\n");
postOrderTraverse(T);
getchar();
return 0;
Expected Output:
ABC##DE#G##F###
ABCDEGF
CBEGDFA
CGEFDBA
41
Ex.No: 8
Algorithm
Program
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX 5
struct Vertex {
char label;
bool visited;
};
//queue variables
int queue[MAX];
int front = 0;
int queueItemCount = 0;
//graph variables
//array of vertices
//adjacency matrix
int adjMatrix[MAX][MAX];
//vertex count
int vertexCount = 0;
//queue functions
queue[++rear] = data;
queueItemCount++;
int removeData() {
42
queueItemCount--;
return queue[front++];
bool isQueueEmpty() {
return queueItemCount == 0;
//graph functions
vertex->label = label;
vertex->visited = false;
lstVertices[vertexCount++] = vertex;
adjMatrix[start][end] = 1;
adjMatrix[end][start] = 1;
printf("%c ",lstVertices[vertexIndex]->label);
int i;
return i;
return -1;
43
}
void breadthFirstSearch() {
int i;
lstVertices[0]->visited = true;
displayVertex(0);
insert(0);
int unvisitedVertex;
while(!isQueueEmpty()) {
lstVertices[unvisitedVertex]->visited = true;
displayVertex(unvisitedVertex);
insert(unvisitedVertex);
for(i = 0;i<vertexCount;i++) {
lstVertices[i]->visited = false;
int main() {
int i, j;
adjMatrix[i][j] = 0;
44
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
breadthFirstSearch();
return 0;
Output
Result : Thus the graph using breadth first search traversal was demonstrated.
45
Aim To implement Depth first graph traversal.
Algorithm
Program
#include<stdio.h>
void DFS(int);
void main()
int i,j;
scanf("%d",&n);
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
let S be stack
S.push( s )
mark s as visited.
//Inserting s in stack
v = S.top( )
S.pop( )
if w is not visited :
S.push( w )
mark w as visited
46
DFS-recursive(G, s):
mark s as visited
for(i=0;i <n;i++)
visited[i]=0
DFS(0);
Void DSF(int i)
Int j;
Printf(“%d”,i)
Visited[i]=1;
For(j=0;j<n;j++)
If(!visited[j]&&g[i][j]==1)
DFS(j);
Output:
47
Result : Thus the graph using depth first search traversal was demonstrated.
Aim:
Algorithm :
Step1:Define a C-struct for each node in the stack. Each node in the stack
contains data and link to the next node. TOP pointer points to last
48
Step 4: POP DATA FROM STACK
Step 5. The stack represented by linked list is traversed to display its content.
PROGRAM:
# include<stdio.h>
# include<conio.h>
struct node
int info;
} *top=NULL;
main()
49
{
int choice;
while(1)
{ printf("1.Push\n");
printf("2.Pop\n");
printf("3.Display\n");
printf("4.Quit\n");
scanf("%d", &choice);
switch(choice)
case 1:
push();
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
exit(1);
default :
printf("Wrong choice\n");
}/*End of switch */
}/*End of while */
}/*End of main() */
push()
50
struct node *tmp;
int pushed_item;
scanf("%d",&pushed_item);
tmp->info=pushed_item;
tmp->link=top;
top=tmp;
}/*End of push()*/
pop()
if(top == NULL)
printf("Stack is empty\n");
else
{ tmp=top;
top=top->link;
free(tmp);
}/*End of pop()*/
display()
ptr=top;
if(top==NULL)
printf("Stack is empty\n");
else
51
printf("Stack elements :\n");
while(ptr!= NULL)
printf("%d\n",ptr->info);
ptr = ptr->link;
}/*End of while */
}/*End of else*/
}/*End of display()*/
Output:
1.Push
2. POP
3.Display
5.Quit
52
1.Push
2. POP
3.Display
5.Quit
1.Push
2. POP
3.Display
5.Quit
1.Push
2. POP
3.Display
5.Quit
1.Push
2. POP
3.Display
5.Quit
53
Enter the choice: 3
40
30
20
10
1.Push
2. POP
3.Display
5.Quit
1.Push
2. POP
3.Display
5.Quit
54