0% found this document useful (0 votes)
25 views26 pages

Muhammad Asaad 22F-3879 3D Mam Rabia Anwar: Data Structure Lab 12 Name: Roll No: Section: Teacher

Uploaded by

f223879
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views26 pages

Muhammad Asaad 22F-3879 3D Mam Rabia Anwar: Data Structure Lab 12 Name: Roll No: Section: Teacher

Uploaded by

f223879
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

DATA STRUCTURE LAB 12

Name : Muhammad Asaad


Roll No : 22F-3879
Section : 3D
Teacher: Mam Rabia Anwar

Task 1:
#include <iostream>
using namespace std;

struct Node {
int data;
Node* left;
Node* right;
int height;
};

Node* newNode(int val)


{
Node* node = new Node();
node->data = val;
node->left = nullptr;
node->right = nullptr;
node->height = 1;
return node;
}
int max(int a, int b)
{
return (a > b) ? a : b;
}

int height(Node* node)


{
if (node == nullptr) return 0;
return node->height;
}

Node* rotateRight(Node* y)
{
Node* x = y->left;
Node* T2 = x->right;

x->right = y;
y->left = T2;

y->height = 1 + max(height(y->left), height(y->right));


x->height = 1 + max(height(x->left), height(x->right));

return x;
}

Node* rotateLeft(Node* x)
{
Node* y = x->right;
Node* T2 = y->left;

y->left = x;
x->right = T2;

x->height = 1 + max(height(x->left), height(x->right));


y->height = 1 + max(height(y->left), height(y->right));

return y;
}

int balanceFactor(Node* node)


{
if (node == nullptr) return 0;
return height(node->left) - height(node->right);
}
Node* insert(Node* node, int val)
{
if (node == nullptr) return newNode(val);

if (val < node->data)


node->left = insert(node->left, val);
else if (val > node->data)
node->right = insert(node->right, val);
else // Equal keys not allowed in BST
return node;

node->height = 1 + max(height(node->left), height(node-


>right));
int balance = balanceFactor(node);

// Left Left
if (balance > 1 && val < node->left->data)
return rotateRight(node);

// Right Right
if (balance < -1 && val > node->right->data)
return rotateLeft(node);

// Left Right
if (balance > 1 && val > node->left->data) {
node->left = rotateLeft(node->left);
return rotateRight(node);
}

// Right Left
if (balance < -1 && val < node->right->data) {
node->right = rotateRight(node->right);
return rotateLeft(node);
}

return node;
}

Node* search(Node* root, int val, int* comparisons)


{
(*comparisons)++;
if (root == nullptr || root->data == val)
return root;

if (val < root->data)


return search(root->left, val, comparisons);
else
return search(root->right, val, comparisons);
}

Node* deleteNode(Node* root, int key)


{
if (root == nullptr) return root;

if (key < root->data)


root->left = deleteNode(root->left, key);
else if (key > root->data)
root->right = deleteNode(root->right, key);
else {
// Node with one or no child
if (root->left == nullptr || root->right == nullptr) {
Node* temp = root->left ? root->left : root-
>right;

if (temp == nullptr) {
temp = root;
root = nullptr;
}
else // One child
*root = *temp;

delete temp;
}
else {
// Node with two children.. Getting inorder
successor (smallest in right subtree)
Node* temp = root->right;
while (temp->left != nullptr)
temp = temp->left;
root->data = temp->data;
// Deleting inorder successor
root->right = deleteNode(root->right, temp-
>data);
}
}

// One node
if (root == nullptr) return root;

root->height = 1 + max(height(root->left), height(root-


>right));
int balance = balanceFactor(root);

// Left Left
if (balance > 1 && balanceFactor(root->left) >= 0)
return rotateRight(root);

// Left Right
if (balance > 1 && balanceFactor(root->left) < 0) {
root->left = rotateLeft(root->left);
return rotateRight(root);
}

// Right Right
if (balance < -1 && balanceFactor(root->right) <= 0)
return rotateLeft(root);

// Right Left
if (balance < -1 && balanceFactor(root->right) > 0) {
root->right = rotateRight(root->right);
return rotateLeft(root);
}

return root;
}

bool isAVL(Node* root)


{
if (root == nullptr) return true;

int balance = balanceFactor(root);

// Checking if current node is balanced


if (balance < -1 || balance > 1) return false;

// Recursively checking if left and right subtrees are AVL


return isAVL(root->left) && isAVL(root->right);
}

void printInorder(Node* root)


{
if (root != nullptr) {
printInorder(root->left);
cout << root->data << " ";
printInorder(root->right);
}
}
void printPreorder(Node* root)
{
if (root != nullptr) {
cout << root->data << " ";
printPreorder(root->left);
printPreorder(root->right);
}
}

