Вы находитесь на странице: 1из 29

IC 309-Programming III Data Structures and Algorithms

SUBMITTED BY: HITESH BAHL 450/IC/09

CONTENTS
1. Recursion Factorial and Quicksort 2. Stack Implementation using array and linked list- LIFO structure, create, POP, PUSH, delete stack 3. Queue- FIFO structure Priority Queues, Circular Queues, operations on Queues 4. Searching- Sequential, Binary, Indexed Sequential Searches 5. Sorting Approaches- Bubble, Quick Sort, Merge Sort, Heap Sort, Selection Sort & Insertion Sort 6. Binary Tree & B-Tree Implementation 7. Traversal of Tree BFS & DFS, Expression in Tree- in-order, pre-order, post-order 8. Minimum Spanning Tree , Prims & Kruskals Algorithm 9. Shortest Path Approaches- Dijkstras, Bellman Ford 10. Longest Common Subsequences

PROGRAM 1:Recursive approach to factorial #include <stdio.h> int factorial(int number) { int temp; if(number <= 1) return 1; temp = number * factorial(number - 1); return temp; } int main() { int number; printf("Please enter a positive integer: "); scanf("%d", &number); if (number < 0) printf("That is not a positive integer.\n"); else printf("%d factorial is: %d\n", number, factorial(number)); return 0; }

PROGRAM-2:Stack Implementation using array and linked list- LIFO structure, create, POP, PUSH, delete stack
// Stack implementation using arrays #include <stdio.h> #define MAX 100 int stack[MAX]; int top=0; void push(int val) { if(top < MAX) stack[top++]=val; else printf("Stack Overflow"); } int pop() { int a; if(top > 0) { top--; a = stack[top]; return a; } else { printf("Stack is Empty"); return -1; } } void display() { int i = 0; if(top > 0) { printf("\tElements of the stack are:"); while(i < top) { printf("\t%d",stack[i++]);

} printf("\n"); } else printf("\tStack is Empty\n"); } int main() { int choice=0,val=0; do { printf("\n\t1.Push 2.Pop 3.Display 4.Exit\n\tSelect Your Choice : "); scanf("%d",&choice); switch(choice) { case 1: printf("\tElement to be Pushed : "); scanf("%d",&val); push(val); break; case 2: val=pop(); if(val!=-1) printf("\tPopped Element : %d\n",val); break; case 3: display(); break; case 4: break; default: printf("\tWrong Choice"); break; } } while(choice!=4); return 0; }

// Stack implementation using Linked Lists #include <stdio.h> #include <malloc.h>

#define maxsize 10 struct node { int info; struct node *link; }*start=NULL, *now,*temp,*p; typedef struct node N; void push() { now=(N*)malloc(sizeof(N)); printf("\nEnter the item : "); scanf("%d",&now->info); now->link=NULL; if(start==NULL) start=now; else { p=start; while(p->link != NULL) p=p->link; p->link=now; } } void pop() { if(start == NULL) printf("\nStack is empty"); else if(start -> link == NULL) { printf("\nThe deleted element is : %d", start->info); free(start); start=NULL; } else { p=start; while(p->link != NULL)

{ temp = p; p = p -> link; } printf("\nDeleted element is : %d\n", p -> info); temp->link = NULL; free(p); } } void display() { if(start == NULL) printf("\nStack is empty"); else { printf("\nThe elements are : "); p = start; while(p != NULL) { printf("%d", p->info); p = p -> link; } printf("\n"); } } int main() { int ch,a; do { printf("\t\t\tLinked stack"); printf("\n 1.Push"); printf("\n 2.Pop"); printf("\n 3.Display"); printf("\n 4.Exit"); printf("\n Enter your choice : "); scanf("%d",&ch); switch(ch) { case 1: push(); break; case 2: pop();

break; case 3: display(); break; case 4: exit(0); default: printf("\nInvalid choice"); break; } } while(ch<=3); return 0; }

PROGRAM-3: Queue- FIFO structure Priority Queues, Circular Queues, operations on Queues
// Implement Queue data structure #include <stdio.h> #include <stdlib.h> #define MAX 50 int queue_arr[MAX]; int rear = -1; int front = -1; void insert() { int added_item; if (rear==MAX-1) printf("Queue Overflow\n"); else { if (front == -1) front=0; printf("Input the element for adding in queue : "); scanf("%d", &added_item); rear=rear+1; queue_arr[rear] = added_item ; } } void del() { if (front == -1 || front > rear) { printf("Queue Underflow\n"); return ; } else { printf("Element deleted from queue is : %d\n", queue_arr[front]); front=front+1; } }

