Professional Documents
Culture Documents
LAB MANUAL
DATA STRUCTURES AND ANALYSIS OF ALGORITHMS
SPRING-2K19
Qasim Niaz
Lecturer
Objective:
In order to develop efficient software systems, it is essential that efficient algorithms and
appropriate data structures are used. This course will help the students to develop efficient
data structures and algorithms in a systematic manner. The students are advised to follow the
following steps for each experiment.
1. Problem definition
2. Algorithm Design
3. Program development either in C or C++ language 4. Execution of the program
List of Experiments
IV. Finding the maximum element in an array, Insert an element at any position in
array, Delete an element at any position in array.
Page 3
LAB 01
LAB Task
Review the programming fundamentals Lab Manual
LAB 02 LAB Task Task # 01: Recursive Function of
Factorial.
Solution
#include<iostream>
using namespace std;
int fact(int n)
{if((n==0)||(n==1))
return 1;
else
return n*fact(n-1);
}
int main()
{
int n;
cout<<"Enter value of for Factorial";
cin>>n;
cout<<"Factorial of "<<n<<" is "<<fact(n);
return 0;
}
Page 5
Lab # 02
Assignment # 02
Lab # 03
LAB Task
Task#01: Write a Program to implement the linear search Algorithm?
#include <iostream>
int main(void)
{
int arr[] = { 2, 3, 4, 10, 40 };
int x = 10;
int n = sizeof(arr) / sizeof(arr[0]);
int result = search(arr, n, x);
(result == -1)?
return 0; }
Task#02: Write a program to implement the binary search algorithm using recursive &
non-recursive functions? #include <stdio.h>
#define MAX_LEN 10
/* Non-Recursive function*/
void b_search_nonrecursive(int l[],int num,int ele)
{
int l1,i,j, flag = 0;
l1 = 0; i = num-1;
while(l1 <= i)
{
j = (l1+i)/2;
if( l[j] == ele)
{
Page 6
printf("\nThe element %d is present at position %d in list\n",ele,j);
flag =1; break; } else if(l[j] < ele) l1 = j+1;
else i = j-1;
}
if( flag == 0)
printf("\nThe element %d is not present in the list\n",ele);
}
/* Recursive function*/
int b_search_recursive(int l[],int arrayStart,int arrayEnd,int a)
{ int
m,pos;
if (arrayStart<=arrayEnd)
{
m=(arrayStart+arrayEnd)/2;
if (l[m]==a)
return m; else
if (a<l[m])
return b_search_recursive(l,arrayStart,m-1,a);
else
return b_search_recursive(l,m+1,arrayEnd,a);
} return
-1;
}
void read_list(int l[],int n)
{
int i;
printf("\nEnter the elements:\n");
for(i=0;i<n;i++)
scanf("%d",&l[i]);
}
void print_list(int l[],int n)
{
int i;
for(i=0;i<n;i++) printf("%d\
t",l[i]);
}
/*main function*/
main() {
int l[MAX_LEN], num, ele,f,l1,a;
int ch,pos;
clrscr();
printf("======================================================");
printf("\n\t\t\tMENU");
printf("\n=====================================================");
printf("\n[1] Binary Search using Recursion method"); printf("\
n[2] Binary Search using Non-Recursion method");
Department of Computer Science
Institute of Southern Punjab, Multan
Page 7
printf("\n\nEnter your Choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("\nRecursive method:\n");
pos=b_search_recursive(l,0,num,ele);
if(pos==-1)
{
printf("Element is not found");
}
else
{
printf("Element is found at %d position",pos);
}
//getch();
break;
Task#3: Write a program to implement the Selection sort on the given list?
#include <bits/stdc++.h>
using namespace std;
Page 8
}
void selectionSort(int arr[], int n)
{
int i, j, min_idx;
for (i = 0; i < n-1; i++)
{
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
swap(&arr[min_idx], &arr[i]);
}
}
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
cout << arr[i] << " "; cout
<< endl;
} int
main()
{
int size;
cin>>size;
int arr[size];
for(int i =0;i<size;i++)
{
cin>>arr[i];
}
selectionSort(arr, size);
cout << "Sorted array: \n";
printArray(arr, size);
return 0;
}
Task # 04: Write a program to implement the insertion sort?
#include <bits/stdc++.h>
using namespace std;
/* Function to sort an array using insertion sort*/
void insertionSort(int arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i - 1;
Page 9
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
// A utility function to print an array of size n
void printArray(int arr[], int n)
{
int i;
for (i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
}
/* Driver code */
int main()
{
int arr[] = { 12, 11, 13, 5, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
insertionSort(arr, n);
printArray(arr, n);
return 0;
}
Task # 05: Write a program to implement the Merge sort on given array?
#include<stdlib.h>
#include<stdio.h>
// Merges two subarrays of arr[].
// First subarray is arr[l..m] // Second
subarray is arr[m+1..r] void merge(int
arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
Page 10
for (j = 0; j < n2; j++)
R[j] = arr[m + 1+ j];
Page 11
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
merge(arr, l, m, r);
}
}
Page 12
/* UTILITY FUNCTIONS */
/* Function to print an array */
void printArray(int A[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", A[i]); printf("\
n");
}
Page 13
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
/* The main function that implements QuickSort
arr[] --> Array to be sorted,
low --> Starting index, high
--> Ending index */
void quickSort(int arr[], int low, int high)
{
if (low < high)
{
/* pi is partitioning index, arr[p] is now
at right place */
int pi = partition(arr, low, high);
// Separately sort elements before
// partition and after partition
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
// Driver Code
int main()
{
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n - 1); cout
<< "Sorted array: \n";
printArray(arr, n);
return 0;
}
Task # 07: Write a program to implement the bubble sort on given list?
#include <stdio.h>
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
Department of Computer Science
Institute of Southern Punjab, Multan
Page 14
}
// An optimized version of Bubble Sort
void bubbleSort(int arr[], int n)
{
int i, j;
bool swapped; for (i =
0; i < n-1; i++)
{
swapped = false;
for (j = 0; j < n-i-1; j++)
{
if (arr[j] > arr[j+1])
{
swap(&arr[j], &arr[j+1]);
swapped = true;
}
}
// IF no two elements were swapped by inner loop, then break
if (swapped == false)
break;
}
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]); printf("n");
}
// Driver program to test above functions
int main()
{
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n); printf("Sorted
array: \n");
printArray(arr, n);
return 0;
}
Page 15
LAB # 03
Assignment # 03
LAB # 04
LAB Task Task #
Solution:
#include <iostream>
using namespace std;
> arr[largest])
largest = l;
largest = r;
if (largest != i)
Page 16
swap(arr[i], arr[largest]); //
heapify(arr, n, largest);
heapify(arr, n, i);
heapify(arr, i, 0);
Page 17
for (int i=0; i<n; ++i)
// Driver program
int main()
int n = sizeof(arr)/sizeof(arr[0]);
heapSort(arr, n);
printArray(arr, n);
}
Task # 02: Write a program to implement the Radix Sort on the give list?
Solution
#include<iostream>
int mx = arr[0];
mx = arr[i];
Page 18
return mx;
(i = n - 1; i >= 0; i--)
Page 19
// Copy the output array to arr[], so that arr[] now
arr[i] = output[i];
countSort(arr, n, exp);
Page 20
// Driver program to test above functions
int main()
int n = sizeof(arr)/sizeof(arr[0]);
return 0;
Task # 03: Write a program to implement the Bucket Sort on a given list?
Solution
#include <iostream>
#include <algorithm>
#include <vector>
vector<float> b[n];
bucket b[bi].push_back(arr[i]);
Page 21
}
sort(b[i].begin(), b[i].end()); //
int index = 0;
arr[index++] = b[i][j];
int main()
int n = sizeof(arr)/sizeof(arr[0]);
return 0;
Task # 04: Write a program to implement the Shell Sort on a given list?
Solution
Page 22
#include <iostream>
// Do a gapped insertion sort for this gap size. The first gap elements a[0..gap-1] are already
// in gapped order keep adding one more element until the entire array is gap sorted
// add a[i] to the elements that have been gap sorted save a[i] in temp and make a hole at
//position i
// shift earlier gap-sorted elements up until the correct location for a[i] is found
int j;
arr[j] = temp;
return 0;
Page 23
} void printArray(int arr[], int
n)
{
for (int i=0; i<n; i++)
} int
main()
int n = sizeof(arr)/sizeof(arr[0]);
printArray(arr, n);
return 0;
LAB # 04
Assignment
LAB # 05
LAB Task
Task # 01: Write a program to implement the Stack Data structure? Solution
#include <bits/stdc++.h>
using namespace std;
#define MAX 1000 class
Stack {
int top;
public:
int a[MAX]; // Maximum size of Stack
Stack() { top = -1; }
bool push(int x);
Page 24
int pop(); int
peek();
bool isEmpty();
};
bool Stack::push(int x)
{
if (top >= (MAX - 1)) {
cout << "Stack Overflow";
return false;
}
else {
a[++top] = x;
cout << x << " pushed into stack\n";
return true;
}
} int
Stack::pop()
{
if (top < 0) {
cout << "Stack Underflow";
return 0;
}
else {
int x = a[top--];
return x;
}
} int
Stack::peek()
{
if (top < 0) {
cout << "Stack is Empty";
return 0;
}
else {
int x = a[top];
return x;
}
}
bool Stack::isEmpty()
{
return (top < 0);
}
// Driver program to test above functions
int main()
{
Page 25
class Stack s;
s.push(10);
s.push(20);
s.push(30);
cout << s.pop() << " Popped from stack\n";
return 0;
}
LAB # 05
Assignment
LAB # 06
LAB Task
Solution
#include <bits/stdc++.h>
class Queue
public:
array;
};
queue->capacity = capacity;
queue->front = queue->size = 0;
Page 26
return queue;
if (isFull(queue))
return;
n";
if (isEmpty(queue))
return INT_MIN;
Page 27
int item = queue->array[queue->front]; queue-
if (isEmpty(queue))
return INT_MIN;
return queue->array[queue->front];
rear(Queue* queue)
if (isEmpty(queue))
return INT_MIN;
return queue->array[queue->rear];
// Driver code
int main()
Page 28
cout << "Front item is " << front(queue) << endl;
return 0;
LAB # 06
Assignment
LAB # 07
LAB Task
Task # 01: Write a program to implement the Linked List Data Structures with all its
operations?
Solution
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
struct node { int
info; struct node
*next;
} *start; class
single_llist
{ publi
c:
node* create_node(int);
void insert_begin();
void insert_pos(); void
insert_last(); void
delete_pos(); void
sort(); void search();
void update(); void
reverse(); void
display(); single_llist()
{
start = NULL;
}
};
main()
{
int choice, nodes, element, position, i;
single_llist sl;
start = NULL;
Page 29
while (1)
{
cout<<endl<<"---------------------------------"<<endl;
cout<<endl<<"Operations on singly linked list"<<endl;
cout<<endl<<"---------------------------------"<<endl;
cout<<"1.Insert Node at beginning"<<endl;
cout<<"2.Insert node at last"<<endl; cout<<"3.Insert
node at position"<<endl; cout<<"4.Sort Link
List"<<endl; cout<<"5.Delete a Particular
Node"<<endl; cout<<"6.Update Node Value"<<endl;
cout<<"7.Search Element"<<endl; cout<<"8.Display
Linked List"<<endl; cout<<"9.Reverse Linked List
"<<endl;
cout<<"10.Exit "<<endl;
cout<<"Enter your choice : ";
cin>>choice;
switch(choice)
{ case
1:
cout<<"Inserting Node at Beginning: "<<endl;
sl.insert_begin();
cout<<endl;
break; case 2:
cout<<"Inserting Node at Last: "<<endl;
sl.insert_last(); cout<<endl;
break; case 3:
cout<<"Inserting Node at a given position:"<<endl;
sl.insert_pos();
cout<<endl;
break; case 4:
cout<<"Sort Link List: "<<endl;
sl.sort();
cout<<endl;
break; case 5:
cout<<"Delete a particular node: "<<endl;
sl.delete_pos();
break; case 6:
cout<<"Update Node Value:"<<endl;
sl.update(); cout<<endl; break;
case 7:
cout<<"Search element in Link List: "<<endl;
sl.search(); cout<<endl; break;
case 8:
cout<<"Display elements of link list"<<endl;
sl.display(); cout<<endl; break;
case 9:
Department of Computer Science
Institute of Southern Punjab, Multan
Page 30
cout<<"Reverse elements of Link List"<<endl;
sl.reverse();
cout<<endl; break;
case 10:
cout<<"Exiting..."<<endl;
exit(1); break;
default:
cout<<"Wrong choice"<<endl;
}
}
}
node *single_llist::create_node(int value)
{ struct node *temp, *s;
temp = new(struct node);
if (temp == NULL)
{
cout<<"Memory not allocated "<<endl;
return 0;
} else
{
temp->info = value;
temp->next = NULL;
return temp;
}
}
void single_llist::insert_begin()
{ int
value;
cout<<"Enter the value to be inserted: ";
cin>>value; struct node *temp, *p;
temp = create_node(value);
if (start == NULL)
{ start = temp;
start->next = NULL;
} else {
p = start; start =
temp; start-
>next = p;
}
cout<<"Element Inserted at beginning"<<endl;
}
void single_llist::insert_last()
{
int value;
cout<<"Enter the value to be inserted: ";
Page 31
cin>>value; struct
node *temp, *s;
temp = create_node(value);
s = start;
while (s->next != NULL)
{
s = s->next;
}
temp->next = NULL; s-
>next = temp;
cout<<"Element Inserted at last"<<endl;
}
void single_llist::insert_pos()
{
int value, pos, counter = 0;
cout<<"Enter the value to be inserted: ";
cin>>value; struct node *temp, *s, *ptr;
temp = create_node(value);
cout<<"Enter the postion at which node to be inserted: ";
cin>>pos;
int i;
s = start;
while (s != NULL)
{ s = s-
>next;
counter++;
} if (pos
== 1)
{ if (start ==
NULL)
{ start =
temp;
start->next = NULL;
} else {
ptr = start; start =
temp; start->next
= ptr;
}
}
else if (pos > 1 && pos <= counter)
{ s = start; for
(i = 1; i < pos; i++) {
ptr = s; s = s->next;
}
ptr->next = temp;
temp->next = s;
Page 32
}
else
{
cout<<"Positon out of range"<<endl;
}
}
void single_llist::sort()
{ struct node *ptr,
*s; int value; if
(start == NULL)
{
cout<<"The List is empty"<<endl;
return;
}
ptr = start; while
(ptr != NULL)
{
for (s = ptr->next;s !=NULL;s = s->next)
{
if (ptr->info > s->info)
{ value =
ptr->info; ptr->info
= s->info;
s->info = value;
}
} ptr = ptr-
>next;
}
}
void single_llist::delete_pos()
{ int pos, i, counter =
0;
if (start == NULL)
{
cout<<"List is empty"<<endl;
return;
}
cout<<"Enter the position of value to be deleted: ";
cin>>pos; struct node *s, *ptr;
s = start;
if (pos == 1)
{ start = s-
>next;
}
else
Page 33
{
while (s != NULL)
{ s = s-
>next;
counter++;
}
if (pos > 0 && pos <= counter)
{ s = start;
for (i = 1;i < pos;i++)
{ ptr
= s; s = s-
>next;
}
ptr->next = s->next;
}
else
{
cout<<"Position out of range"<<endl;
}
free(s);
cout<<"Element Deleted"<<endl;
}
}
void single_llist::update()
{ int value, pos,
i;
if (start == NULL)
{
cout<<"List is empty"<<endl;
return;
}
cout<<"Enter the node postion to be updated: ";
cin>>pos; cout<<"Enter the new value: ";
cin>>value; struct node *s, *ptr; s = start;
if (pos == 1) {
start->info = value;
}
else
{ for (i = 0;i < pos -
1;i++)
{
if (s == NULL)
{
cout<<"There are less than "<<pos<<" elements";
return; }
s = s->next;
}
Department of Computer Science
Institute of Southern Punjab, Multan
Page 34
s->info = value;
}
cout<<"Node Updated"<<endl;
}
void single_llist::search()
{ int value, pos =
0; bool flag =
false;
if (start == NULL)
{
cout<<"List is empty"<<endl;
return;
}
cout<<"Enter the value to be searched: ";
cin>>value; struct node *s; s = start;
while (s != NULL)
{ pos+
+;
if (s->info == value)
{ flag
= true;
cout<<"Element "<<value<<" is found at position "<<pos<<endl;
} s = s-
>next;
} if (!
flag)
cout<<"Element "<<value<<" not found in the list"<<endl;
}
void single_llist::reverse()
{
struct node *ptr1, *ptr2, *ptr3;
if (start == NULL)
{
cout<<"List is empty"<<endl;
return;
}
if (start->next == NULL)
{ return; }
ptr1 = start; ptr2 =
ptr1->next; ptr3 =
ptr2->next; ptr1-
>next = NULL;
ptr2->next = ptr1;
while (ptr3 != NULL)
Page 35
{ ptr1 = ptr2;
ptr2 = ptr3; ptr3 = ptr3-
>next; ptr2->next =
ptr1;
}
start = ptr2;
}
void single_llist::display()
{ struct node
*temp;
if (start == NULL)
{
cout<<"The List is Empty"<<endl;
return;
} temp =
start;
cout<<"Elements of list are: "<<endl;
while (temp != NULL)
{
cout<<temp->info<<"->";
temp = temp->next;
}
cout<<"NULL"<<endl;
}
LAB # 07
Assignment
LAB # 08
LAB Task
Task # 01: Write a program to implement the Doubly Linked list with its operations?
Solution
#include <iostream>
using namespace std;
struct Node { int
data; struct Node*
next; struct Node*
prev;
};
void insert_front(struct Node** head, int new_data)
{
struct Node* newNode = new Node;
newNode->data = new_data;
newNode->next = (*head);
newNode->prev = NULL; if
((*head) != NULL) (*head)->prev =
newNode;
(*head) = newNode;
Page 36
}
void insert_After(struct Node* prev_node, int new_data)
{
if (prev_node == NULL) {
cout<<"Previous node is required , it cannot be NULL";
return; }
struct Node* newNode = new Node;
newNode->data = new_data;
newNode->next = prev_node->next;
prev_node->next = newNode;
newNode->prev = prev_node; if
(newNode->next != NULL)
newNode->next->prev = newNode;
}
void insert_end(struct Node** head, int new_data)
{
struct Node* newNode = new Node; struct Node*
last = *head; //set last node value to head
newNode->data = new_data;
newNode->next = NULL; if
(*head == NULL)
{ newNode->prev = NULL;
*head = newNode;
return; }
while (last->next != NULL)
last = last->next; last->next
= newNode; newNode-
>prev = last;
return;
}
void displayList(struct Node* node) {
struct Node* last; while (node
!= NULL) { cout<<node-
>data<<"<==>"; last = node;
node = node->next;
}
if(node == NULL)
cout<<"NULL";
}
int main() {
/* Start with the empty list */
struct Node* head = NULL;
insert_end(&head, 40);
insert_front(&head, 20);
Page 37
insert_front(&head, 10);
insert_end(&head, 50);
insert_After(head->next, 30);
cout<<"Doubly linked list is as follows: "<<endl;
displayList(head); return 0;
}
LAB 08
Assignment
LAB 09
LAB Task
Task # 01: Write a program to implement the stack using linked list?
Solution
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* link;
}; struct Node*
top; void push(int
data)
{
struct Node* temp; temp = new
Node(); if (!temp) { cout
<< "\nHeap Overflow";
exit(1);
}
temp->data = data; temp-
>link = top;
top = temp;
} int
isEmpty()
{
return top == NULL;
} int
peek()
{
if (!isEmpty())
return top->data;
else exit(1);
} void
pop()
{
struct Node* temp; if (top == NULL) {
cout << "\nStack Underflow" << endl;
exit(1);
Page 38
}
else { temp =
top; top = top->link;
temp->link = NULL;
free(temp);
}
} void
display()
{
struct Node* temp; if (top ==
NULL) { cout << "\nStack
Underflow";
exit(1);
}
else { temp =
top; while (temp != NULL)
{
cout << temp->data << " ";
temp = temp->link;
}
}
}
// Driver Code
int main()
{
push(11);
push(22);
push(33);
push(44);
display();
cout << "\nTop element is %d\n" << peek();
pop();
pop();
display();
cout << "\nTop element is %d\n" << peek();
return 0;
}
LAB # 09
Assignments
LAB # 10
LAB Task
Task # 01: Write a program to implement the Queue data structures using linked list?
Page 39
Solution
#include <bits/stdc++.h>
struct QNode {
int data;
QNode* next;
QNode(int d)
data = d;
next = NULL;
};
struct Queue {
Queue()
void enQueue(int x)
Page 40
if (rear == NULL) {
return;
rear->next = temp;
rear = temp;
// Function to remove
void deQueue()
if (front == NULL)
return;
front = front->next;
Page 41
// If front becomes NULL, then
if (front == NULL)
rear = NULL;
delete (temp);
};
// Driven Program
int main()
Queue q;
q.enQueue(10);
q.enQueue(20);
q.deQueue();
q.deQueue();
q.enQueue(30);
q.enQueue(40);
q.enQueue(50);
Page 42