int main() {
Node* root = nullptr;

cout << "Inserting 10,20,30,40,50,25 in AVL.."<<endl<<endl;


root = insert(root, 10);
root = insert(root, 20);
root = insert(root, 30);
root = insert(root, 40);
root = insert(root, 50);
root = insert(root, 25);

int comparisons = 0;
Node* found = search(root, 30, &comparisons);
if (found != nullptr)
{
cout << "Searching for 30.." << endl;
cout << "Element found after " << comparisons << "
comparisons." << endl<<endl;
}
else cout << "Element not found." << endl<<endl;

cout << "Deleting 30.."<<endl<<endl;


root = deleteNode(root, 30);

cout << "Printing the tree.."<<endl<<endl;


cout << "Inorder traversal: ";
printInorder(root);
cout << endl;

cout << "Preorder traversal: ";


printPreorder(root);
cout << endl;

cout << endl<<"Checking if tree is AVL.." << endl;

if (isAVL(root))
cout << "The tree is AVL." << endl;
else
cout << "The tree is not AVL." << endl;

system("pause;");
return 0;
}

Output:

Task 2:
#include <iostream>

using namespace std;

class MinHeap {
private:
int* heapArray;
int capacity;
int heapSize;

int parent(int i) { return (i - 1) / 2; }


int leftChild(int i) { return 2 * i + 1; }
int rightChild(int i) { return 2 * i + 2; }

void percolateUp(int i) {
int parentIndex = parent(i);
while (i > 0 && heapArray[parentIndex] > heapArray[i])
{
// Swap elements
int temp = heapArray[i];
heapArray[i] = heapArray[parentIndex];
heapArray[parentIndex] = temp;

i = parentIndex;
parentIndex = parent(i);
}
}

// Helps to maintain heap property


void percolateDown(int i) {
int smallest = i;
int left = leftChild(i);
int right = rightChild(i);

if (left < heapSize && heapArray[left] <


heapArray[smallest])
smallest = left;
if (right < heapSize && heapArray[right] <
heapArray[smallest])
smallest = right;

if (smallest != i) {
// Swapping
int temp = heapArray[i];
heapArray[i] = heapArray[smallest];
heapArray[smallest] = temp;

percolateDown(smallest);
}
}

public:
MinHeap(int cap) {
capacity = cap;
heapSize = 0;
heapArray = new int[capacity];
}

~MinHeap() {
delete[] heapArray;
}

int getMin() {
if (heapSize == 0) {
cout << "Heap is empty\n";
return -1;
}
return heapArray[0];
}

int extractMin()
{
if (heapSize <= 0) {
cout << "Heap is empty\n";
return -1;
}
if (heapSize == 1) {
heapSize--;
return heapArray[0];
}

int root = heapArray[0];


heapArray[0] = heapArray[heapSize - 1];
heapSize--;
percolateDown(0);

return root;
}

void decreaseKey(int i, int newVal)


{
heapArray[i] = newVal;
percolateUp(i);
}

void insert(int newVal)


{
if (heapSize == capacity) {
cout << "Heap overflow\n";
return;
}

heapSize++;
int i = heapSize - 1;
heapArray[i] = newVal;

percolateUp(i);
}

void remove(int i)
{
if (i < 0 || i >= heapSize) {
cout << "Index out of range\n";
return;
}

decreaseKey(i, -2.153467647); // Decreasing key to


smallest possible value
extractMin();
}

int* getHeapArray() {
return heapArray;
}

int getHeapSize() {
return heapSize;
}
};
int main() {
int capacity;
cout << "Enter the capacity of the min heap: ";
cin >> capacity;

MinHeap minHeap(capacity);

int choice;
do {
cout << "\nMin Heap Operations:" << endl;
cout << "1. Insert" << endl;
cout << "2. Extract Minimum" << endl;
cout << "3. Decrease Key" << endl;
cout << "4. Remove" << endl;
cout << "5. Get Minimum" << endl;
cout << "6. Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;

switch (choice) {
case 1: {
cout << "Enter " << capacity << " values to
insert into the heap:" << endl;
for (int i = 0; i < capacity; ++i) {
int newVal;
cin >> newVal;
minHeap.insert(newVal);
}
break;
}
case 2: {
int min = minHeap.extractMin();
cout << "Minimum element extracted: " << min <<
endl;

cout << "Heap after extraction:" << endl;


int* heapArray = minHeap.getHeapArray();
int heapSize = minHeap.getHeapSize();
for (int i = 0; i < heapSize; ++i) {
cout << heapArray[i] << " ";
}
cout << endl;
break;
}

case 3: {
int index, newVal;
cout << "Enter the index and new value to
decrease key: ";
cin >> index >> newVal;
minHeap.decreaseKey(index, newVal);

cout << "Heap after decreasing key:" << endl;


int* heapArray = minHeap.getHeapArray();
int heapSize = minHeap.getHeapSize();
for (int i = 0; i < heapSize; ++i) {
cout << heapArray[i] << " ";
}
cout << endl;
break;
}
case 4: {
int index;
cout << "Enter the index to remove: ";
cin >> index;
minHeap.remove(index);
break;
}
case 5: {
int min = minHeap.getMin();
cout << "Minimum element: " << min << endl;
break;
}
case 6: {
cout << "Exiting..." << endl;
break;
}
default:
cout << "Invalid choice. Please try again." <<
endl;
}

} while (choice != 6);

system("pause");
return 0;
}
Output:
Task 3:
#include <iostream>
using namespace std;