void display() { int i; if (front == -1) printf("Queue is empty\n"); else { printf("Queue is :\n"); for(i=front;i<= rear;i++) printf("%d ",queue_arr[i]); printf("\n"); } } int main() { int choice; while(1) { printf("1.Insert\n"); printf("2.Delete\n"); printf("3.Display\n"); printf("4.Quit\n"); printf("Enter your choice : "); scanf("%d",&choice); switch(choice) { case 1: insert(); break; case 2: del(); break; case 3: display(); break; case 4: exit(1); default: printf("Wrong choice\n"); } } return 0;}

PROGRAM-4:Searching- Sequential, Binary, Indexed Sequential Searches

PROGRAM-5:Sorting Approaches- Bubble, Quick Sort, Merge Sort, Heap Sort, Selection Sort & Insertion Sort
// Implement Quick sort, merge sort, heap sort, selection sort and // insertion sort #include <stdio.h> int a[50],n,i; void quick_sort(int a[], int low, int high) { int l,h,key,temp,t; key = a[low]; l = low; h = high; while(low < high) { if(a[low] < key) low=low+1; else if(a[high] > key) high=high-1; else { temp = a[low]; a[low] = a[high]; a[high] = temp; } } t = key; key = a[high]; a[high] = t; if(l<high) quick_sort(a,0,high-1); if(low<h) quick_sort(a,high+1,n-1); } void perc_down(int a[], int i, int n) { int child, tmp;

for (tmp = a[i]; i*2 <= n; i=child) { child = i*2; if ((child != n) && (a[child+1] > a[child])) child++; if (tmp < a[child]) a[i] = a[child]; else break; } a[i] = tmp; } void swap(int& a, int &b) { int t = a; a = b; b = t; } void heapsort(int a[], int n) { int i, j; j = n; for (i=n/2; i>0; i--) perc_down(a,i,j); i = 1; for (j=n; j>=2; j--) { swap(a[i], a[j]); perc_down(a,i,j-1); } } void mergesort(int low,int mid,int high) { int i,j,k,temp[50]; i = low; j = mid + 1; k = low; while((i <= mid)&&(j <= high)) { if(a[i] >= a[j])

temp[k++] = a[j++]; else temp[k++]=a[i++]; } while(i <= mid) temp[k++] = a[i++]; while(j <= high) temp[k++] = a[j++]; for(i=low;i<=high;i++) a[i] = temp[i]; for(i=0;i<n;i++) printf("%d ",a[i]); } void msort(int low,int high) { int mid; if(low != high) { mid = ((low+high)/2); msort(low,mid); msort(mid+1,high); mergesort(low,mid,high); } } void insertion(int a[], int n) { int i,j,x,k; for(i=1;i<=n-1;i++) { j = i; x = a[i]; while(a[j-1] > x && j>0) { a[j] = a[j-1]; j = j-1; } a[j] = x; printf("\n\n The array after pass no.%d: ", i); for(k=0;k<=n-1;k++)

printf("%4d",a[k]); } } void selection(int a[], int n) { int i, j, k; int min, temp; for (i = 0; i < n-1; i++) { min = i; for (j = i+1; j < n; j++) { if (a[j] < a[min]) min = j; } temp = a[i]; a[i] = a[min]; a[min] = temp; } } int main() { printf("Enter number of elements: "); scanf("%d",&n); printf("ELEMENTS: \n"); for(i=0;i<n;i++) scanf("%d", &a[i]); quick_sort(a,0,n-1); printf("AFTER SORT\n"); for(i=0;i<n;i++) printf("%d\t",a[i]); printf("\n"); return 0;}

PROGRAM-6:Binary Tree & B-Tree Implementation


#include <stdio.h> #include <stdlib.h> struct AvlNode {

int Element; AvlNode *Left, *Right; int Height; }; AvlNode* MakeEmpty( AvlNode* T ) { if( T != NULL ) { MakeEmpty( T->Left ); MakeEmpty( T->Right ); free( T ); } return NULL; } AvlNode* Find( int X, AvlNode* T ) { if( T == NULL ) return NULL; if( X < T->Element ) return Find( X, T->Left ); else if( X > T->Element ) return Find( X, T->Right ); else return T; } AvlNode* FindMin( AvlNode* T ) { if( T == NULL ) return NULL; else if( T->Left == NULL ) return T; else return FindMin( T->Left ); } AvlNode* FindMax( AvlNode* T ) { if( T != NULL ) while( T->Right != NULL ) T = T->Right; return T; }

