Sei sulla pagina 1di 84

BINARY TREE TRAVERSAL

#include <stdio.h> #include <stdlib.h> #include <conio.h> /* tree node */ struct tnode { int data; /* data */ int count; /* number of occurrences */ struct tnode *left; /* left child */ struct tnode *right; /* right child */ }; /* talloc: make a tnode */ static struct tnode *talloc(void) { return (struct tnode *)malloc(sizeof(struct tnode)); } /* insert a tnode into the binary tree */ static struct tnode *tnode_insert(struct tnode *p, int value) { if (p == NULL) { /* a new element has arrived */ p = talloc(); /* make a new node */ p->data = value; p->count = 1; p->left = p->right = NULL; } else if (value == p->data) /* repeated value */ { /* when dupl i ca t i on i s al l owed, add i t in r igh t subtree */ p->count++; } else if (value < p->data) /* less than into left subtree */ { p->left = tnode_insert(p->left, value); } else if (value > p->data) /* greater than into right subtree */ { p->right = tnode_insert(p->right, value); } return p; } static struct tnode *tread(struct tnode *root) { int i, n, d; printf(" Enter number of nodes in Binary Tree : ");

scanf("%d", &n); for (i = 1; i <= n; i++) { printf(" Enter node %d : ", i); scanf("%d", &d); root = tnode_insert(root, d); } return root; } /* destroy the binary tree */ static void tflush(struct tnode *n) { if (n) { tflush(n->left); tflush(n->right); free(n); } } /* print in binary tree format */ static void tprint(struct tnode *root, int level) { int i; if (root == NULL) { return; } tprint(root->right, level+1); for (i = 0; i < level; i++) { printf(" "); } printf(" %d\n", root->data); tprint(root->left, level+1); } static void preorder(struct tnode *root) /* DLR */ { if (root) { printf("[%d] ", root->data); preorder(root->left);

preorder(root->right); } } static void inorder(struct tnode *root) /* LDR */ { if (root) { inorder(root->left); printf("[%d] ", root->data); inorder(root->right); } } static void postorder(struct tnode *root) /* LRD */ { if (root) { postorder(root->left); postorder(root->right); printf("[%d] ", root->data); } } static void levelorder(struct tnode *root) { struct tnode *queue[100] = { (struct tnode *)0 }; int size = 0; int qptr = 0; while (root) { printf("[%d] ", root->data); if (root->left) { queue[size++] = root->left; } if (root->right) { queue[size++] = root->right; } root = queue[qptr++]; } } int main() { struct tnode *root = NULL;

clrscr(); printf("\n Binary Tree Traversal \n\n"); root = tread(root); printf("\n Binary tree for the given data : \n"); tprint(root, 0); putchar('\n'); /* traversa l */ printf(" Preorder : "); preorder(root); printf("\n\n"); printf(" Inorder inorder(root); printf("\n\n"); : ");

printf(" Postorder : "); postorder(root); printf("\n\n"); printf(" Levelorder : "); levelorder(root); printf("\n\n"); t f l u sh ( roo t ) ; getch(); return 0; }

Output:

Binary Tree Traversal Enter number of nodes in Binary Tree : 11 Enter node 1 : 15 Enter node 2 : 6 Enter node 3 : 18 Enter node 4 : 3 Enter node 5 : 7 Enter node 6 : 17 Enter node 7 : 20 Enter node 8 : 2 Enter node 9 : 4 Enter node 10 : 13 Enter node 11 : 9 Binary tree for the given data : 20 18 17 15 13 9 7 6 4 3 2 Preorder : [15] [6] [3] [2] [4] [7] [13] [9] [18] [17] [20] Inorder : [2] [3] [4] [6] [7] [9] [13] [15] [17] [18] [20]

Postorder : [2] [4] [3] [9] [13] [7] [6] [17] [20] [18] [15] Levelorder : [15] [6] [18] [3] [7] [17] [20] [2] [4] [13] [9]

PRINTING NODE LEVEL BY LEVEL


#include <stdio.h> #include <stdlib.h> #include <conio.h> /* tree node */ struct tnode { int data; /* data */ int count; /* number of occurrences */ struct tnode *left; /* left child */ struct tnode *right; /* right child */ }; /* global variables */ static int g_currwidth = 0; static int g_maxwidth = 0; /* talloc: make a tnode */ static struct tnode *talloc(void) { return (struct tnode *)malloc(sizeof(struct tnode)); } /* insert a tnode into the binary tree */ static struct tnode *tnode_insert(struct tnode *p, int value) { if (p == NULL) { /* a new element has arrived */ p = talloc(); /* make a new node */ p->data = value; p->count = 1; p->left = p->right = NULL; } else if (value == p->data) /* repeated value */

{ /* when duplication is allowed, add it in right subtree */ p->count++; } else if (value < p->data) /* less than into left subtree */ { p->left = tnode_insert(p->left, value); } else if (value > p->data) /* greater than into right subtree */ { p->right = tnode_insert(p->right, value); } return p; }

static struct tnode *tread(struct tnode *root) { printf(" Enter number of nodes in Binary Tree: "); scanf("%d", &n); for (i=1; i<=n; i++) { printf(" Enter node %d: ", i); scanf("%d", &d); root = tnode_insert(root, d); } return root; } /* destroy the binary tree */ static void tflush(struct tnode *n) { if (n) { tflush(n->left); tflush(n->right); free(n); } } /* print in binary tree format */ static void tprint(struct tnode *root, int level) { int i; if (root == NULL)

{ return; } tprint(root->right, level+1); for (i = 0; i < level; i++) { printf(" "); } printf(" %d\n", root->data); tprint(root->left, level+1); } static void tprint_levelorder(struct tnode *p, int level) { if (p) { if (level == 1) /* root */ { printf("[%d] ", p->data); g_currwidth++; }

else if (level > 1) /* process the child first */ { tprint_levelorder(p->left, level-1); tprint_levelorder(p->right, level-1); } } } static int tmaxdepth(struct tnode* p) { if (p == NULL) { return 0; } else { /* compute depth of each subtree */ int ldepth = tmaxdepth(p->left); int rdepth = tmaxdepth(p->right); /* use the larger one */ return (ldepth > rdepth) ? (ldepth + 1) : (rdepth + 1); } }

/* maximum width of a binary tree/level with maximum number of element */ static int tmaxwidth(struct tnode* p) { int i, level; level = tmaxdepth(p); for (i = 1; i <= level; i++) { printf(" level %d : ", i); tprint_levelorder(p, i); /* elements in the level i */ putchar('\n'); if (g_currwidth > g_maxwidth) { g_maxwidth = g_currwidth; g_currwidth = 0; } } return g_maxwidth; } int main() { struct tnode *root = NULL; int depth, width; depth = 0; width = 0; clrscr(); printf("\n Printing the Binary Tree node details level wise \n\n"); root = tread(root); printf("\n Binary tree for the given data : \n"); tprint(root, 0); putchar('\n'); depth = tmaxdepth(root); printf("\n Depth of binary tree : %d \n\n", depth); /* print level by level */ width = tmaxwidth(root); printf("\n Max width of binary tree/level with max no. of elements : %d \n", width); tflush(root); getch(); return 0; }

Output: Printing the Binary Tree node details level wise Enter number of nodes in Binary Tree: 20 Enter node 1: 26 Enter node 2: 17 Enter node 3: 41 Enter node 4: 14 Enter node 5: 21 Enter node 6: 30 Enter node 7: 47 Enter node 8: 10 Enter node 9: 16 Enter node 10: 19 Enter node 11: 23 Enter node 12: 28 Enter node 13: 38 Enter node 14: 7 Enter node 15: 12 Enter node 16: 15 Enter node 17: 20 Enter node 18: 35 Enter node 19: 39 Enter node 20: 3 Binary tree for the given data : 47 41

39 38 35 30 28 26 23 21 20 19 17 16 15 14 12 10 7 3 Depth of binary tree : 6 level 1 : [26] level 2 : [17] [41] level 3 : [14] [21] [30] [47] level 4 : [10] [16] [19] [23] [28] [38] level 5 : [7] [12] [15] [20] [35] [39] level 6 : [3] Max width of binary tree/level with max no. of elements : 7

KRUSKAL ALGORITHM
#include <stdio.h> #include <stdlib.h> #include <conio.h> #define MAXV #define SETSZ 100 /* maximum number of vertices in graph */ 1000 /* disjoint set size */

