0% found this document useful (0 votes)
44 views25 pages

Dsa Extra Program

The document discusses implementing various sorting algorithms like selection sort, bubble sort, insertion sort, merge sort, quick sort and heap sort using arrays as data structures. It also discusses implementing linear search, binary search and hashing based search on arrays. Further, it discusses creating a graph and performing depth first search (DFS) and breadth first search (BFS) traversals on the graph. Code implementations with explanations are provided for each algorithm.

Uploaded by

Ansh Balgotra
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)
44 views25 pages

Dsa Extra Program

The document discusses implementing various sorting algorithms like selection sort, bubble sort, insertion sort, merge sort, quick sort and heap sort using arrays as data structures. It also discusses implementing linear search, binary search and hashing based search on arrays. Further, it discusses creating a graph and performing depth first search (DFS) and breadth first search (BFS) traversals on the graph. Code implementations with explanations are provided for each algorithm.

Uploaded by

Ansh Balgotra
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/ 25

PROGRAM-11

AIM: Implement Selection Sort, Bubble Sort, Insertion sort, Merge sort, Quick
sort, and Heap Sort using array as a data structure.
THEORY:
CODE:
#include <stdio.h>
// Function to swap two elements
void swap(int* a, int* b) {
int t = *a;
*a = *b;
*b = t;
}
// Function to perform Selection Sort
void selectionSort(int arr[], int n) {
int i, j, minIndex, temp;
for (i = 0; i < n - 1; i++) {
minIndex = i;
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
// Function to perform Bubble Sort
void bubbleSort(int arr[], int n) {
int i, j, temp;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
// Function to perform Insertion Sort
void insertionSort(int arr[], int n) {
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
// Function to merge two subarrays of arr[]
void merge(int arr[], int l, int m, int r) {
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int L[n1], R[n2];
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];
i = 0;
j = 0;
k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
// Function to perform Merge Sort
void mergeSort(int arr[], int l, int r) {
if (l < r) {
int m = l + (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
// Function to partition the array and return the pivot index
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = (low - 1);
for (int j = low; j <= high - 1; j++) {
if (arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
void quickSort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
void heapify(int arr[], int n, int i) {
int largest = i; // Initialize largest as root
int left = 2 * i + 1; // left = 2*i + 1
int right = 2 * i + 2; // 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]);
heapify(arr, n, largest);
}
}
void heapSort(int arr[], int n) {
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
for (int i = n - 1; i > 0; i--) {
// Move current root to end
swap(&arr[0], &arr[i]);
heapify(arr, i, 0);
}
}
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main() {
printf(“ANSH BALGOTRA\n”);
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: \n");
printArray(arr, n);
selectionSort(arr, n);
printf("Selection Sort: \n");
printArray(arr, n);
int resetArr[] = {64, 25, 12, 22, 11};
bubbleSort(resetArr, n);
printf("Bubble Sort: \n");
printArray(resetArr, n);
// Reset array
int resetArr2[] = {64, 25, 12, 22, 11};
// Insertion Sort
insertionSort(resetArr2, n);
printf("Insertion Sort: \n");
printArray(resetArr2, n);
// Reset array
int resetArr3[] = {64, 25, 12, 22, 11};
// Merge Sort
mergeSort(resetArr3, 0, n - 1);
printf("Merge Sort: \n");
printArray(resetArr3, n);
return 0;}
OUTPUT:
PROGRAM-12
AIM:Perform Linear Search and Binary Search on an array.
THEORY:
CODE:

#include <stdio.h>
int linearSearch(int arr[], int n, int key) {
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
return i; // Element found, return index
}
}
return -1; // Element not found
}
int binarySearch(int arr[], int low, int high, int key) {
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == key) {
return mid; // Element found, return index
}
if (arr[mid] < key) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1; // Element not found
}
int main() {
printf(“ANSH BALGOTRA\n”);
int n;
printf("Enter the size of the array: ");
scanf("%d", &n);
int arr[n];
printf("Enter the elements of the array:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
int key;
printf("Enter the element to search: ");
scanf("%d", &key);
int linearResult = linearSearch(arr, n, key);
if (linearResult != -1) {
printf("Linear Search: Element found at position %d\n", linearResult + 1);
} else {
printf("Linear Search: Element not found\n");
}
int binaryResult = binarySearch(arr, 0, n - 1, key);
if (binaryResult != -1) {
printf("Binary Search: Element found at position %d\n", binaryResult + 1);
} else {
printf("Binary Search: Element not found\n");
}

return 0;
OUTPUT:
PROGRAM-13
AIM: Implement the searching using hashing method.
THEORY:
CODE:
#include <stdio.h>
#define SIZE 10
int hashFunction(int key) {
return key % SIZE;
}
int linearProbe(int hashIndex, int attempt) {
return (hashIndex + attempt) % SIZE;
}
void insert(int hashTable[], int key) {
int hashIndex = hashFunction(key);
int index = hashIndex;
int attempt = 0;
while (hashTable[index] != -1) {
attempt++;
index = linearProbe(hashIndex, attempt);
}
hashTable[index] = key;
}
int search(int hashTable[], int key) {
int hashIndex = hashFunction(key);
int index = hashIndex;
int attempt = 0;
while (hashTable[index] != key && hashTable[index] != -1) {
attempt++;
index = linearProbe(hashIndex, attempt);
}
if (hashTable[index] == key) {
return index;
} else {
return -1;
}
}
void displayHashTable(int hashTable[]) {
printf("Hash Table:\n");
for (int i = 0; i < SIZE; i++) {
printf("%d: %d\n", i, hashTable[i]);
}}
int main() {
printf(“ANSH BALGOTRA\n”);
int hashTable[SIZE];
for (int i = 0; i < SIZE; i++) {
hashTable[i] = -1; }
insert(hashTable, 5);
insert(hashTable, 25);
insert(hashTable, 15);
insert(hashTable, 35);
displayHashTable(hashTable);
int keyToSearch = 15;
int searchResult = search(hashTable, keyToSearch);
if (searchResult != -1) {
printf("Element %d found at position %d\n", keyToSearch, searchResult);
} else {
printf("Element %d not found\n", keyToSearch);}
return 0;}
OUTPUT:

PROGRAM-14
AIM:Create a graph and perform DFS and BFS traversals.
THEORY:
CODE:
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTICES 10
struct Graph {
int vertices;
int** adjMatrix;
};
struct Queue {
int front, rear, capacity;
int* array;
};
struct Graph* createGraph(int vertices) {
struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
graph->vertices = vertices;
graph->adjMatrix = (int**)malloc(vertices * sizeof(int*));
for (int i = 0; i < vertices; i++) {
graph->adjMatrix[i] = (int*)calloc(vertices, sizeof(int));
}
return graph;
}
struct Queue* createQueue(int capacity) {
struct Queue* queue = (struct Queue*)malloc(sizeof(struct Queue));
queue->front = queue->rear = -1;
queue->capacity = capacity;
queue->array = (int*)malloc(capacity * sizeof(int));
return queue;
}
int isEmpty(struct Queue* queue) {
return queue->front == -1;
}
void enqueue(struct Queue* queue, int item) {
if (queue->rear == queue->capacity - 1) {
printf("Queue overflow\n");
return;
}
if (queue->front == -1) {
queue->front = 0;
}
queue->rear++;
queue->array[queue->rear] = item;
}
int dequeue(struct Queue* queue) {
if (isEmpty(queue)) {
printf("Queue underflow\n");
return -1;
}
int item = queue->array[queue->front];
queue->front++;
if (queue->front > queue->rear) {
queue->front = queue->rear = -1;
}
return item;
}
void addEdge(struct Graph* graph, int src, int dest) {
graph->adjMatrix[src][dest] = 1;
graph->adjMatrix[dest][src] = 1;
}
void dfsTraversal(struct Graph* graph, int vertex, int visited[]) {
printf("%d ", vertex);
visited[vertex] = 1;
for (int i = 0; i < graph->vertices; i++) {
if (graph->adjMatrix[vertex][i] == 1 && !visited[i]) {
dfsTraversal(graph, i, visited);
}
}
}
void dfs(struct Graph* graph, int startVertex) {
int visited[MAX_VERTICES] = {0};
printf("DFS Traversal: ");
dfsTraversal(graph, startVertex, visited);
printf("\n");
}
void bfs(struct Graph* graph, int startVertex) {
int visited[MAX_VERTICES] = {0};
struct Queue* queue = createQueue(MAX_VERTICES);
printf("BFS Traversal: ");
visited[startVertex] = 1;
enqueue(queue, startVertex);
while (!isEmpty(queue)) {
int vertex = dequeue(queue);
printf("%d ", vertex);
for (int i = 0; i < graph->vertices; i++) {
if (graph->adjMatrix[vertex][i] == 1 && !visited[i]) {
visited[i] = 1;
enqueue(queue, i);
}
}
}
printf("\n");
}
int main() {
printf(“ANSH BALGOTRA\n”);
int vertices = 6;
struct Graph* graph = createGraph(vertices);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 3);
addEdge(graph, 1, 4);
addEdge(graph, 2, 5);
int startVertex = 0;
dfs(graph, startVertex);
bfs(graph, startVertex);
return 0;
}
OUTPUT:
PROGRAM-15
AIM: Implement insertion, deletion and display in a AVL tree.
THEORY:
CODE:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int key;
struct Node* left;
struct Node* right;
int height;
};
int height(struct Node* node) {
if (node == NULL)
return 0;
return node->height;
}
int max(int a, int b) {
return (a > b) ? a : b;
}
struct Node* newNode(int key) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->key = key;
node->left = node->right = NULL;
node->height = 1;
return node;
}
struct Node* rightRotate(struct Node* y) {
struct Node* x = y->left;
struct Node* T2 = x->right;
x->right = y;
y->left = T2;
y->height = max(height(y->left), height(y->right)) + 1;
x->height = max(height(x->left), height(x->right)) + 1;
return x;
}
struct Node* leftRotate(struct Node* x) {
struct Node* y = x->right;
struct Node* T2 = y->left;
y->left = x;
x->right = T2;
x->height = max(height(x->left), height(x->right)) + 1;
y->height = max(height(y->left), height(y->right)) + 1;
return y;
}
int getBalance(struct Node* node) {
if (node == NULL)
return 0;
return height(node->left) - height(node->right);
}
struct Node* insert(struct Node* node, int key) {
if (node == NULL)
return newNode(key);
if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);
else // Duplicate keys are not allowed
return node;
node->height = 1 + max(height(node->left), height(node->right));
int balance = getBalance(node);
if (balance > 1 && key < node->left->key)
return rightRotate(node);
if (balance < -1 && key > node->right->key)
return leftRotate(node);
if (balance > 1 && key > node->left->key) {
node->left = leftRotate(node->left);
return rightRotate(node);
}
if (balance < -1 && key < node->right->key) {
node->right = rightRotate(node->right);
return leftRotate(node);
}
return node;
}
struct Node* minValueNode(struct Node* node) {
struct Node* current = node;
while (current->left != NULL)
current = current->left;
return current;
}
struct Node* deleteNode(struct Node* root, int key) {
if (root == NULL)
return root;
if (key < root->key)
root->left = deleteNode(root->left, key);
else if (key > root->key)
root->right = deleteNode(root->right, key);
else {
if ((root->left == NULL) || (root->right == NULL)) {
struct Node* temp = root->left ? root->left : root->right;
if (temp == NULL) {
temp = root;
root = NULL;
} else
*root = *temp;
free(temp);
} else {
struct Node* temp = minValueNode(root->right);
root->key = temp->key;
root->right = deleteNode(root->right, temp->key);
}
}
if (root == NULL)
return root;
root->height = 1 + max(height(root->left), height(root->right));
int balance = getBalance(root);
if (balance > 1 && getBalance(root->left) >= 0)
return rightRotate(root);
if (balance > 1 && getBalance(root->left) < 0) {
root->left = leftRotate(root->left);
return rightRotate(root);
}
if (balance < -1 && getBalance(root->right) <= 0)
return leftRotate(root);
if (balance < -1 && getBalance(root->right) > 0) {
root->right = rightRotate(root->right);
return leftRotate(root);
}
return root;
}
void inOrder(struct Node* root) {
if (root != NULL) {
inOrder(root->left);
printf("%d ", root->key);
inOrder(root->right);
}
}
int main() {
printf(“ANSH BALGOTRA\n”);
struct Node* root = NULL;
root = insert(root, 10);
root = insert(root, 20);
root = insert(root, 30);
root = insert(root, 40);
root = insert(root, 50);
printf("AVL Tree after insertions: ");
inOrder(root);
printf("\n");
root = deleteNode(root, 20);
root = deleteNode(root, 30);
printf("AVL Tree after deletions: ");
inOrder(root);
printf("\n");
return 0;
}

OUTPUT:

PROGRAM-16
AIM: Write a program to find minimum spanning tree.
THEORY:
CODE:
#include <stdio.h>
#include <stdlib.h>
struct Edge {
int src, dest, weight;
};
struct Subset {
int parent, rank;
};
int find(struct Subset subsets[], int i) {
if (subsets[i].parent != i)
subsets[i].parent = find(subsets, subsets[i].parent);
return subsets[i].parent;
}
void unionSets(struct Subset subsets[], int x, int y) {
int xroot = find(subsets, x);
int yroot = find(subsets, y);
if (subsets[xroot].rank < subsets[yroot].rank)
subsets[xroot].parent = yroot;
else if (subsets[xroot].rank > subsets[yroot].rank)
subsets[yroot].parent = xroot;
else {
subsets[yroot].parent = xroot;
subsets[xroot].rank++;
}
}
int compareEdges(const void* a, const void* b) {
return ((struct Edge*)a)->weight - ((struct Edge*)b)->weight;
}
void kruskal(struct Edge edges[], int V, int E) {
struct Subset* subsets = (struct Subset*)malloc(V * sizeof(struct Subset));
for (int i = 0; i < V; i++) {
subsets[i].parent = i;
subsets[i].rank = 0;
}
qsort(edges, E, sizeof(edges[0]), compareEdges);
struct Edge result[V - 1];
int i = 0, e = 0;
while (e < V - 1 && i < E) {
struct Edge nextEdge = edges[i++];
int x = find(subsets, nextEdge.src);
int y = find(subsets, nextEdge.dest);
if (x != y) {
result[e++] = nextEdge;
unionSets(subsets, x, y);
}
}
printf("Minimum Spanning Tree:\n");
for (int j = 0; j < e; j++) {
printf("%d - %d : %d\n", result[j].src, result[j].dest, result[j].weight);
}
free(subsets);
}
int main() {
printf(“ANSH BALGOTRA\n”);
int V = 4; // Number of vertices
int E = 5; // Number of edges
// Edges and their weights
struct Edge edges[] = {
{0, 1, 10},
{0, 2, 6},
{0, 3, 5},
{1, 3, 15},
{2, 3, 4},
};

// Find and print the minimum spanning tree


kruskal(edges, V, E);
return 0;
}
OUTPUT:
PROGRAM-17
AIM: Write a program to implement Dijkstra’s Shortest Path algorithm.
THEORY:
CODE:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define V 6 // Number of vertices
int minDistance(int dist[], int sptSet[]) {
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++) {
if (!sptSet[v] && dist[v] <= min) {
min = dist[v];
min_index = v;
}
}
return min_index;
}
void printSolution(int dist[]) {
printf("Vertex \t Distance from Source\n");
for (int i = 0; i < V; i++)
printf("%d \t %d\n", i, dist[i]);
}
void dijkstra(int graph[V][V], int src) {
int dist[V]; // The output array dist[i] holds the shortest distance from src to i
int sptSet[V]; // sptSet[i] is true if vertex i is included in the shortest path tree
for (int i = 0; i < V; i++) {
dist[i] = INT_MAX;
sptSet[i] = 0;
}
dist[src] = 0;
for (int count = 0; count < V - 1; count++) {
// Pick the minimum distance vertex from the set of vertices not yet
processed
int u = minDistance(dist, sptSet);
// Mark the picked vertex as processed
sptSet[u] = 1;
// Update dist value of the adjacent vertices of the picked vertex
for (int v = 0; v < V; v++) {
if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX &&
dist[u] + graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
}
}
}
printSolution(dist);
}
int main() {
printf(“ANSH BALGOTRA\n”);
int graph[V][V] = {
{0, 2, 0, 1, 0, 0},
{2, 0, 4, 0, 3, 0},
{0, 4, 0, 5, 0, 0},
{1, 0, 5, 0, 6, 2},
{0, 3, 0, 6, 0, 7},
{0, 0, 0, 2, 7, 0}
};
dijkstra(graph, 0);
return 0;
}
OUTPUT:

You might also like