void MaxHeapify(char arr[], int n, int i)


{
int largest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;

// If left child larger than root..


if (l < n && arr[l] > arr[largest])
largest = l;

// Right child is larger than largest so far..


if (r < n && arr[r] > arr[largest])
largest = r;

if (largest != i) {
swap(arr[i], arr[largest]);
// Recursively heapifying affected sub-tree..
MaxHeapify(arr, n, largest);
}
}

void MinHeapify(char arr[], int n, int i)


{
int smallest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;

// Left child smaller than root..


if (l < n && arr[l] < arr[smallest])
smallest = l;

// Right child smaller than smallest so far..


if (r < n && arr[r] < arr[smallest])
smallest = r;

if (smallest != i) {
swap(arr[i], arr[smallest]);

MinHeapify(arr, n, smallest);
}
}

void HeapSort(char arr[], int n)


{
// Building heap...
for (int i = n / 2 - 1; i >= 0; i--) {
MaxHeapify(arr, n, i);
}

// Extracting elements
for (int i = n - 1; i > 0; i--) {
swap(arr[0], arr[i]);
MaxHeapify(arr, i, 0);
}
}

void PrintArray(char arr[], int n)


{
for (int i = 0; i < n; ++i)
cout << arr[i] << " ";
cout << endl;
}
int main() {
char arr[] = { 'H', 'E', 'A', 'P', 'S', 'O', 'R', 'T' };
int n = sizeof(arr) / sizeof(arr[0]);

cout << "Original array: ";


PrintArray(arr, n);

HeapSort(arr, n);

cout << "Sorted array: ";


PrintArray(arr, n);

cout << endl;


system("pause");
return 0;
}

Output:

Task 4:
#include <iostream>
using namespace std;

void minHeapify(int arr[], int n, int i)


{
int smallest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
// Left child smaller than root
if (l < n && arr[l] < arr[smallest])
smallest = l;

// Right child smaller than smallest


if (r < n && arr[r] < arr[smallest])
smallest = r;

if (smallest != i) {
swap(arr[i], arr[smallest]);

minHeapify(arr, n, smallest);
}
}

void buildMinHeap(int arr[], int n)


{
// Index of last non-leaf node..
int startIdx = (n / 2) - 1;

// Reverse order traversal


for (int i = startIdx; i >= 0; i--) {
minHeapify(arr, n, i);
}
}

void printKLargestElements(int arr[], int n, int k)


{
buildMinHeap(arr, k);

// Remaining elements of array


for (int i = k; i < n; ++i)
{
if (arr[i] > arr[0]) {
swap(arr[0], arr[i]);
minHeapify(arr, k, 0);
}
}

cout << "The " << k << " largest elements in the array are: ";
for (int i = 0; i < k; ++i) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
int arr[] = { 1, 23, 12, 9, 30, 2, 50 };
int n = sizeof(arr) / sizeof(arr[0]);
int k;
cout << "The array is: " << "1 6 12 9 35 2 50" << endl << endl;
cout << "Enter the number of largest elements you want to find: ";
cin >> k;

cout << endl;


printKLargestElements(arr, n, k);

cout << endl;


system("pause");
return 0;
}

Output:

Task 5:
#include <iostream>
using namespace std;

struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
void inorderTraversal(TreeNode* root, int arr[], int& index)
{
if (root == nullptr) return;
inorderTraversal(root->left, arr, index);
arr[index++] = root->val;
inorderTraversal(root->right, arr, index);
}

void preorderTraversal(TreeNode* root, int arr[], int& index)


{
if (root == nullptr) return;
root->val = arr[index++];
preorderTraversal(root->left, arr, index);
preorderTraversal(root->right, arr, index);
}

void convertBSTtoMinHeap(TreeNode* root)


{
// Performing inorder traversal to get sorted array of values
int arr[100];
int index = 0;
inorderTraversal(root, arr, index);

// Copying values from array to nodes using preorder


index = 0;
preorderTraversal(root, arr, index);
}

