0% found this document useful (0 votes)
5 views16 pages

Exp-3 & 4

The document provides C programs for constructing Min and Max Heaps using arrays, including functions for deletion and display. It also includes implementations of Breadth-First Traversal (BFT) using an adjacency matrix and Depth-First Traversal (DFT) using adjacency lists. The explanations detail the algorithms and data structures used, along with example outputs for each program.

Uploaded by

kesavat0001
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)
5 views16 pages

Exp-3 & 4

The document provides C programs for constructing Min and Max Heaps using arrays, including functions for deletion and display. It also includes implementations of Breadth-First Traversal (BFT) using an adjacency matrix and Depth-First Traversal (DFT) using adjacency lists. The explanations detail the algorithms and data structures used, along with example outputs for each program.

Uploaded by

kesavat0001
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/ 16

3.

Construct Min and Max Heap using arrays, delete any element and
display the content of the Heap.

C Program: Min and Max Heap Construction, Deletion, and Display

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

#define MAX 100

void swap(int *a, int *b) {


int temp = *a;
*a = *b;
*b = temp;
}

// Functions for Min Heap


void minHeapify(int heap[], int n, int i) {
int smallest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;

if (left < n && heap[left] < heap[smallest])


smallest = left;
if (right < n && heap[right] < heap[smallest])
smallest = right;

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

void buildMinHeap(int heap[], int n) {


for (int i = n / 2 - 1; i >= 0; i--) {
minHeapify(heap, n, i);
}
}

void deleteMinElement(int heap[], int *n, int value) {


int i;
for (i = 0; i < *n; i++) {
if (heap[i] == value)
break;
}
if (i == *n) {
printf("Element not found in Min Heap\n");
return;
}
swap(&heap[i], &heap[*n - 1]);
(*n)--;
buildMinHeap(heap, *n);
}

void displayMinHeap(int heap[], int n) {


printf("Min Heap: ");
for (int i = 0; i < n; i++) {
printf("%d ", heap[i]);
}
printf("\n");
}

// Functions for Max Heap


void maxHeapify(int heap[], int n, int i) {
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;

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


largest = left;
if (right < n && heap[right] > heap[largest])
largest = right;
if (largest != i) {
swap(&heap[i], &heap[largest]);
maxHeapify(heap, n, largest);
}
}

void buildMaxHeap(int heap[], int n) {


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

void deleteMaxElement(int heap[], int *n, int value) {


int i;
for (i = 0; i < *n; i++) {
if (heap[i] == value)
break;
}
if (i == *n) {
printf("Element not found in Max Heap\n");
return;
}
swap(&heap[i], &heap[*n - 1]);
(*n)--;
buildMaxHeap(heap, *n);
}

void displayMaxHeap(int heap[], int n) {


printf("Max Heap: ");
for (int i = 0; i < n; i++) {
printf("%d ", heap[i]);
}
printf("\n");
}
int main() {
int minHeap[MAX], maxHeap[MAX];
int n, value, choice;

printf("Enter the number of elements: ");


scanf("%d", &n);

printf("Enter the elements:\n");


for (int i = 0; i < n; i++) {
scanf("%d", &minHeap[i]);
maxHeap[i] = minHeap[i];
}

buildMinHeap(minHeap, n);
buildMaxHeap(maxHeap, n);

displayMinHeap(minHeap, n);
displayMaxHeap(maxHeap, n);

printf("Enter element to delete from heaps: ");


scanf("%d", &value);

deleteMinElement(minHeap, &n, value);


deleteMaxElement(maxHeap, &n, value);

displayMinHeap(minHeap, n);
displayMaxHeap(maxHeap, n);

return 0;
}

Explanation:
1. Min Heap Construction:
o minHeapify() maintains the heap property for a subtree rooted at
index i.
o buildMinHeap() builds the heap from the array by calling
minHeapify() for non-leaf nodes.
o deleteMinElement() finds and deletes an element from the min heap,
rebuilds it to maintain the heap structure.
2. Max Heap Construction:
o maxHeapify() maintains the heap property for a subtree rooted at

index i in a max heap.


o buildMaxHeap() builds the max heap from an array by calling
maxHeapify().
o deleteMaxElement() deletes an element from the max heap and then
rebuilds the heap.
3. Display:
o displayMinHeap() and displayMaxHeap() print the current state of the

heaps.

Example Output:

Enter the number of elements: 5


Enter the elements:
10 20 15 30 40
Min Heap: 10 20 15 30 40
Max Heap: 40 30 15 10 20
Enter element to delete from heaps: 15
Min Heap: 10 20 40 30
Max Heap: 40 30 20 10
4. Implement BFT and DFT for given graph, when graph is represented by
o Adjacency Matrix b) Adjacency Lists

C Program: BFT for Graph Using Adjacency Matrix

#include <stdio.h>

#define MAX 100

int queue[MAX], front = -1, rear = -1;

// Function to enqueue an element in the queue


void enqueue(int v) {
if (rear == MAX - 1) {
printf("Queue Overflow\n");
return;
}
if (front == -1) front = 0;
queue[++rear] = v;
}

// Function to dequeue an element from the queue


int dequeue() {
if (front == -1 || front > rear) {
printf("Queue Underflow\n");
return -1;
}
return queue[front++];
}

// Check if the queue is empty


int isEmptyQueue() {
return front == -1 || front > rear;
}

// Breadth-First Traversal (BFT) for graph represented by adjacency matrix


void BFT_AdjMatrix(int adjMatrix[MAX][MAX], int n, int start) {
int visited[MAX] = {0}; // To keep track of visited vertices
enqueue(start);
visited[start] = 1;

printf("BFT (Adjacency Matrix): ");


while (!isEmptyQueue()) {
int v = dequeue();
printf("%d ", v);

// Explore the neighbors of the dequeued vertex


for (int i = 0; i < n; i++) {
if (adjMatrix[v][i] == 1 && !visited[i]) {
enqueue(i);
visited[i] = 1;
}
}
}
printf("\n");
}

int main() {
int n, start;
int adjMatrix[MAX][MAX];

// Input the number of vertices


printf("Enter the number of vertices: ");
scanf("%d", &n);

// Input the adjacency matrix


printf("Enter the adjacency matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &adjMatrix[i][j]);
}
}
// Input the starting vertex
printf("Enter the starting vertex: ");
scanf("%d", &start);

// Perform Breadth-First Traversal


BFT_AdjMatrix(adjMatrix, n, start);

return 0;
}