typedef enum boolean /* boolean datatype */ { FALSE, TRUE } bool; /* graph related structures */ typedef struct edgenode_t { int y; /* adjancency info */ int weight; /* edge weight, if any */ struct edgenode_t *next; /* next edge in list */ } edgenode; typedef struct graph_t { edgenode *edges[MAXV+1]; /* adjacency info */

int degree[MAXV+1]; /* outdegree of each vertex */ int nvertices; /* number of vertices in the graph */ int nedges; /* number of edges in the graph */ int directed; /* is the graph directed? */ } graph; typedef struct edge_pair_t { int x, y; /* adjacency info */ int weight; /* edge weight, if any */ } edge_pair; /* disjoint set related structure */ typedef struct set_union_t { in t p[SETSZ+1]; /* parent element */ in t si ze [SETSZ+1]; /* number of elements in subtree i */ int n; /* number of elements in set */ } set_union; /***************************** graph ********* * * * * * * * * * * * * * * * * * * * * / static void init_graph(graph *g, bool directed) { int i; /* counter */ g->nvertices = 0; g->nedges = 0; g->directed = directed; for (i = 1; i <= MAXV; i++) { g->degree[i] = 0; g->edges[i] = NULL; } } static void insert_edge(graph *g, int x, int y, int w, bool directed) { edgenode *p; /* temporary pointer */ p = malloc(sizeof(edgenode)); /* allocate storage for edgenode */ p- >y = y; p->weight = w; p- >next = g- >edges[x] ; g->edges[x] = p; /* insert at head of list */ g->degree[x]++; if (directed == FALSE) { insert_edge(g, y, x, w, TRUE); }

else { g->nedges++; } } static void read_graph(graph *g, bool directed) { int i; /* counter */ int m; /* number of edges */ int x, y; /* vertices in edge (x,y) */ int w; /* weight(cost) */ init_graph(g, directed); printf(" Enter no. of vertices and edges: "); scanf ( "%d %d", &(g- >nvert i ces ) , &m); for ( i = 1; i <= m; i++) { printf(" Enter edge and cost: "); scanf("%d %d %d", &x, &y, &w); insert_edge(g, x, y, w, directed); } } static void print_graph(graph *g) { int i; /* counter */ edgenode *p; /* temporary pointer */ for (i = 1; i <= g->nvertices; i++) { printf("%2d : ", i); for (p = g->edges[i]; p != NULL; p = p->next) { printf(" %2d ( %2d )", p->y, p->weight); } putchar('\n'); } } static void del_graph(graph *g) { int i; /* counter */ edgenode *p, *q; /* temporary pointers */ for (i = 1; i <= g->nvertices; i++) { for (p = g->edges[i]; p != NULL; p = q) {

q = p->next; free(p); } g->edges[i] = NULL; } init_graph(g, FALSE); } /************************* disjoint set ******** ** * * * * * * * * * * * * * * * * / static void set_union_init(set_union *s, int n) { int i; /* counter */ for (i = 1; i <= n; i++) { s->p[i] = i; s->size[i] = 1; } s->n = n; } static int find(set_union *s, int x) { if (s->p[x] == x) { return(x); } else { return (find(s, s->p[x])); } } static void union_sets(set_union *s, int s1, int s2) { int r1, r2; /* roots of sets */ r1 = find(s, s1); r2 = find(s, s2); if (r1 == r2) { return; /* already in same set */ } if (s->size[r1] >= s->size[r2]) { s->size[r1] = s->size[r1] + s->size[r2]; s->p[r2] = r1; }

else { s->size[r2] = s->size[r1] + s->size[r2]; s->p[r1] = r2; } } static bool same_component(set_union *s, int s1, int s2) { return (find(s,s1) == find(s,s2)); } /******************* Kruskal algorithm for MST********* * * * * * * * * * * / static void to_edge_array(graph *g, edge_pair e[]) { int i, m; /* counters */ edgenode *p; /* temporary pointer */ m = 0; for (i = 1; i <= g->nvertices; i++) { p = g->edges[i]; while (p != NULL) { if (p->y > i) { e[m].x = i; e[m].y = p->y; e[m].weight = p- >weight; m = m+1; } p = p->next; } } } static int weight_compare(const void *x, const void *y) { edge_pair *lx, *ly; lx = (edge_pair *)x; ly = (edge_pair *)y; return ((lx->weight > ly->weight) ? 1 : \ (lx->weight < ly->weight) ? -1 : 0); } static void kruskal(graph *g) { int i; /* counter */

int tot; /* minimum cost */ set_union s; /* set union data structure */ edge_pair e[MAXV+1]; /* array of edges data structure */ set_union_init(&s, g->nvertices); to_edge_array(g, e); qsort((void *)&e, g->nedges, sizeof(edge_pair), weight_compare); for (i = 0, tot = 0; i < (g->nedges); i++) { if (!same_component(&s, e[i].x, e[i].y)) { printf(" edge (%d,%d) of weight %d in MST \n", e[ i ] . x , e[ i ] . y , e[ i ] .we ight ) ; tot += e[ i ] .we ight ; union_sets(&s, e[i].x, e[i].y); } } printf("\n Minimum cost: %d \n", tot); } int main() { graph g; clrscr(); printf("\n Minimum Spanning Tree using Kruskal Algorithm \n\n"); /* undirected */ read_graph(&g, FALSE); puts("\n Graph :"); print_graph(&g); puts("\n Applying Kruskal algorithm... ") ; kruskal(&g); del_graph(&g); getch( ) ; return 0; } Output: Minimum Spanning Tree using Kruskal Algorithm Enter Enter Enter Enter Enter no. of vertices and edge and cost: 1 4 edge and cost: 1 2 edge and cost: 2 3 edge and cost: 4 2 edges: 7 11 5 7 8 9

Enter Enter Enter Enter Enter Enter Enter

edge edge edge edge edge edge edge

and and and and and and and

cost: cost: cost: cost: cost: cost: cost:

4 2 5 4 6 7 6

5 5 3 6 5 5 7

15 7 5 6 8 9 11

Graph : 1: 2( 7) 2: 5( 7) 3: 5( 5) 4: 6( 6) 5: 7( 9) 6 : 7 ( 11 ) 7 : 6 ( 11 )

4( 5) 4( 9) 2( 8) 5 ( 15 ) 6( 8) 5( 8) 5( 9)

3( 8) 1( 7) 2( 9) 1( 5) 3 ( 5 ) 2 ( 7 ) 4 ( 15 ) 4( 6)

Applying Kruskal algorithm... edge (1,4) of weight 5 in MST edge (3,5) of weight 5 in MST edge (4,6) of weight 6 in MST edge (2,5) of weight 7 in MST edge (1,2) of weight 7 in MST edge (5,7) of weight 9 in MST Minimum cost: 39

FLOYD WARSHALL ALGORITHM


#include <stdio.h> #include <stdlib.h> #include <conio.h> #define MAXV #define INFINITE 100 /* maximum number of vertices in graph */ 9999