void printInorder(TreeNode* root)


{
if (root == nullptr) return;
printInorder(root->left);
cout << root->val << " ";
printInorder(root->right);
}

TreeNode* buildBST(TreeNode* root, int val)


{
if (root == nullptr) return new TreeNode(val);
if (val < root->val) root->left = buildBST(root->left, val);
else root->right = buildBST(root->right, val);
return root;
}

TreeNode* makeBST()
{
TreeNode* root = nullptr;
int n, val;
cout << "Enter the number of nodes in BST: ";
cin >> n;
cout << "Enter the values of nodes: " << endl;
for (int i = 0; i < n; ++i) {
cin >> val;
root = buildBST(root, val);
}
return root;
}

int main() {
TreeNode* root = makeBST();

cout << "Original BST (inorder): ";


printInorder(root);
cout << endl;

convertBSTtoMinHeap(root);

cout << "Min Heap after conversion (preorder): ";


printInorder(root);
cout << endl << endl;

system("pause");
return 0;
}

Output:
Task 6:
#include <iostream>
using namespace std;

void maxHeapify(int arr[], int n, int i)


{
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;

if (left < n && arr[left] > arr[largest])


largest = left;

if (right < n && arr[right] > arr[largest])


largest = right;

if (largest != i) {
swap(arr[i], arr[largest]);
maxHeapify(arr, n, largest);
}
}

void buildMaxHeap(int arr[], int n)


{
int start_index = (n / 2) - 1;
for (int i = start_index; i >= 0; i--) {
maxHeapify(arr, n, i);
}
}

void convertMinHeapToMaxHeap(int arr[], int n)


{
buildMaxHeap(arr, n);
}

int main() {
int n;
cout << "Enter the size of the array: ";
cin >> n;

int* arr = new int[n];


cout << "Enter " << n << " elements of the array: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}

convertMinHeapToMaxHeap(arr, n);

cout << "Max Heap: ";


for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;

delete[] arr;
return 0;
}

Output:
Task 7:
#include <iostream>
using namespace std;

struct Task {
int taskID;
int priority;
int executionTime;

Task() : taskID(-1), priority(-1), executionTime(-1) {}


Task(int id, int p, int time) : taskID(id), priority(p), executionTime(time) {}
};

class PriorityQueue {
private:
Task* heap;
int capacity;
int size;

// Helper function to maintain heap property


void minHeapify(int i) {
int left = 2 * i + 1;
int right = 2 * i + 2;
int smallest = i;

if (left < size && heap[left].priority < heap[smallest].priority)


smallest = left;

if (right < size && heap[right].priority < heap[smallest].priority)


smallest = right;

if (smallest != i) {
swap(heap[i], heap[smallest]);
minHeapify(smallest);
}
}

public:
PriorityQueue(int capacity) : capacity(capacity), size(0)
{
heap = new Task[capacity];
}

~PriorityQueue() {
delete[] heap;
}

void insertTask(int taskID, int priority, int executionTime)


{
if (size == capacity) {
cout << "Priority queue is full. Cannot insert task." << endl;
return;
}

heap[size] = Task(taskID, priority, executionTime);


int i = size;
size++;

// Fixing min-heap property by moving newly inserted task up


while (i > 0 && heap[(i - 1) / 2].priority > heap[i].priority) {
swap(heap[i], heap[(i - 1) / 2]);
i = (i - 1) / 2;
}
}

// Removing task with highest priority (i.e., with lowest priority level)
Task extractMin() {
if (size <= 0) {
cerr << "Priority queue is empty. No task to extract." << endl;
return Task(-1, -1, -1); // dummy task
}

Task minTask = heap[0];


heap[0] = heap[size - 1];
size--;
minHeapify(0); // Restoring min-heap property
return minTask;
}

Task peek() {
if (size <= 0) {
cout << "Priority queue is empty. No task to peek." << endl;
return Task(-1, -1, -1);
}
return heap[0];
}
};

int main() {

PriorityQueue pq(10);
pq.insertTask(1, 5, 10);
pq.insertTask(2, 3, 8);
pq.insertTask(3, 7, 12);
pq.insertTask(4, 3, 9);

Task topTask = pq.peek();


cout << "Task at the top of the priority queue: ";
cout << "Task ID: " << topTask.taskID << ", Priority: " <<
topTask.priority << ", Execution Time: " << topTask.executionTime << endl;

// Removing the task with highest priority


Task extractedTask = pq.extractMin();
cout << "Removed task: ";
cout << "Task ID: " << extractedTask.taskID << ", Priority: " <<
extractedTask.priority << ", Execution Time: " <<
extractedTask.executionTime << endl;

return 0;
}

Output:

You might also like