Professional Documents
Culture Documents
DAA Practical-1
DAA Practical-1
return (i + 1);
}
int main()
{
int a[100], n, i;
printf("Enter the number of elements of array upto 100:");
scanf("%d", &n);
quickSort(a, 0, n-1);
printf("Sorted Array:\n");
for(int i=0; i<n; i++)
{
printf("%d ", a[i]);
}
return 0;
}
Output
2. Computing best, average, and worst-case time complexity of
various sorting techniques.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void Exch(int *p, int *q)
{
int temp = *p;
*p = *q;
*q = temp;
}
void QuickSort(int a[], int low, int high)
{
int i, j, key, k;
if (low >= high)
return;
key = low;
i = low + 1;
j = high;
while (i <= j)
{
while (a[i] <= a[key])
i = i + 1;
while (a[j] > a[key])
j = j - 1;
if (i < j)
Exch(&a[i], &a[j]);
}
Exch(&a[j], &a[key]);
QuickSort(a, low, j - 1);
QuickSort(a, j + 1, high);
}
void main()
{
int n, a[1000], k;
clock_t st, et;
double ts;
printf("\n Enter How many Numbers: ");
scanf("%d", &n);
printf("\nThe Random Numbers are:\n");
for (k = 1; k <= n; k++)
{
a[k] = rand();
printf("%d\t", a[k]);
}
st = clock();
QuickSort(a, 1, n);
et = clock();
ts = (double)(et - st) / CLOCKS_PER_SEC;
printf("\nSorted Numbers are: \n ");
for (k = 1; k <= n; k++)
printf("%d\t", a[k]);
printf("\nThe time taken is %e", ts);
}
Output:
3. Performance analysis of different internal and external sorting
algorithms with different type of data set.
External Sorting Algorithm: Merge Sort
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
void Merge(int a[], int low, int mid, int high)
{
int i, j, k, b[20];
i = low;
j = mid + 1;
k = low;
while (i <= mid && j <= high)
{
if (a[i] <= a[j])
b[k++] = a[i++];
else
b[k++] = a[j++];
}
while (i <= mid)
b[k++] = a[i++];
while (j <= high)
b[k++] = a[j++];
for (k = low; k <= high; k++)
a[k] = b[k];
}
void MergeSort(int a[], int low, int high)
{
int mid;
if (low >= high)
return;
mid = (low + high) / 2;
MergeSort(a, low, mid);
MergeSort(a, mid + 1, high);
Merge(a, low, mid, high);
}
void main()
{
int n, a[2000], k;
clock_t st, et;
double ts;
printf("\n Enter How many Numbers:");
scanf("%d", &n);
printf("\nThe Random Numbers are:\n");
for (k = 1; k <= n; k++)
{
a[k] = rand();
printf("%d\t", a[k]);
}
st = clock();
MergeSort(a, 1, n);
et = clock();
ts = (double)(et - st) / CLOCKS_PER_SEC;
printf("\n Sorted Numbers are : \n ");
for (k = 1; k <= n; k++)
printf("%d\t", a[k]);
printf("\nThe time taken is %e", ts);
}
Output
Internal Sorting Algorithm: Insertion Sort
#include <math.h>
#include <time.h>
#include <stdio.h>
int main()
{
int arr[] = { 12, 11, 13, 5, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
clock_t st, et;
double ts;
return 0;
}
Output
4. Use of divide and conquer technique to solve some problem
that uses two different algorithms for solving
small problem
Searching Algorithm (Sequential technique): Linear Search
#include <stdio.h>
int main() {
int array[] = {2, 4, 0, 1, 9};
int x = 1;
int n = sizeof(array) / sizeof(array[0]);
if (array[mid] == x)
return mid;
if (array[mid] < x)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
int main(void) {
int array[] = {3, 4, 5, 6, 7, 8, 9};
int n = sizeof(array) / sizeof(array[0]);
int x = 4;
int result = binarySearch(array, x, 0, n - 1);
printf("The array is: \n");
for (int i = 0; i < 5; i++)
{
printf("%d, ", array[i]);
}
printf("\nElement to be found: %d", x);
if (result == -1)
printf("\nNot found");
else
printf("\nElement is found at index %d", result);
return 0;
}
Output
5. Implementation of different basic computing algorithms like
AVL tree
#include <stdio.h>
#include <stdlib.h>
// Create Node
struct Node {
int key;
struct Node *left;
struct Node *right;
int height;
};
// Calculate height
int height(struct Node *N) {
if (N == NULL)
return 0;
return N->height;
}
// Create a node
struct Node *newNode(int key) {
struct Node *node = (struct Node *)
malloc(sizeof(struct Node));
node->key = key;
node->left = NULL;
node->right = NULL;
node->height = 1;
return (node);
}
// Right rotate
struct Node *rightRotate(struct Node *y) {
struct Node *x = y->left;
struct Node *T2 = x->right;
x->right = y;
y->left = T2;
return x;
}
// Left rotate
struct Node *leftRotate(struct Node *x) {
struct Node *y = x->right;
struct Node *T2 = y->left;
y->left = x;
x->right = T2;
return y;
}
// Insert node
struct Node *insertNode(struct Node *node, int key) {
// Find the correct position to insertNode the node and insertNode
it
if (node == NULL)
return (newNode(key));
if (key < node->key)
node->left = insertNode(node->left, key);
else if (key > node->key)
node->right = insertNode(node->right, key);
else
return node;
return node;
}
// Delete a nodes
struct Node *deleteNode(struct Node *root, int key) {
// Find the node and delete it
if (root == NULL)
return root;
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;
if (root == NULL)
return root;
return root;
}
int main() {
struct Node *root = NULL;
return 0;
}
Output
6. Consider the problem of eight queens on an (8x8) chessboard.
Two queens are said to attack each other if they
are on the same row, column, or diagonal. Write a program that
implements backtracking algorithm to solve
the problem i.e. place eight non-attacking queens on the board.
#define N 8
#include <stdbool.h>
#include <stdio.h>
return true;
}
board[i][col] = 0;
}
}
return false;
}
bool solveNQ()
{
int board[N][N] = { { 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 0 } };
if (solveNQUtil(board, 0) == false) {
printf("Solution does not exist");
return false;
}
printSolution(board);
return true;
}
int main()
{
solveNQ();
return 0;
}
Output
7. Write a program to find the strongly connected components
in a digraph
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_SIZE 5
struct Graph *graph;
struct Graph *gr;
int stack[MAX_SIZE], top;
struct adj_list_node
{
int dest;
int weight;
struct adj_list_node *next;
};
struct adj_list
{
struct adj_list_node *head;
};
struct Graph
{
int V;
int *visited;
struct adj_list *array;
};
struct adj_list_node *new_adj_list_node(int dest, int weight)
{
struct adj_list_node *newNode = (struct adj_list_node
*)malloc(sizeof(struct adj_list_node));
newNode->dest = dest;
newNode->weight = weight;
newNode->next = NULL;
return newNode;
}
struct Graph *create_graph(int V)
{
struct Graph *graph = (struct Graph *)malloc(sizeof(struct Graph));
graph->V = V;
graph->array = (struct adj_list *)malloc(V * sizeof(struct adj_list));
int i;
for (i = 0; i < V; ++i)
graph->array[i].head = NULL;
return graph;
}
void add_edge(struct Graph *graph, struct Graph *gr, int src, int
dest, int weight)
{
struct adj_list_node *newNode = new_adj_list_node(dest, weight);
newNode->next = graph->array[src].head;
graph->array[src].head = newNode;
get_transpose(gr, src, dest, weight);
}
void print_graph(struct Graph *graph1)
{
int v;
for (v = 0; v < graph1->V; ++v)
{
struct adj_list_node *temp = graph1->array[v].head;
while (temp)
{
printf("(%d -> %d(%d))\t", v, temp->dest, temp->weight);
temp = temp->next;
}
}
}
void set_fill_order(struct Graph *graph, int v, bool visited[], int
*stack)
{
visited[v] = true;
int i = 0;
struct adj_list_node *temp = graph->array[v].head;
while (temp)
{
if (!visited[temp->dest])
{
set_fill_order(graph, temp->dest, visited, stack);
}
temp = temp->next;
}
push(v);
}
void dfs_recursive(struct Graph *gr, int v, bool visited[])
{
visited[v] = true;
printf("%d ", v);
struct adj_list_node *temp = gr->array[v].head;
while (temp)
{
if (!visited[temp->dest])
{
dfs_recursive(gr, temp->dest, visited);
}
temp = temp->next;
}
}
void get_transpose(struct Graph *gr, int src, int dest, int weight)
{
struct adj_list_node *newNode = new_adj_list_node(src, weight);
newNode->next = gr->array[dest].head;
gr->array[dest].head = newNode;
}
void strongly_connected_components(struct Graph *graph, struct
Graph *gr, int V)
{
bool visited[V];
for (int i = 0; i < V; i++)
visited[i] = false;
for (int i = 0; i < V; i++)
{
if (visited[i] == false)
{
set_fill_order(graph, i, visited, stack);
}
}
int count = 1;
for (int i = 0; i < V; i++)
visited[i] = false;
while (top != -1)
{
int v = stack[top];
pop();
if (visited[v] == false)
{
printf("Strongly connected component %d: \n", count++);
dfs_recursive(gr, v, visited);
printf("\n");
}
}
}
void push(int x)
{
if (top >= MAX_SIZE - 1)
{
printf("\n\tSTACK is over flow");
}
else
{
top++;
stack[top] = x;
}
}
void pop()
{
if (top <= -1)
{
printf("\n\t Stack is under flow");
}
else
{
top--;
}
}
int main()
{
top = -1;
int v = 5;
struct Graph *graph = create_graph(v);
struct Graph *gr = create_graph(v);
add_edge(graph, gr, 1, 0, 2);
add_edge(graph, gr, 0, 2, 2);
add_edge(graph, gr, 2, 1, 2);
add_edge(graph, gr, 0, 3, 2);
add_edge(graph, gr, 3, 4, 2);
strongly_connected_components(graph, gr, v);
return 0;
}
Output
8. Write a program to implement file compression (and un-
compression) using Huffman’s algorithm.
#include <stdio.h>
#include <stdlib.h>
#define MAX_TREE_HT 50
struct MinHNode
{
char item;
unsigned freq;
struct MinHNode *left, *right;
};
struct MinHeap
{
unsigned size;
unsigned capacity;
struct MinHNode **array;
};
return temp;
}
minHeap->size = 0;
minHeap->capacity = capacity;
if (smallest != idx)
{
swapMinHNode(&minHeap->array[smallest], &minHeap-
>array[idx]);
minHeapify(minHeap, smallest);
}
}
--minHeap->size;
minHeapify(minHeap, 0);
return temp;
}
minHeap->size = size;
buildMinHeap(minHeap);
return minHeap;
}
while (!checkSizeOne(minHeap))
{
left = extractMin(minHeap);
right = extractMin(minHeap);
top->left = left;
top->right = right;
insertMinHeap(minHeap, top);
}
return extractMin(minHeap);
}
void printHCodes(struct MinHNode *root, int arr[], int top)
{
if (root->left)
{
arr[top] = 0;
printHCodes(root->left, arr, top + 1);
}
if (root->right)
{
arr[top] = 1;
printHCodes(root->right, arr, top + 1);
}
if (isLeaf(root))
{
printf(" %c | ", root->item);
printArray(arr, top);
}
}
printf("\n");
}
int main()
{
char arr[] = {'A', 'B', 'C', 'D'};
int freq[] = {5, 1, 6, 3};
#include <stdio.h>
#define nV 4
int main() {
int graph[nV][nV] = {{0, 3, INF, 5},
{2, 0, INF, 4},
{INF, 1, 0, INF},
{INF, INF, 2, 0}};
floydWarshall(graph);
}
Output
10. Write a program to solve 0/1 knapsack problem using the
following:
a) Greedy algorithm
#include<stdio.h>
int max(int a, int b) {
if(a>b){
return a;
} else {
return b;
}
}
int knapsack(int W, int wt[], int val[], int n) {
int i, w;
int knap[n+1][W+1];
for (i = 0; i <= n; i++) {
for (w = 0; w <= W; w++) {
if (i==0 || w==0)
knap[i][w] = 0;
else if (wt[i-1] <= w)
knap[i][w] = max(val[i-1] + knap[i-1][w-wt[i-1]], knap[i-1][w]);
else
knap[i][w] = knap[i-1][w];
}
}
return knap[n][W];
}
int main() {
int val[] = {20, 25, 40};
int wt[] = {25, 20, 30};
int W = 50;
int n = sizeof(val)/sizeof(val[0]);
printf("The solution is : %d", knapsack(W, wt, val, n));
return 0;
}
Output
b) Dynamic Programming
#include <stdio.h>
#include <conio.h>
int w[10], p[10], v[10][10], n, i, j, cap, x[10] = {0};
int max(int i, int j)
{
return ((i > j) ? i : j);
}
int knap(int i, int j)
{
int value;
if (v[i][j] < 0)
{
if (j < w[i])
value = knap(i - 1, j);
else
value = max(knap(i - 1, j), p[i] + knap(i - 1, j - w[i]));
v[i][j] = value;
}
return (v[i][j]);
}
void main()
{
int profit, count = 0;
//clrscr();
printf("\nEnter the number of elements\n");
scanf("%d", &n);
printf("Enter the profit and weights of the elements\n");
for (i = 1; i <= n; i++)
{
printf("For item no %d\n", i);
scanf("%d%d", &p[i], &w[i]);
}
printf("\nEnter the capacity \n");
scanf("%d", &cap);
for (i = 0; i <= n; i++)
for (j = 0; j <= cap; j++)
if ((i == 0) || (j == 0))
v[i][j] = 0;
else
v[i][j] = -1;
profit = knap(n, cap);
i = n;
j = cap;
while (j != 0 && i != 0)
{
if (v[i][j] != v[i - 1][j])
{
x[i] = 1;
j = j - w[i];
i--;
}
else
i--;
}
printf("Items included are\n");
printf("Sl.no\tweight\tprofit\n");
for (i = 1; i <= n; i++)
if (x[i])
printf("%d\t%d\t%d\n", ++count, w[i], p[i]);
printf("Total profit = %d\n", profit);
getch();
}
Output
c) Backtracking Algorithm
#include <stdio.h>
#define MAX 20
float final_profit;
int w[MAX];
int p[MAX];
int n, m;
int temp[MAX], x[MAX];
float final_wt;
void main()
{
int i;
printf("\n Enter number of Objects you want:");
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
printf("\n Enter Weight and value for object%d:", i);
scanf("%3d %3d", &w[i], &p[i]);
}
printf("\n Enter Capacity of Knapsack:");
scanf("%d", &m);
printf("\n Weight\tProfit");
BackTracking(1, 0, 0);
typedef enum
{
NO,
YES
} BOOL;
int N;
int vals[100];
int wts[100];
int cap = 0;
int mval = 0;
int main()
{
int keys[] = {10, 12, 20};
int freq[] = {34, 8, 50};
int n = sizeof(keys)/sizeof(keys[0]);
printf("Cost of Optimal BST is %d ",
optimalSearchTree(keys, freq, n));
return 0;
}
Output
12. Write a program for solving traveling sales persons problem
using the following:
a) Dynamic programming algorithm
#include <iostream>
const int n = 4;
if (memo[i][mask] != 0)
return memo[i][mask];
int main()
{
int ans = MAX;
for (int i = 1; i <= n; i++)
ans = std::min(ans, fun(i, (1 << (n + 1)) - 1) + dist[i][1]);
return 0;
}
Output
b) Backtracking algorithm
#include <bits/stdc++.h>
using namespace std;
#define V 4
v[i] = true;
tsp(graph, v, i, n, count + 1,
cost + graph[currPos][i], ans);
v[i] = false;
}
}
};
int main()
{
int n = 4;
int graph[][V] = {
{0, 10, 15, 20},
{10, 0, 35, 25},
{15, 35, 0, 30},
{20, 25, 30, 0}};
vector<bool> v(n);
for (int i = 0; i < n; i++)
v[i] = false;
v[0] = true;
int ans = INT_MAX;
tsp(graph, v, 0, n, 1, 0, ans);
return 0;
}
Output
c) Branch and bound
#include <bits/stdc++.h>
using namespace std;
const int N = 4;
int final_path[N+1];
bool visited[N];
if (level==1)
curr_bound -= ((firstMin(adj, curr_path[level-1]) +
firstMin(adj, i))/2);
else
curr_bound -= ((secondMin(adj, curr_path[level-1])
+
firstMin(adj, i))/2);
curr_weight -= adj[curr_path[level-1]][i];
curr_bound = temp;
int curr_bound = 0;
memset(curr_path, -1, sizeof(curr_path));
memset(visited, 0, sizeof(curr_path));
visited[0] = true;
curr_path[0] = 0;
int main()
{
int adj[N][N] = { {0, 10, 15, 20},
{10, 0, 35, 25},
{15, 35, 0, 30},
{20, 25, 30, 0}
};
TSP(adj);
return 0;
}
Output