int Height( AvlNode* P ) { if( P == NULL ) return -1; else return P->Height; } int Max( int Lhs, int Rhs ) { return Lhs > Rhs ? Lhs : Rhs; } AvlNode* SingleRotateWithLeft( AvlNode* K2 ) { AvlNode* K1; K1 = K2->Left; K2->Left = K1->Right; K1->Right = K2; K2->Height = Max( Height( K2->Left ), Height( K2->Right ) ) + 1; K1->Height = Max( Height( K1->Left ), K2->Height ) + 1; return K1; } AvlNode* SingleRotateWithRight( AvlNode* K1 ) { AvlNode* K2; K2 = K1->Right; K1->Right = K2->Left; K2->Left = K1; K1->Height = Max( Height( K1->Left ), Height( K1->Right ) ) + 1; K2->Height = Max( Height( K2->Right ), K1->Height ) + 1; return K2; } AvlNode* DoubleRotateWithLeft( AvlNode* K3 ) { K3->Left = SingleRotateWithRight( K3->Left ); return SingleRotateWithLeft( K3 ); } AvlNode* DoubleRotateWithRight( AvlNode* K1 ) { K1->Right = SingleRotateWithLeft( K1->Right );

return SingleRotateWithRight( K1 ); } AvlNode* Insert( int X, AvlNode* T ) { if( T == NULL ) { T = (AvlNode*)malloc( sizeof( struct AvlNode ) ); if( T == NULL ) exit(1); else { T->Element = X; T->Height = 0; T->Left = T->Right = NULL; } } else if( X < T->Element ) { T->Left = Insert( X, T->Left ); if( Height( T->Left ) - Height( T->Right ) == 2 ) if( X < T->Left->Element ) T = SingleRotateWithLeft( T ); else T = DoubleRotateWithLeft( T ); } else if( X > T->Element ) { T->Right = Insert( X, T->Right ); if( Height( T->Right ) - Height( T->Left ) == 2 ) if( X > T->Right->Element ) T = SingleRotateWithRight( T ); else T = DoubleRotateWithRight( T ); } T->Height = Max( Height( T->Left ), Height( T->Right ) ) + 1; return T; } int Retrieve( AvlNode* P ) { return P->Element; } int main( ) { AvlNode *T, *P;

int i; int j = 0; T = MakeEmpty( NULL ); for( i = 0; i < 50; i++, j = ( j + 7 ) % 50 ) T = Insert( j, T ); /* for( i = 0; i < 50; i += 2 ) T = Delete( i, T ); */ printf( "Min is %d, Max is %d\n", Retrieve( FindMin( T ) ), Retrieve( FindMax( T ) ) ); return 0; }

PROGRAM-7:Traversal of Tree BFS & DFS, Expression in Tree- in-order, preorder, post-order
// Implement inorder, preorder and postorder traversal of tree #include <stdio.h> #include <stdlib.h> struct node { int data; struct node *lchild,*rchild; }; struct node *insert(struct node *p,int n) { static struct node *temp1,*temp2; if(p == NULL) { p = (struct node*)malloc(sizeof(struct node)); p->data = n; p->lchild = p->rchild = NULL; } else { temp1 = p; while(temp1 != NULL) { temp2 = temp1; if(n < temp1->data) temp1 = temp1->lchild; else temp1 = temp1->rchild; } if(temp2->data > n) { temp2->lchild = (struct node*)malloc(sizeof(struct node)); temp2 = temp2->lchild; temp2->data = n; temp2->lchild = temp2->rchild = NULL; } else

{ temp2->rchild = (struct node*)malloc(sizeof(struct node)); temp2 = temp2->rchild; temp2->data = n; temp2->lchild = temp2->rchild = NULL; } } return p; } void inorder(struct node *p) { if(p != NULL) { inorder(p->lchild); printf("%d ",p->data); inorder(p->rchild); } } void preorder(struct node *p) { if(p != NULL) { printf("%d ",p->data); preorder(p->lchild); preorder(p->rchild); } } void postorder(struct node *p) { if(p != NULL) { postorder(p->lchild); postorder(p->rchild); printf("%d ",p->data); } } int main() { int x,y,i; struct node *root; root = NULL; printf("Enter the no. of nodes in the tree\n");

scanf("%d",&x); while(x-- > 0) { printf("Enter the data part of the node\n"); scanf("%d",&y); root = insert(root,y); } printf("\t\tEnter the traversal:\n"); printf("1.Inorder.\n2.Preorder.\n3.Postorder.\n"); scanf("%d",&i);

switch(i) { case 1: printf("The inorder traversal is:\n"); inorder(root); break; case 2: printf("The preorder traversal is:\n"); preorder(root); break; case 3: printf("The postorder traversal is:\n"); postorder(root); break; } return 0; }