typedef enum boolean /* boolean datatype */ { FALSE, TRUE } bool; typedef struct graph_t { int weight[MAXV+1][MAXV+1]; /* adjacency/weight matrix */ int nvertices; /* number of vertices in the graph */ } graph; static void init_graph(graph *g) { int i, j; /* counters */ g->nvertices = 0; for (i = 1; i <= MAXV; i++) { for (j = 1; j <= MAXV; j++) { g->weight[i][j] = (i == j ? 0 : INFINITE); } } } static void read_graph(graph *g, bool directed) { int i; /* counter */ int m; /* number of edges */ int x, y, w; /* placeholder for edge and weight */ init_graph(g); printf(" Enter no. of vertices and edges : "); scanf ( "%d %d", &(g- >nvert i ces ) , &m); for ( i = 1; i <= m; i++) { printf(" Enter edge and cost : "); scanf("%d %d %d", &x, &y, &w); g->weight[x][y] = w; if (directed == FALSE) { g->weight[y][x] = w; } } } static void print_graph(graph *g) {

int i, j;

/* counters */

for (i = 1; i <= g->nvertices; i++) { printf("%2d : ", i); for (j = 1; j <= g->nvertices; j++) { if (g->weight[i][j] < INFINITE) { printf(" %2d ( %2d )",j, g->weight[i][j]); } } putchar('\n'); } } static void print_adjmatrix(graph *g) { int i, j; /* counters */ for (i = 1; i <= g->nvertices; i++) { printf("%2d : ",i); for (j = 1; j <= g->nvertices; j++) { printf(" %3d", g->weight[i][j]); } putchar('\n'); } } static void floyd(graph *g) { int i, j; /* dimension counters */ int k; /* intermediate vertex counter */ int thru_k; /* distance through vertex k */ for (k = 1; k <= g->nvertices; k++) { for (i = 1; i <= g->nvertices; i++) { for (j = 1; j <= g->nvertices; j++) { thru_k = g->weight[i][k] + g->weight[k][j]; if (thru_k < g->weight[i][j]) { g->weight[i][j] = thru_k; } }

} } } int main() { graph g; clrscr(); printf("\n All-Pairs Shortest Paths using Floyd-Warshall Algorithm \n\n"); /* directed */ read_graph(&g, TRUE); puts("\n Graph: "); print_graph(&g); puts("\n Applying Floyd-Warshall algorithm... ") ; floyd(&g); puts("\n Adjacent Matrix : "); print_adjmatrix(&g); puts( " \n Graph (a l l - pai rs shortest paths) : ") ; print_graph(&g); /* clean up */ init_graph(&g); getch(); return 0; }

Output: All-Pairs Shortest Paths using Floyd-Warshall Algorithm Enter Enter Enter Enter Enter Enter Enter Enter no. of vertices and edges : 5 7 edge and cost : 1 2 2 edge and cost : 1 5 4 edge and cost : 4 1 8 edge and cost : 5 4 7 edge and cost : 3 4 5 edge and cost : 3 5 1 edge and cost : 2 3 3 0 0 0 8 7 ) ) ) ) ) 2 3 4 4 5 ( ( ( ( ( 2 3 5 0 0 ) 5( 4) ) ) 5( 1) ) )

Graph: 1: 1( 2: 2( 3: 3( 4: 1( 5: 4(

Applying Floyd-Warshall algorithm... Adjacent Matrix : 1 : 0 2 5 10 2 : 16 0 3 8 3 : 13 15 0 5 4 : 8 10 13 0 5 : 15 17 20 7 4 4 1 12 0

Graph (all-pairs shortest paths) : 1 : 1 ( 0 ) 2 ( 2 ) 3 ( 5 ) 4 ( 10 ) 5 ( 4 ) 2 : 1 ( 16 ) 2 ( 0 ) 3 ( 3 ) 4 ( 8 ) 5 ( 4 ) 3 : 1 ( 13 ) 2 ( 15 ) 3 ( 0 ) 4 ( 5 ) 5 ( 1 ) 4 : 1 ( 8 ) 2 ( 10 ) 3 ( 13 ) 4 ( 0 ) 5 ( 12 ) 5 : 1 ( 15 ) 2 ( 17 ) 3 ( 20 ) 4 ( 7 ) 5 ( 0 )

TRAVELLING SALESMAN PROBLEM


#include <stdio.h> #include <conio.h> template <class T> void get2Darray(T ** &x, int rows, int cols) { x = new T * [rows]; for (int i = 0; i < rows; i++) { x[i] = new T[cols]; } } template <class T> void free2Darray(T ** &x, int rows) { for (int i = 0; i < rows; i++) { delete [] x[i]; } delete [] x; } template <class T> class tspclass { public: tspclass(int, T**, T, T); ~tspclass ( ) ; void backtrack(int i); void pr in t ( ) ; private: void swap(T& a, T& b); in t num, *ax, *bx; /* no of elements, actual route , best route */ T **ar, ac, bc, ne; /* adj matrix, actual cost, best cost, no edge */ }; template <class T> tspclass<T>::tspclass(int n, T** arr, T cost, T er) { num = n; ar = arr; ac = cost; bc = er; ne = er; ax = new in t [num+1];

bx = new int[num+1]; for (int i = 0; i <= num; i++) { ax[i] = i; } } template <class T> tspclass<T>::~tspclass() { delete[] ax; delete[] bx; } template <class T> void tspclass<T>::swap(T& a, T& b) { T tmp = a; a = b; b = tmp; } template <class T> void tspclass<T>::print() { if (bc != ne) { printf(" Optimal route for round-trip tour : \n"); printf(" %d", bx[1]); for (int i = 2; i <= num; i++) { printf(" -> %d", bx[i]); } printf(" -> %d", bx[1]); printf("\n\n At a cost of %d \n", bc); } else { printf(" Problem has no solution!\n"); } putchar('\n'); } template <class T> void tspclass<T>::backtrack(int i) { if (i == num) { if ((ar[ax[num-1]][ax[num]] != ne) && \ (ar[ax[num]][1] != ne) && \

((ac + ar[ax[num-1]][ax[num]] + ar[ax[num]][1] < bc) || \ (bc == ne)) ) { for (int j = 1; j <= num; j++) { bx[j] = ax[j]; } bc = ac + ar[ax[num-1]][ax[num]] + ar[ax[num]][1]; } } else { for (int j = i; j <= num; j++) { /* check whether to enter ax[j] subtree */ if ((ar[ax[i-1]][ax[j]] != ne) && \ ((ac + ar[ax[i-1]][ax[i]] < bc) || \ (bc == ne))) { /* search subtree */ swap(ax[i], ax[j]); ac += ar[ax[ i - 1]] [ax [ i ] ] ; backtrack( i+1) ; ac -= ar[ax[i-1]][ax[i]]; swap(ax[i], ax[j]); } } } } int main() { int n, m; in t i , j , int **a;

k, d;

clrscr(); printf("\n Travelling Salesman Problem \n\n"); printf(" Enter no. of cities and paths : "); scanf("%d %d", &n, &m); /* allocate memory */ get2Darray(a, n+1, n+1); /* initialization */ for (i = 1; i <= n; i++) { for (j = 1; j <= n; j++) { a[i][j] = -1; }

} /* path and distance of the route */ for (k = 1; k <= m; k++) { printf(" Enter path and distance : "); scanf("%d %d %d", &i, &j, &d); a[i][j] = d; a[j][i] = d; /* undirected */ } puts("\n Solving Travelling Salesman Problem using Backtracking... \n"); tspclass <int> tspobj(n, a, 0, -1); tspobj.backtrack(2); tspobj.print(); free2Darray(a, n+1); getch(); return 0; }

Output: Travelling Salesman Problem Enter Enter Enter Enter Enter Enter Enter no. of cities and paths : 4 6 path and distance : 1 2 20 path and distance : 1 3 42 path and distance : 1 4 35 path and distance : 2 3 30 path and distance : 2 4 34 path and distance : 3 4 12

Solving Travelling Salesman Problem using Backtracking... Optimal route for round-trip tour : 1 -> 2 -> 3 -> 4 -> 1 At a cost of 97

KNAPSACK GREEDY ALGORITHM


#include <stdio.h> #include <stdlib.h> #include <conio.h> static void knapsack_greedy(int num, int ksc, int *wt, int *ct) { int curwt; int i, maxi, rt; float totct; int *used; curwt = ksc; totct = 0; rt = 0; /* running time */ used = (int*)malloc(num * sizeof(int)); for (i = 0; i < num; ++i) { used[i] = 0; /* we have not used the ith object yet */ } while (curwt > 0) { rt++; maxi = -1; for (i=0; i <num; ++i) { rt++; if ((used[i] == 0) && \ ((maxi == -1) || \

((float)ct[i]/wt[i] > (float)ct[maxi]/wt[maxi]))) { maxi = i; } } used[maxi] = 1; /* mark the maxi-th object as used */ curwt -= wt[maxi]; totct += ct[maxi]; if (curwt >= 0) { printf(" Added object %d ( %2dKg , $%2d ) completely in the bag. ", maxi + 1, wt[maxi], ct[maxi]); printf("Space left: %d.\n", curwt); } else {

printf(" Added %d%% of object %d ( %2dKg , $%2d ) in the bag \n", (int)((1 + (float)curwt/wt[maxi]) * 100), maxi + 1, wt[maxi], ct[maxi]); totct -= ct[maxi]; totct += (1 + (float)curwt/wt[maxi]) * ct[maxi]; } } printf("\n Filled the bag with objects worth $%.2f \n", totct); printf("\n Total running time: %d \n\n", rt); free(used); } int main() { int num; /* total number of objects */ int ksc; /* knapsack capacity (maximum weight you can take) */ int *wt; /* weight array */ int *ct; /* cost array */ int i; clrscr(); printf("\n Knapsack Problem using Greedy Method \n\n"); printf(" Enter total number of objects : "); scanf("%d", &num); printf(" Enter knapsack capacity (maximum weight you can take) : "); scanf("%d", &ksc); wt = (int*)malloc(num * sizeof(int));

ct = (int*)malloc(num * sizeof(int)); for (i = 0; i < num; i++) { printf(" Enter weight and cost of the object %2d : ", i+1); scanf("%d %d", &wt[i], &ct[i]); } puts("\n Solving Knapsack problem using Greedy algorithm... "); knapsack_greedy(num, ksc, wt, ct); free(wt); free(ct); getch(); return 0; }