Explanation:

1. BFT Algorithm:
o Start from the start vertex.
o Enqueue the starting vertex, mark it as visited.
o Dequeue a vertex from the front of the queue.
o Explore all the adjacent vertices of the dequeued vertex that have not
been visited, mark them as visited, and enqueue them.
o Repeat the process until the queue is empty.

2. Queue Operations:
o enqueue(): Adds a vertex to the rear of the queue.
o dequeue(): Removes a vertex from the front of the queue.
o isEmptyQueue(): Checks whether the queue is empty.

3. Adjacency Matrix:
o adjMatrix[i][j] == 1 indicates an edge between vertex i and vertex j.
o If a vertex is found unvisited and there is an edge, it is enqueued.

Example Output:

Enter the number of vertices: 4


Enter the adjacency matrix:
0110
1001
1001
0110
Enter the starting vertex: 0
BFT (Adjacency Matrix): 0 1 2 3

In this example:

 The input matrix represents a graph with 4 vertices, and there is an edge
between vertices 0-1, 0-2, and 1-3, 2-3.
 Starting from vertex 0, the traversal order is: 0 -> 1 -> 2 -> 3.

C Program: DFT for Graph Using Adjacency Lists

Structure and Key Concepts

 Adjacency List Representation:


Each vertex in the graph has a linked list of adjacent vertices.
 Stack for DFT:
We use a stack (explicit or recursive) to implement Depth-First Traversal.

#include <stdio.h>

#include <stdlib.h>

#define MAX 100

// Node structure to represent adjacency list nodes

struct Node {

int vertex;

struct Node* next;

};

// Graph structure containing the number of vertices and an array of


adjacency lists
struct Graph {

int numVertices;

struct Node** adjLists; // Array of adjacency lists

int* visited; // Array to keep track of visited vertices

};