PROGRAM-8:Minimum Spanning Tree Prims & Kruskals Algorithm


#include <stdio.h> #include <stdlib.h> #define MAX 20 #define infinity 9999 struct node { int predecessor; int dist; int status; }; struct edge { int u; int v; }; int adj[MAX][MAX]; int n; void create_graph() { int i,max_edges,origin,destin,wt; printf("Enter number of vertices : "); scanf("%d",&n); max_edges = n*(n-1)/2; for(i=1;i<=max_edges;i++) { printf("Enter edge %d(0 0 to quit) : ", i); scanf("%d %d", &origin, &destin); if((origin == 0) && (destin == 0)) break; printf("Enter weight for this edge : "); scanf("%d",&wt); if( origin > n || destin > n || origin<=0 || destin<=0) { printf("Invalid edge!\n"); i--; }

else { adj[origin][destin]=wt; adj[destin][origin]=wt; } } if(i <= 0) { printf("Spanning tree is not possible\n"); exit(1); } } void display() { int i,j; for(i=1;i<=n;i++) { for(j=1;j<=n;j++) printf("%3d",adj[i][j]); printf("\n"); } } int all_perm(struct node state[MAX]) { int i; for(i=1;i<=n;i++) if( state[i].status == 1) return 0; return 1; } int maketree(struct edge tree[MAX],int *weight) { struct node state[MAX]; int i,k,min,count,current,newdist; int m; int u1,v1; *weight=0; for(i=1;i<=n;i++) {

state[i].predecessor=0; state[i].dist = infinity; state[i].status = 0; } state[1].predecessor=0; state[1].dist = 0; state[1].status = 1; current=1; count=0; while( all_perm(state) != 1 ) { for(i=1;i<=n;i++) { if ( adj[current][i] > 0 && state[i].status == 0) { if( adj[current][i] < state[i].dist ) { state[i].predecessor = current; state[i].dist = adj[current][i]; } } } min=infinity; for(i=1;i<=n;i++) { if(state[i].status == 0&& state[i].dist < min) { min = state[i].dist; current=i; } } state[current].status = 1; u1=state[current].predecessor; v1=current; count++; tree[count].u=u1; tree[count].v=v1; *weight=*weight+adj[u1][v1]; } return (count); } int main() { int i,j;

int path[MAX]; int wt_tree, count; struct edge tree[MAX]; create_graph(); printf("Adjacency matrix is :\n"); display(); count = maketree(tree, &wt_tree); printf("Weight of spanning tree is : %d\n", wt_tree); printf("Edges to be included in spanning tree are : \n"); for(i=1;i<=count;i++) { printf("%d->",tree[i].u); printf("%d\n",tree[i].v); } return 0; }

PROGRAM-9:

PROGRAM-10:Longest common Sequence #include<stdio.h> #include<conio.h> #include<string.h> void print_lcs(char b[][20],char x[],int i,int j) { if(i==0 || j==0) return; if(b[i][j]=='c') { print_lcs(b,x,i-1,j-1); printf(" %c",x[i-1]); } else if(b[i][j]=='u') print_lcs(b,x,i-1,j); else print_lcs(b,x,i,j-1); }

void lcs_length(char x[],char y[]) { int m,n,i,j,c[20][20]; char b[20][20]; m=strlen(x); n=strlen(y); for(i=0;i<=m;i++)

c[i][0]=0; for(i=0;i<=n;i++) c[0][i]=0; for(i=1;i<=m;i++) for(j=1;j<=n;j++) { if(x[i-1]==y[j-1]) { c[i][j]=c[i-1][j-1]+1; b[i][j]='c'; //c stands for left upright cross } else if(c[i-1][j]>=c[i][j-1]) { c[i][j]=c[i-1][j]; b[i][j]='u'; //u stands for upright or above } else { c[i][j]=c[i][j-1]; b[i][j]='l'; //l stands for left } } print_lcs(b,x,m,n); } void lcs() {

int i,j; char x[20],y[20]; printf("1st sequence:"); gets(x); printf("2nd sequence:"); gets(y); printf("\nlcs are:"); lcs_length(x,y); printf("\n"); lcs_length(y,x); } main() { char ch; do { lcs(); printf("\nContinue(y/n):"); ch=getch(); } while(ch=='y'||ch=='Y'); }

Вам также может понравиться