Output: Knapsack Problem using Greedy Method Enter Enter Enter Enter Enter Enter Enter Enter Enter Enter Enter Enter total number of objects : 10 knapsack capacity (maximum weight you can take) : 56 weight and cost of the object 1 : 3 75 weight and cost of the object 2 : 45 65 weight and cost of the object 3 : 2 2 weight and cost of the object 4 : 4 3 weight and cost of the object 5 : 1 30 weight and cost of the object 6 : 10 4 weight and cost of the object 7 : 12 5 weight and cost of the object 8 : 50 1 weight and cost of the object 9 : 5 10 weight and cost of the object 10 : 6 7

Solving Knapsack problem using Greedy algorithm... Added object 5 ( 1Kg , $30 ) completely in the bag. Space left: 55. Added object 1 ( 3Kg , $75 ) completely in the bag. Space left: 52. Added object 9 ( 5Kg , $10 ) completely in the bag. Space left: 47. Added object 2 ( 45Kg , $65 ) completely in the bag. Space left: 2. Added 33% of object 10 ( 6Kg , $ 7 ) in the bag Filled the bag with objects worth $182.33 Total running time: 55

Quadtree Representation

IMPLEMENTATION OF QUAD TREE

#include #include #include #include

<stdio.h> <stdlib.h> <ctype.h> <conio.h>

#define MAX_N 512 unsigned char xbm[MAX_N][MAX_N/8]; /* image/graphics in the XBM format */ const int n = 16; /* image size */ typedef struct qt_node* qtree; /* * +----+----+ * | NW | NE | * +----+----+ * | SW | SE | * +----+----+ */ typedef struct qt_node { char c; qtree nw; /* north west (top left) */ qtree ne; /* north east (top right) */ qtree sw; /* south west (bottom left) */ qtree se; /* south east (bottom right) */ } node; /* quad tree encode input */ static unsigned char img[] = { 0xf0,0xf0, 0xf0,0xf0, 0xf0,0xf0, 0xf0,0xf0, 0x0f,0x0f, 0x0f,0x0f, 0x0f,0x0f, 0x0f,0x0f, 0xf0,0xf0, 0xf0,0xf0, 0xf0,0xf0, 0xf0,0xf0, 0x0f,0x0f, 0x0f,0x0f, 0x0f,0x0f, 0x0f,0x0f, }; /* quad tree decode input */ static char *qt_nodes = "QQWBBWQWBBWQWBBWQWBBW"; static qtree qt_simplify(qtree q) { if (q->c != 'Q')

{ return q; } if (q->nw->c=='W' && q->ne->c=='W' && q->sw->c=='W' && q->se->c=='W') { /* QWWWW -> W */ free(q->nw); free(q->ne); free(q->sw); free(q->se); q->c = 'W'; return q; } if (q->nw->c=='B' && q->ne->c=='B' && q->sw->c=='B' && q->se->c=='B') { /* QBBBB -> B */ free(q->nw); free(q->ne); free(q->sw); f ree(q - >se); q->c = 'B'; return q; } return q; } static qtree qt_encode(int top, int left, int sz) { qtree q = (qtree)malloc(sizeof(node)); if (sz == 1) { q->c = xbm[top][left/8] & (1<<(left%8)) ? 'B' : 'W'; q->nw = NULL; q- >ne = NULL; q->sw = NULL; q->se = NULL; } else { q->c = 'Q'; q->nw = qt_encode(top, left, sz/2); /* nw */

q->ne = qt_encode(top, left+sz/2, sz/2); /* ne */ q- >sw = qt_encode( top+sz/2 , le f t , sz /2 ) ; q- >se = qt_encode( top+sz/2 , le f t+sz /2 , sz /2 ) ; } return qt_simplify(q); } static void qt_decode(int top, int left, int sz) { int i, j; static int k = 0; /* must be static */ char c = qt_nodes[k++]; switch (c) { case 'W': { for (i = top; i < (top + sz); i++) { for (j = left; j < (left + sz); j++) { xbm[i][j/8] &= ~(1 << (j%8)); /* clear */ } } break; } case 'B': { for (i = top; i < (top + sz); i++) { for (j = left; j < (left + sz); j++) { xbm[i][j/8] |= 1 << (j%8); /* set */ } } break; } case 'Q': { qt_decode(top, left, sz/2); /* nw */ qt_decode(top, left+sz/2, sz/2); /* ne */ qt_decode(top+sz/2, left, sz/2); /* sw */ qt_decode(top+sz/2, left+sz/2, sz/2); /* se */ } } }

/* sw */ /* se */

static void qt_print(qtree q) { putchar(q->c); if (q->c == 'Q') { qt_print(q->nw); qt_print(q->ne); qt_print(q->sw); qt_print(q->se); } } int main() { int i, j; char ch; clrscr(); puts("\n Implementing Quad Tree "); do { printf("\n Enter your choice [ Encode (E) / Decode (D) / Exit (X) ] : "); printf("%c", ch = getch()); ch = toupper(ch); putchar('\n'); if ('E' == ch) { int k = 0; for (i = 0; i < n; i++) { for (j = 0; j < n/8; j++) { xbm[i][j] = *(img+(k++)); } } printf(" Quadtree Width/Height : %d \n", n); printf(" Quadtree Nodes : \n "); qt_print(qt_encode(0, 0, n)); /* building quad tree from image */ printf("\n"); } else if ('D' == ch) { qt_decode(0, 0, n); /* retrieving image from quad tree */ printf(" Image size : %d \n", n); printf(" static unsigned char img[] = { \n ");

for (i = 0; i < n; i++) { for (j = 0; j < n/8; j++) { printf("0x%02x,", xbm[i][j]); } printf("\n "); } printf("};\n"); } else if ('X' == ch) { break; } } while (1); return 0; }

Output: Implementing Quad Tree Enter your choice [ Encode (E) / Decode (D) / Exit (X) ] : e Quadtree Width/Height : 16 Quadtree Nodes : QQWBBWQWBBWQWBBWQWBBW Enter your choice [ Encode (E) / Decode (D) / Exit (X) ] : d Image size : 16 static unsigned char img[] = { 0xf0,0xf0, 0xf0,0xf0, 0xf0,0xf0, 0xf0,0xf0, 0x0f,0x0f, 0x0f,0x0f, 0x0f,0x0f, 0x0f,0x0f, 0xf0,0xf0, 0xf0,0xf0, 0xf0,0xf0, 0xf0,0xf0, 0x0f,0x0f, 0x0f,0x0f, 0x0f,0x0f, 0x0f,0x0f, }; Enter your choice [ Encode (E) / Decode (D) / Exit (X) ] : x

Octree Representation

IMPLEMENTATION OF OCT TREE


#include <stdio.h> #include <stdlib.h> #include <string.h> #include <conio.h> typedef unsigned char uchar; typedef unsigned short ushort; #define #define #define #define #define XVAL 4 /* x value */ YVAL 4 /* y value */ ZVAL 4 /* z value */ LEAF 128 /* leaf node */ INTL 256 /* internal node */

/* * 1---5 * /| /| * 0---4 | * | 3-|-7 * |/ |/ * 2---6 */ enum ot_parts { TFL, /* TOP FRONT LEFT */ TFR, /* TOP FRONT RIGHT */ TBL, /* TOP BACK LEFT */ TBR, /* TOP BACK RIGHT */

BFL, BFR, BBL, BBR };