// Stack for Depth-First Traversal (DFT)

int stack[MAX];

int top = -1;

// Function to push an element to the stack

void push(int v) {

if (top == MAX - 1) {

printf("Stack Overflow\n");

return;

stack[++top] = v;

// Function to pop an element from the stack

int pop() {

if (top == -1) {

printf("Stack Underflow\n");

return -1;
}

return stack[top--];

// Check if the stack is empty

int isEmptyStack() {

return top == -1;

// Function to create a node in the adjacency list

struct Node* createNode(int v) {

struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));

newNode->vertex = v;

newNode->next = NULL;

return newNode;

// Function to create a graph with n vertices

struct Graph* createGraph(int vertices) {

struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));

graph->numVertices = vertices;

graph->adjLists = (struct Node**)malloc(vertices * sizeof(struct Node*));

graph->visited = (int*)malloc(vertices * sizeof(int));


for (int i = 0; i < vertices; i++) {

graph->adjLists[i] = NULL;

graph->visited[i] = 0;

return graph;

// Function to add an edge to an undirected graph

void addEdge(struct Graph* graph, int src, int dest) {

// Add edge from src to dest

struct Node* newNode = createNode(dest);

newNode->next = graph->adjLists[src];

graph->adjLists[src] = newNode;

// Add edge from dest to src (for undirected graph)

newNode = createNode(src);

newNode->next = graph->adjLists[dest];

graph->adjLists[dest] = newNode;

// Function to perform Depth-First Traversal (DFT) using a stack

void DFT_AdjList(struct Graph* graph, int start) {


push(start);

graph->visited[start] = 1;

printf("DFT (Adjacency List): ");

while (!isEmptyStack()) {

int v = pop();

printf("%d ", v);

// Get all adjacent vertices of the popped vertex v

struct Node* temp = graph->adjLists[v];

// Push all unvisited adjacent vertices to the stack

while (temp) {

int adjVertex = temp->vertex;

if (!graph->visited[adjVertex]) {

push(adjVertex);

graph->visited[adjVertex] = 1;

temp = temp->next;

}
printf("\n");

int main() {

int vertices, edges, src, dest, start;

// Input the number of vertices and edges

printf("Enter the number of vertices: ");

scanf("%d", &vertices);

struct Graph* graph = createGraph(vertices);

printf("Enter the number of edges: ");

scanf("%d", &edges);

// Input the edges (source and destination)

for (int i = 0; i < edges; i++) {

printf("Enter edge (source and destination): ");

scanf("%d %d", &src, &dest);

addEdge(graph, src, dest);

// Input the starting vertex for Depth-First Traversal

printf("Enter the starting vertex: ");

scanf("%d", &start);
// Perform Depth-First Traversal from the starting vertex

DFT_AdjList(graph, start);

return 0;

Explanation:

1. Graph Representation:
o Adjacency List: Each vertex has a linked list of adjacent vertices.
o A Node structure is used to represent each vertex in the adjacency list.

2. DFT Algorithm:
o Stack: DFT is implemented using a stack to explore vertices.
o Start from the given start vertex.
o Push the starting vertex onto the stack, mark it as visited.
o Pop a vertex from the stack, and print it.
o For each adjacent vertex that has not been visited, push it onto the
stack and mark it as visited.
o Repeat until the stack is empty.

3. Graph Creation:
o createGraph(): Initializes the graph with a specified number of
vertices.
o addEdge(): Adds an edge between two vertices in the adjacency list
for an undirected graph.

4. Stack Operations:
o push(): Adds a vertex to the top of the stack.
o pop(): Removes the top vertex from the stack.
o isEmptyStack(): Checks whether the stack is empty.

Example Output:

Enter the number of vertices: 4

Enter the number of edges: 4


Enter edge (source and destination): 0 1

Enter edge (source and destination): 0 2

Enter edge (source and destination): 1 2

Enter edge (source and destination): 1 3

Enter the starting vertex: 0

DFT (Adjacency List): 0 2 1 3

In this example:

 The graph has 4 vertices and 4 edges.


 The depth-first traversal starting from vertex 0 explores the vertices in the
order 0 -> 2 -> 1 -> 3.

You might also like