/* BOTTOM FRONT LEFT */ /* BOTTOM FRONT RIGHT */ /* BOTTOM BACK LEFT */ /* BOTTOM BACK RIGHT */

class ot_node_class { public: ushort index; uchar value; ot_node_class **child; ot_node_class(int ntype) { index = 0; value = 0; if (ntype == LEAF) /* node type */ { child = NULL; } else { child = new ot_node_class*[8];

child[TFL] = NULL; child[TFR] = NULL; child[TBL] = NULL; child[TBR] = NULL; child[BFL] = NULL; child[BFR] = NULL; child[BBL] = NULL; child[BBR] = NULL; } } ~ot_node_class() { if (child) { delete child[TFL]; delete child[TFR]; delete child[TBL]; delete child[TBR]; delete child[BFL]; delete child[BFR]; delete child[BBL]; delete child[BBR]; } }

void ot_print() { printf(" %2d\t", value); } uchar avg_child(); /* average child */ }; uchar ot_node_class::avg_child() /* average child */ { if (child) { ushort tmp = 0; for (int i = 0; i < 8; i++) { tmp += (ushort)child[i]; } return (uchar)(tmp /= 8); } return 0; } class data_array_class { public: uchar data[XVAL][YVAL][ZVAL]; data_array_class() { } ~data_array_class() { } void read_data(); ot_node_class *buildtree(int xpt = 0, in t ypt = 0, int zpt = 0, int len = XVAL); }; void data_array_class::read_data() { for (int i = 0; i < ZVAL; i++) { for (int j = 0; j < YVAL; j++) { for (int k = 0; k < XVAL; k++) { data[k][j][i] = rand() % 100; printf(" [%d-%d-%d]:%2d\t", k, j, i, data[k][j][i]); }

} } putchar('\n'); } ot_node_class* data_array_class::buildtree(int xpt, int ypt, int zpt, int len) { ot_node_class *parent; if (len == 1) { parent = new ot_node_class(LEAF); parent->value = data[xpt][ypt][zpt]; return parent; } parent = new ot_node_class(INTL); parent->child[TFL] = buildtree(xpt, ypt, zpt, len/2); parent->child[TFR] = buildtree(xpt, ypt, zpt+len/2, len/2); parent->child[TBL] = buildtree(xpt, ypt+len/2, zpt, len/2); parent->child[TBR] = buildtree(xpt, ypt+len/2, zpt+len/2, len/2); parent->child[BFL] = buildtree(xpt+len/2, ypt, zpt, len/2); parent->child[BFR] = buildtree(xpt+len/2, ypt, zpt+len/2, len/2); parent->child[BBL] = buildtree(xpt+len/2, ypt+len/2, zpt, len/2); parent->child[BBR] = buildtree(xpt+len/2, ypt+len/2, zpt+len/2, len/2); parent->value = parent->avg_child(); return parent; } class octree_class { public: ot_node_class *root; octree_class(ot_node_class *otree) { root = otree; } ~octree_class() { delete root; } void depth_traversal(ot_node_class *recur_root = NULL, char *octnode_fun = "ot_print"); };

void octree_class::depth_traversal(ot_node_class *recur_root, char *octnode_fun) { if (recur_root == NULL) { return; } if (!(recur_root->child)) { if(!(strcmp(octnode_fun, "ot_print"))) { recur_root->ot_print(); } return; } for (int i = 0; i < 8; i++) { depth_traversal(recur_root->child[i], octnode_fun); } } int main() { data_array_class dataobj; clrscr(); printf("\n Implementing Octree \n"); printf("\n Reading three dimensional random data... \n"); dataobj.read_data(); printf("\n Building Octree using three dimensional random data... \n"); octree_class otobj(dataobj.buildtree()); printf("\n Depth Traversing Octree... \n"); printf(" Octree nodes are : \n"); otobj.depth_traversal(otobj.root, "ot_print"); putchar('\n'); getch(); return 0; }

Output: Implementing Octree Reading three dimensional random data... [0-0-0]:46 [1-0-0]:30 [2-0-0]:82 [3-0-0]:90 [1-1-0]:17 [2-1-0]:95 [3-1-0]:15 [0-2-0]:48 [2-2-0]: 4 [3-2-0]:58 [0-3-0]:71 [1-3-0]:79 [3-3-0]:60 [0-0-1]:12 [1-0-1]:21 [2-0-1]:63 [0-1-1]:19 [1-1-1]:41 [2-1-1]:90 [3-1-1]:85 [1-2-1]: 9 [2-2-1]:52 [3-2-1]:71 [0-3-1]:79 [2-3-1]:81 [3-3-1]:51 [0-0-2]:95 [1-0-2]:93 [3-0-2]:10 [0-1-2]:79 [1-1-2]:95 [2-1-2]:61 [0-2-2]:89 [1-2-2]:88 [2-2-2]:66 [3-2-2]:64 [0-1-0]:56 [1-2-0]:26 [2-3-0]:92 [3-0-1]:47 [0-2-1]:14 [1-3-1]:16 [2-0-2]:34 [3-1-2]:92 [0-3-2]:92

[1-3-2]:63 [2-0-3]:27 [3-1-3]:66 [0-3-3]:89

[2-3-2]:66 [3-0-3]: 0 [0-2-3]:47 [1-3-3]:83

[3-3-2]:64 [0-1-3]:95 [1-2-3]:42 [2-3-3]:66

[0-0-3]:39 [1-1-3]:12 [2-2-3]:74 [3-3-3]:41

[1-0-3]:51 [2-1-3]: 8 [3-2-3]:69

Building Octree using three dimensional random data... Depth Traversing Octree nodes are 46 12 56 79 95 93 26 9 79 63 83 82 34 27 61 92 81 58 64 69 64 Octree... : 19 30 51 95 16 89 63 95 8 10 71 60 41

21 12 47 90 0 51

17 48 92 90 92 66

41 14 89 47 66 74

95 39 71 79 88 42 15 85 4 52 66 66

IMPLEMENTATION OF RED BLACK TREE


#include #include #include #include #include <stdio.h> <stdlib.h> <assert.h> <ctype.h> <conio.h>

typedef enum rbt_node_color { REDCOL, BLACKCOL } rbt_color; typedef struct rbt_node_t { void *key; void *value; struct rbt_node_t *left; struct rbt_node_t *right; st ruct rbt_node_t *parent ; rbt_co lo r color ; } *rbt_node; typedef struct rbt_t { rbt_node root; } *rbt; typedef int (*cmp_fn)(void *left, void *right);

static static static static static static static static static static static

void void void void void void void void void void void

ins_case1(rbt ins_case2(rbt ins_case3(rbt ins_case4(rbt ins_case5(rbt del_case1(rbt del_case2(rbt del_case3(rbt del_case4(rbt del_case5(rbt del_case6(rbt

t, t, t, t, t, t, t, t, t, t, t,

rbt_node rbt_node rbt_node rbt_node rbt_node rbt_node rbt_node rbt_node rbt_node rbt_node rbt_node

n); n); n); n); n); n); n); n); n); n); n);

/******************* Relationship between Nodes ******** ** * * * * * * * * / static rbt_node grandparent(rbt_node n) { assert(n != NULL); assert(n->parent != NULL); assert(n->parent->parent != NULL); return n- >parent- >parent;

} static rbt_node sibling(rbt_node n) { assert(n != NULL); assert(n->parent != NULL); if { (n == n- >parent- >lef t )

return n->parent->right; } else { return n->parent->left; } } static rbt_node uncle(rbt_node n) { assert(n != NULL); assert(n->parent != NULL); assert(n->parent->parent != NULL); return sib l i ng (n - >parent) ; } static rbt_color node_color(rbt_node n)

{ return n == NULL ? BLACKCOL : n->color; } /*************** Verify Red-Black Tree Properties********* * * * * * * * / /* 1. Each node is either red or black */ static void verify_prop1(rbt_node n) { assert(node_color(n) == REDCOL || node_color(n) == BLACKCOL); if (n == NULL) { return; } verify_prop1(n->left); verify_prop1(n->right); } /* 2. The root node is black */ static void verify_prop2(rbt_node root) { assert(node_color(root) == BLACKCOL); }

/* * 3. All leaves (NIL) are black and contain no data. * This property is implicitly assured by always treating NULL as black. */ /* * 4. Every red node has two children, and both are black * (or equivalently, the parent of every red node is black). */ static void verify_prop4(rbt_node n) { if (node_color(n) == REDCOL) { assert(node_color(n->left) == BLACKCOL); assert(node_color(n->right) == BLACKCOL); assert(node_color(n->parent) == BLACKCOL); } if (n == NULL) { return; } verify_prop4(n->left); verify_prop4(n->right); }

/* * 5. All paths from any given node to its leaf nodes contain * the same number of black nodes. */ static void verify_prop5_hlpr(rbt_node n, int black_cnt, int *path_black_cnt) { if (node_color(n) == BLACKCOL) { black_cnt++; } if (n == NULL) { if (*path_black_cnt == -1) { *path_black_cnt = black_cnt; } else { assert(black_cnt == *path_black_cnt); } return; } verify_prop5_hlpr(n->left, black_cnt, path_black_cnt); verify_prop5_hlpr(n->right, black_cnt, path_black_cnt); } static void verify_prop5(rbt_node root) { int black_cnt_path = -1; verify_prop5_hlpr(root, 0, &black_cnt_path); } static void verify_properties(rbt t) { verify_prop1(t->root); verify_prop2(t->root); /* property 3 is implicit */ verify_prop4(t->root); verify_prop5(t->root); } /******************* Red-Black Tree Operations ******** ** * * * * * * * * * / static rbt rbt_create() { rbt t = malloc(sizeof(struct rbt_t)); t->root = NULL; verify_properties(t); return t; }

static rbt_node new_node(void *key, void *value, rbt_color color, rbt_node left, rbt_node right) { rbt_node result = malloc(sizeof(struct rbt_node_t)); result->key = key; result->value = value; result->color = color; result->left = left; result->right = right; if (left != NULL) { left->parent = result; } if (right != NULL) { right->parent = result; } result->parent = NULL; return result; } static rbt_node lookup_node(rbt t, void *key, cmp_fn cmp) { rbt_node n = t->root; while (n != NULL) { int cmp_res = cmp(key, n->key); if (cmp_res == 0) { return n; } else if (cmp_res < 0) { n = n->left; } else { assert(cmp_res > 0); n = n->right; } } return n; } static void* rbt_lookup(rbt t, void *key, cmp_fn cmp) {

rbt_node n = lookup_node(t, key, cmp); return n == NULL ? NULL : n->value; } static rbt_node find_min(rbt_node n) { assert(n != NULL); while (n->left != NULL) { n = n->left; } return n; } static rbt_node find_max(rbt_node n) { assert(n != NULL); while (n->right != NULL) { n = n->right; } return n; } static void replace_node(rbt t, rbt_node oldn, rbt_node newn) { if (oldn->parent == NULL) { t->root = newn; } else { if (oldn == oldn->parent->left) { oldn->parent->left = newn; } else { oldn->parent->right = newn; } } if (newn != NULL) { newn->parent = oldn->parent; } } static void rotate_left(rbt t, rbt_node n) {

rbt_node r = n->right; replace_node(t, n, r); n- >right = r - >lef t ; if (r->left != NULL) { r->left->parent = n; } r->left = n; n- >parent = r ; } static void rotate_right(rbt t, rbt_node n) { rbt_node l = n->left; rep lace_node( t , n, l ) ; n- >lef t = l - >right ; if (l->right != NULL) { l->right->parent = n; } l->right = n; n->parent = l; } static void ins_case1(rbt t, rbt_node n) { if (n->parent == NULL) { n->color = BLACKCOL; } else { ins_case2(t, n); } } static void ins_case2(rbt t, rbt_node n) { if (node_color(n->parent) == BLACKCOL) { return; } else { ins_case3(t, n); } }

static void ins_case3(rbt t, rbt_node n) { if (node_color(uncle(n)) == REDCOL) { n->parent->color = BLACKCOL; uncle(n)->color = BLACKCOL; grandparent(n)->color = REDCOL; ins_case1(t, grandparent(n)); } else { ins_case4(t, n); } } static void ins_case4(rbt t, rbt_node n) { if (n == n->parent->right && n->parent == grandparent(n)->left) { rotate_left(t, n->parent); n = n->left; } else if (n == n->parent->left && n->parent == grandparent(n)->right) { rotate_right(t, n->parent); n = n- >right ; } ins_case5(t, n); } static void ins_case5(rbt t, rbt_node n) { n->parent->color = BLACKCOL; grandparent(n)->color = REDCOL; if (n == n->parent->left && n->parent == grandparent(n)->left) { rotate_right(t, grandparent(n)); } else { assert(n == n->parent->right && n->parent == grandparent(n)->right); rotate_left(t, grandparent(n)); } } static void rbt_ins(rbt t, void *key, void *value, cmp_fn cmp) { rbt_node newn = new_node(key, value, REDCOL, NULL, NULL);

if (t->root == NULL) { t->root = newn; } else { rbt_node n = t->root; while (1) { int cmp_res = cmp(key, n->key); if (cmp_res == 0) { n->value = value; free (newn); return; } else if (cmp_res < 0) { if (n->left == NULL) { n->left = newn; break; } else { n = n->left; } } else { assert(cmp_res > 0); if (n->right == NULL) { n->right = newn; break; } else { n = n->right; } } } newn->parent = n; } ins_case1(t, newn); verify_properties(t); }

static void del_case1(rbt t, rbt_node n) { if (n->parent == NULL) { return; } else { del_case2(t, n); } } static void del_case2(rbt t, rbt_node n) { if (node_color(sibling(n)) == REDCOL) { n->parent->color = REDCOL; sibling(n)->color = BLACKCOL; if (n == n->parent->left) { rotate_left(t, n->parent); } else { rotate_right(t, n->parent); } } del_case3(t, n); } static void del_case3(rbt t, rbt_node n) { if (node_color(n->parent) == BLACKCOL && node_color(sibling(n)) == BLACKCOL && node_color(sibling(n)->left) == BLACKCOL && node_color(sibling(n)->right) == BLACKCOL) { sibling(n)->color = REDCOL; del_case1(t, n->parent); } else { del_case4(t, n); } } static void del_case4(rbt t, rbt_node n) { if (node_color(n->parent) == REDCOL && node_color(sibling(n)) == BLACKCOL && node_color(sibling(n)->left) == BLACKCOL &&

node_color(sibling(n)->right) == BLACKCOL) { sibling(n)->color = REDCOL; n->parent->color = BLACKCOL; } else { del_case5(t, n); } } static void del_case5(rbt t, rbt_node n) { if (n == n->parent->left && node_color(sibling(n)) == BLACKCOL && node_color(sibling(n)->left) == REDCOL && node_color(sibling(n)->right) == BLACKCOL) { sibling(n)->color = REDCOL; sibling(n)->left->color = BLACKCOL; rotate_right(t, sibling(n)); } else if (n == n->parent->right && node_color(sibling(n)) == BLACKCOL && node_color(sibling(n)->right) == REDCOL && node_color(sibling(n)->left) == BLACKCOL) { sibling(n)->color = REDCOL; sibling(n)->right->color = BLACKCOL; rotate_left(t, sibling(n)); } del_case6(t, n); } static void del_case6(rbt t, rbt_node n) { sibling(n)->color = node_color(n->parent); n->parent->color = BLACKCOL; if (n == n->parent->left) { assert(node_color(sibling(n)->right) == REDCOL); sibling(n)->right->color = BLACKCOL; rotate_left(t, n->parent); } else { assert(node_color(sibling(n)->left) == REDCOL); sibling(n)->left->color = BLACKCOL; rotate_right(t, n->parent); } }

static void rbt_del(rbt t, void *key, cmp_fn cmp) { rbt_node child; rbt_node n = lookup_node(t, key, cmp); if (n == NULL) { return; } if (n->left != NULL && n->right != NULL) { rbt_node pred = find_max(n->left); n->key = pred->key; n->value = pred->value; n = pred; } assert(n->left == NULL || n->right == NULL); child = n->right == NULL ? n->left : n->right; if (node_color(n) == BLACKCOL) { n->color = node_color(child); del_case1(t, n); } replace_node(t, n, child); if (n->parent == NULL && child != NULL) { child->color = BLACKCOL; } free(n); verify_properties(t); } static void rbt_flush(rbt_node n) { if (n) { rbt_flush(n->left); rbt_flush(n->right); free(n); } } static int cmp_int(void *leftp, void *rightp) { int left = (int)leftp; int right = (int)rightp;

return (left < right) ? -1 : (left > right) ? 1 : 0; } static void print_hlpr(rbt_node n, int level) { int i; if (n == NULL) { return; } print_hlpr(n->right, level+1); for (i = 0; i < level; i++) { printf(" "); } if (n->color == BLACKCOL) { printf(" %d\n", (int)n->key); } else { printf(" <%d>\n", (int)n->key); } print_hlpr(n->left, level+1); } static void print_tree(rbt t) { print_hlpr(t->root, 0); puts(""); } int main() { int x, y; char ch; rbt t; rbt_node n = NULL; clrscr(); puts("\n Implementing Red-Black Tree "); t = rbt_create(); do { printf("\n Insert(I) \n Search (S)\n FindMin(A)\n FindMax (B) "); pr in t f ( " \ n Pr in t (P) \n Delete (D) \n Flush (F) \n Exi t pr in t f ( " Enter your choice : ") ; printf("%c", ch = getch()); ch = toupper(ch); putchar('\n'); if ('I' == ch) { printf(" Enter the elements of node ( key, value ) : ");

(X) \n" ) ;

scanf ( "%d %d", &x, &y); printf(" Inserting %d -> %d\n\n", x, y); rbt_ i ns ( t , (vo id* )x , (vo id* )y , cmp_int ) ; print_tree(t); } else if ('S' == ch) { printf(" Enter the key to be searched : "); scanf("%d", &x); printf(" Search Result : %2d\n", (int)rbt_lookup(t,(void*)x, cmp_int)); } else if ('A' == ch) { if ((n = find_min(t->root)) != NULL) { printf(" Minimum is %d -> %d\n\n", n->key, n->value); } } else if ('B' == ch) { if ((n = find_max(t->root)) != NULL) { printf(" Maximum is %d -> %d\n\n", n->key, n->value); } } else if ('P' == ch) { printf(" Printing Red-Black tree...\n"); print_tree(t); } else if ('D' == ch) { printf(" Enter the key to be deleted : "); scanf("%d", &x); printf(" Deleting key %d\n\n", x); rbt_de l ( t , (vo id* )x , cmp_int ) ; pr in t _ t r ee ( t ) ; } else if ('F' == ch) { printf(" Flushing nodes...\n"); rbt_flush(t->root); t->root = NULL; print_tree(t); } else if ('X' == ch) { printf(" Exit...\n"); rbt_flush(t->root); t->root = NULL; break;

} } while (1); free(t); return 0; } Output: Implementing Red-Black Tree Insert (I) Search (S) FindMin (A) FindMax (B) Print (P) Delete (D) Flush (F) Exit (X) Enter your choice : i Enter the elements of node ( key, value ) : 11 11 Inserting 11 -> 11 11 Insert (I) Search (S) FindMin (A) FindMax (B) Print (P) Delete (D) Flush (F) Exit (X) Enter your choice : i Enter the elements of node ( key, value ) : 2 2 Inserting 2 -> 2 11 <2> Insert (I) Search (S) FindMin (A) FindMax (B) Print (P) Delete (D) Flush (F) Exit (X) Enter your choice : i Enter the elements of node ( key, value ) : 14 14 Inserting 14 -> 14

<14> 11 <2>

Insert (I) Search (S) FindMin (A) FindMax (B) Print (P) Delete (D) Flush (F) Exit (X) Enter your choice : i Enter the elements of node ( key, value ) : 1 1 Inserting 1 -> 1 14 11 2 <1> Insert (I) Search (S) FindMin (A) FindMax (B) Print (P) Delete (D) Flush (F) Exit (X) Enter your choice : i Enter the elements of node ( key, value ) : 7 7 Inserting 7 -> 7 14 11 <7> 2 <1> Insert (I) Search (S) FindMin (A) FindMax (B) Print (P) Delete (D) Flush (F) Exit (X) Enter your choice : i Enter the elements of node ( key, value ) : 15 15

Inserting 15 -> 15 <15> 14 11 <7> 2 <1>

Insert (I) Search (S) FindMin (A) FindMax (B) Print (P) Delete (D) Flush (F) Exit (X) Enter your choice : i Enter the elements of node ( key, value ) : 5 5 Inserting 5 -> 5 <15> 14 11 7 <5> <2> 1 Insert (I) Search (S) FindMin (A) FindMax (B) Print (P) Delete (D) Flush (F) Exit (X) Enter your choice : i Enter the elements of node ( key, value ) : 8 8 Inserting 8 -> 8 <15> 14 11 <8> 7 <5> <2> 1

Insert (I) Search (S) FindMin (A) FindMax (B) Print (P) Delete (D) Flush (F) Exit (X) Enter your choice : i Enter the elements of node ( key, value ) : 8 8 Inserting 8 -> 8 <15> 14 11 <8> 7 <5> <2> 1 Insert (I) Search (S) FindMin (A) FindMax (B) Print (P) Delete (D) Flush (F) Exit (X) Enter your choice : i Enter the elements of node ( key, value ) : 4 4 Inserting 4 -> 4 <15> 14 <11> 8 7 5 <4> <2> 1 Insert (I) Search (S) FindMin (A) FindMax (B) Print (P) Delete (D) Flush (F) Exit (X) Enter your choice : a

Minimum is 1 -> 1 Insert (I) Search (S) FindMin (A) FindMax (B) Print (P) Delete (D) Flush (F) Exit (X) Enter your choice : b Maximum is 15 -> 15 Insert (I) Search (S) FindMin (A) FindMax (B) Print (P) Delete (D) Flush (F) Exit (X) Enter your choice : s Enter the key to be searched : 8 Search Result : 8 Insert (I) Search (S) FindMin (A) FindMax (B) Print (P) Delete (D) Flush (F) Exit (X) Enter your choice : s Enter the key to be searched : 100 Search Result : 0 Insert (I) Search (S) FindMin (A) FindMax (B) Print (P) Delete (D) Flush (F) Exit (X) Enter your choice : p Printing Red-Black tree... <15> 14 <11> 8 7

5 <4> <2> 1 Insert (I) Search (S) FindMin (A) FindMax (B) Print (P) Delete (D) Flush (F) Exit (X) Enter your choice : d Enter the key to be deleted : 7 Deleting key 7 <15> 14 <11> 8 5 <4> 2 <1> Insert (I) Search (S) FindMin (A) FindMax (B) Print (P) Delete (D) Flush (F) Exit (X) Enter your choice : d Enter the key to be deleted : 15 Deleting key 15 14 <11> 8 5 <4> 2 <1> Insert (I) Search (S) FindMin (A) FindMax (B) Print (P)

Delete (D) Flush (F) Exit (X) Enter your choice : d Enter the key to be deleted : 11 Deleting key 11 <14> 8 5 <4> 2 <1> Insert (I) Search (S) FindMin (A) FindMax (B) Print (P) Delete (D) Flush (F) Exit (X) Enter your choice : d Enter the key to be deleted : 2 Deleting key 2 <14> 8 5 <4> 1 Insert (I) Search (S) FindMin (A) FindMax (B) Print (P) Delete (D) Flush (F) Exit (X) Enter your choice : d Enter the key to be deleted : 5 Deleting key 5 <14> 8 4 1 Insert (I) Search (S)

FindMin (A) FindMax (B) Print (P) Delete (D) Flush (F) Exit (X) Enter your choice : f Flushing nodes... Insert (I) Search (S) FindMin (A) FindMax (B) Print (P) Delete (D) Flush (F) Exit (X) Enter your choice : x

INSERTION SORT
#include<stdio.h> #include<conio.h> void main() { int a[20],n,temp,i,j; clrscr(); printf("\n enter the total no elements:"); scanf("%d",&n); printf("\n enter the elements:"); for(i=0;i<n;i++) { scanf("%d",&a[i]); } for(i=1;i<n;i++) { temp=a[i]; j=i-1; while(temp<a[j]&&j>=0) { a[j+1]=a[j]; j=j-1; } a[j+1]=temp; }

printf("\n elements after sorting are:\n"); for(i=0;i<n;i++) printf("%d\n",a[i]); getch(); }

OUTPUT: enter the total no elements: 6 enter the elements: 4 3 7 2 19 1 elements after sorting are: 1 2 3 4 7 19

QUICK SORT
#include<stdio.h> #include<conio.h> int main() { int x[20],size,i; void quicksort(int[],int,int); clrscr(); printf("\n enter the size of the array"); scanf("%d",&size); printf("\n enter %d elements",size); for(i=0;i<size;i++) scanf("%d",&x[i]); quicksort(x,0,size-1); printf("\n sorted elements"); for(i=0;i<size;i++) printf("%d\n",x[i]); getch();

} void quicksort(int x[10],int first,int last) { int pivot,j,temp,i; if(first<last) { pivot=first; i=first; j=last; while(i<j) { while(x[i]<x[pivot]&&i<last) i++; while(x[j]>x[pivot]) j--; if(i<j) { temp=x[i]; x[i]=x[j]; x[j]=temp; } } temp=x[pivot]; x[pivot]=x[j]; x[j]=temp; quicksort(x,first,j-1); quicksort(x,j+1,last); } }

OUTPUT: enter the size of the array: 5 enter 5 elements: 24 12 1 55 34 sorted elements: 1 12 24 34

55

BUCKET SORT
#include<stdio.h> #include<conio.h> #include<alloc.h> struct term { float e; struct term*next; }*b[10],*p,*q; void isort(float a[],int n) { int i,j,k; float key;

for(j=0;j<n;j++) { key=a[j]; i=j-1; while(i>=0&&a[i]>key) { a[i+1]=a[i]; i--; } a[i+1]=key; } for(k=0;k<n;k++) printf("%2f\n",a[k]); } void bsort(float a[],int n) { int i,j,k; float list[20],list1[20]; for(i=0;i<10;i++) b[i]=NULL; for(i=0;i<n;i++) { j=(int)a[i]*n; p=(struct term*)malloc(sizeof(struct term)); p->e=a[i]; p->next=NULL; if(b[j]==NULL) { b[j]=p; } else { q=b[j]; while(q->next!=NULL) {

q=q->next; } q->next=p; } } printf("the sorted list is:\n"); for(i=0;i<10;i++) { p=b[i]; j=0; while(p!=NULL)

{ list[j]=p->e; j++; p=p->next; } isort(list,j); } } void main() { int n,i; float a[10],t; clrscr(); printf("\n enter the no of elements to be sorted:"); scanf("%d",&n); printf("\n enter the list of decimal no's:"); for(i=0;i<n;i++) { scanf("%f",&t); if(t>0&&t<1) a[i]=t; else { printf("invalid input"); i--; } } bsort(a,n); getch(); }

OUTPUT: enter the no of elements to be sorted:5 enter the list of decimal no's:.2 3 invalid input.5 .4

.12 .04 the sorted list is: 0.040000 0.120000 0.200000 0.400000 0.500000

POLYNOMIAL DIFFERENTIATION
#include<stdio.h> #include<conio.h> struct node

{ int coef,degree; struct node*next; } head,temp,mynode[10]; void getequation() { char response; int i; printf("enter the first term:"); scanf("%d%d",&mynode[0].coef,&mynode[0].degree); mynode[0].next=NULL; printf("do u want to add more nodes :(y\n)\n"); scanf("%s",&response); for(i=1;i<10&&(response=='y'||response=='y');i++) { printf("enter the node:"); scanf("%d%d",&temp.coef,&temp.degree); temp.next=NULL; if(i==1) { mynode[0].next=&temp; mynode[i]=temp; } else { mynode[i-1].next=&temp; mynode[i]=temp; } printf("do u want to add more nodes:(y/n):\n"); scanf("%s",&response); } } void display() { int i; for(i=0;i<10;i++) { if(mynode[i].degree>=0) if(i==0) printf("%dx^%d",mynode[0].coef,mynode[0].degree); else if(mynode[i].coef!=NULL&&mynode[i].coef!=0) printf("+%dx^%d",mynode[i].coef,mynode[i].degree);

} } void differentiation()

{ int i; for(i=0;i<10;i++) { if(mynode[i].next!=NULL) { mynode[i].coef=mynode[i].coef*mynode[i].degree; mynode[i].degree--; } if(mynode[i].next==NULL&&mynode[i].coef!=0) { mynode[i].coef=mynode[i].coef*mynode[i].degree; mynode[i].degree--; } } } void main() {clrscr(); getequation(); printf("the polynomial is:"); display(); printf("the polynomial after differentation is :"); differentiation(); display(); getch(); }

Output:

enter the first term: 2 2 do u want to add more nodes :(y/n) y enter the node:4 3 do u want to add more nodes:(y/n): n the polynomial is:2x^2+4x^3 the polynomial after differentation is :4x^1+12x^2

HEAP SORT
#include <stdio.h> #include <conio.h> void restorehup(int *,int); void restorehdown(int *,int,int); void main() { int a[20],n,i,j,k; clrscr(); printf("Enter the no of elements to be sorted:"); scanf("%d",&n); printf("Enter the elements"); for(i=1;i<=n;i++) { scanf("%d",&a[i]); restorehup(a,i); } j=n; for(i=1;i<=j;i++) { int temp; temp=a[1]; a[1]=a[n]; a[n]=temp; n--; restorehdown(a,1,n); } n=j; printf("Final Sorting"); for(i=1;i<=n;i++) { printf("%4d",a[i]); } } void restorehup(int *a,int i) { int v=a[i]; while((i>1) & (a[i/2]<v)) { a[i]=a[i/2]; i=i/2; } a[i]=v; } void restorehdown(int *a,int i,int n) { int v=a[i];int j=i*2; while(j<=n) { if((j<n)&&(a[j]<a[j+1]))

j++; if(a[j]<a[j/2]) break; a[j/2]=a[j]; j=j*2; } a[j/2]=v; } Output: enter the size :5

enter the elements: 4 89 1 34 23 The sorted order is : 1 4 23 34 89

BINARY SEARCH USING N*N MATRIX


#include<stdio.h> #include<conio.h> void binsearch(int n,int num); void insertsort(int n); int a[20][20]; void main(){ int n,num,i,j; clrscr(); printf("Enter order of elements"); scanf("%d",&n); printf("Enter matrix of elements"); for(i=0;i<n;i++) for(j=0;j<n;j++) scanf("%d",&a[i][j]); insertsort(n); printf("matrix of elements are"); for(i=0;i<n;i++) { for(j=0;j<n;j++) printf("%d\t",a[i][j]); printf("\n"); } printf("Enter element to be searched"); scanf("%d",&num); binsearch(n,num); getch(); } void binsearch(int n,int num){ int i; for(i=0;i<n;i++) { int low=0,high=n-1,mid; for(mid=(low+high)/2;low<=high;mid=(low+high)/2){ if(a[i][mid]==num){ printf("num %d is present at position %d%d",num,i+1,mid+1); return; } else if(a[i][mid]<num) low = mid+1; else high = mid+1;

} } printf("\n number is not present in the matrix"); } void insertsort(int n)

{ int i,j,k=0,key,list[20]; for(i=0;i<n;i++) for(j=0;j<n;j++) { list[k] = a[i][j]; k++; } for(j=1;j<n*n;j++){ key = list[j]; i=j-1; while(i>=0 && list[i] >key){ list[i+1] = list[i]; i--; list[i+1] = key; } list[i+1] = key; } k=0; for(i=0;i<n;i++) for(j=0;j<n;j++) { a[i][j] = list[k]; k++; } }

Output: Enter order of elements: 3 Enter matrix of elements: 10 9 5 6 3 22 11 41 52 matrix of elements are: 3 5 6 9 10 11 22 41 52 Enter element to be searched: 6 num 6 is present at position 13

INDEX SNO DATE NAME OF THE EXPERIMENT


INSERTION SORT QUICK SORT HEAP SORT BUCKET SORT POLYNOMIAL DIFFERENTIATION PRINTING NODE DETAILS LEVELWISE BINARY SEARCH IN N*N MATRIX BINARY TREE TRAVERSAL RED BLAK TREES KNAPSACK PROBLEM TRAVELLING SALESMAN PROBLEM KRUSKAL ALGORITHM FLOYD WARSHALL ALGORITHM IMPLEMENTATING OCT TREES

PG .NO.

1 2 3 4 5 6 7 8 9 10 11 12 13 14

15

IMPLEMENTING QUAD TREES

OBSERVATION MARK: _____________

SIGNATURE:__________________

Potrebbero piacerti anche