thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web...

171
ASSIGNMENT NO:1 PROBLEM STATEMENT: A Vegetable and Fruit Mall wants to organize its vegetables and fruit products in a combination of purchase pattern of customers. Solve the problem by suggesting appropriate data structures. Design necessary class. AIM:To organize vegetables and fruit products in a combination of purchase pattern of customers. FACILITIES (TOOLS USED):Linux Operating Systems, Turbo C++ / Eclipse framework. ALGORITHM: 1. Start 2. Read the number of Vegetables and fruit product. 3. Print vegetable and fruit items 4. Sort them according to their price. 5. Stop THEORY: 1. To organize vegetables and fruit products in a combination of purchase pattern of customers. 2. Sort them accordingly with their price list. 3. Algorithm Bubble Sort: Bubble(A, N) //Let A be an array with N elements. //This algorithm sorts the elements in array A. Repeat for I = 0 to N: Repeat for J = 0 to N-1: If A[J] > A[J + 1], then Interchange A[J] & A[J +1]. End for

Transcript of thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web...

Page 1: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

ASSIGNMENT NO:1

PROBLEM STATEMENT: A Vegetable and Fruit Mall wants to organize its vegetables and fruit products in a combination of purchase pattern of customers. Solve the problem by suggesting appropriate data structures. Design necessary class.

AIM:To organize vegetables and fruit products in a combination of purchase pattern of customers.

FACILITIES (TOOLS USED):Linux Operating Systems, Turbo C++ / Eclipse framework.

ALGORITHM: 1. Start 2. Read the number of Vegetables and fruit product. 3. Print vegetable and fruit items 4. Sort them according to their price. 5. Stop

THEORY: 1. To organize vegetables and fruit products in a combination of purchase pattern of customers. 2. Sort them accordingly with their price list. 3. Algorithm Bubble Sort: Bubble(A, N)

//Let A be an array with N elements. //This algorithm sorts the elements in array A. Repeat for I = 0 to N: Repeat for J = 0 to N-1: If A[J] > A[J + 1], then Interchange A[J] & A[J +1]. End for End for. End Bubble Sort 5

MATHEMATICAL MODEL: (using set theory)

Page 2: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

RF is the set of pairs (x; y) for which x has purchased fruit y. OR Above we can represent like XRT Y. C and F are two sets and f : CF is fn from C to F. Then Here, G is relation of members of x and y. INPUT: 1. Integer Values as Item codes.

OUTPUT: 1. Price List of items 2. Frequency of item’s cost

FAQ: 1. What is Class and Inheritance? 2. What is sorting? 3. How to sort the element using bubble sort? 4. What is Time complexity of bubble Sort? CONCLUSION: Hence, we have implemented fruit and vegetable organization in a Mall in combination of purchase pattern of customers using class.

NAME OF FACULTY:

SIGNATURE:

DATE:

Page 3: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

PROGRAM CODE

Title:- A Vegetable and Fruit Mall wants to organize its vegetables and fruit products in a combination of purchase pattern of customers. Solve the problem by suggesting appropriate data structures. Design necessary class.

Name: Class:SEDiv: A Roll No: Batch:

#include<stdio.h>#include<conio.h>#include<iostream.h>#include<string.h>#include<stdlib.h>

const int MAX=50;

class veg{public : char V[MAX]; int Vpcount; void accept1(char S[MAX],int P) { strcpy(V,S); Vpcount=P; }

void display1() { cout<<"\n"<<V<<"\t\t"<<Vpcount ; }};

class fruits{public : char F[MAX]; int Fpcount; void accept2(char S[MAX],int P) { strcpy(F,S); Fpcount=P; }

void display2() { cout<<"\n"<<F<<"\t\t"<<Fpcount ; }};

Page 4: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

void sort(veg *Vobj[MAX],fruits *Fobj[MAX],int m, int n ){ char *S1,*S2; int i,j,temp1,temp2;

for(i=0;i<m-1;i++) { for(j=0;j<m-1-i;j++) { if(Vobj[j]->Vpcount<Vobj[j+1]->Vpcount ) { temp1=Vobj[j]->Vpcount; Vobj[j]->Vpcount=Vobj[j+1]->Vpcount; Vobj[j+1]->Vpcount=temp1; strcpy(S1,Vobj[j]->V) ; strcpy(Vobj[j]->V,Vobj[j+1]->V); strcpy(Vobj[j]->V,S1); } } }

cout<<"====================================================";cout<<"\n \tVEGTABLE"<<"\t"<<"\tQUANTITY\n";

cout<<"====================================================";for(i=0;i<m;i++)

{ cout<<"\n\t"<<Vobj[i] ->V<<"\t\t"<<Vobj[i]->Vpcount<<"\n";}

for(i=0;i<n-1;i++) { for(j=0;j<n-1-i;j++) { if(Fobj[j]->Fpcount<Fobj[j+1]->Fpcount ) {

temp2=Fobj[j]->Fpcount; Fobj[j]->Fpcount=Fobj[j+1]->Fpcount; Fobj[j+1]->Fpcount=temp2; strcpy(S2,Fobj[j]->F) ; strcpy(Fobj[j]->F,Fobj[j+1]->F); strcpy(Fobj[j]->F,S2); } } }

cout<<"========================================================"; cout<<"\n\n\t FRUTIS"<<"\t"<<"\tQUANTITY\n";cout<<"=========================================================";

for(i=0;i<n;i++){ cout<<"\n\t"<<Fobj[i]->F<<"\t\t"<<Fobj[i]->Fpcount;}

}

Page 5: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

int main(){int ch;clrscr();veg *vobj[MAX];char vname[MAX];int vcount;

fruits *fobj[MAX];char fname[MAX];int fcount;

int m,n;while(1){cout<<"\n==========================================================\n";cout<<"\t\tWELCOME TO FRUITS AND VEGTABLE MALL\n";cout<<"\n==========================================================\n";cout<<"\n\n\t\t!!!!!!!! Enter your choice !!!!!!!!!\n";cout<<"\n\t\t-> 1 For Accept Vegtable data\n";cout<<"\n\t\t-> 2 For Accept Fruits data \n";cout<<"\n\t\t-> 3 For Display Sorted data\n";cout<<"\n\t\t-> 4 For exit\t";

cin>>ch;switch(ch){case 1 :

cout<<"\nEnter No. Of Items For Vegetable U Want To Enter \t"; cin>>m; for(int i=0;i<m;i++) {

cout<<"\n Enter name of vegetable :- "<<i+1<<"\t"; cin>>vname; cout<<"\n Enter quantity of vegetable :- :"<<i+1<<"\t"; cin>>vcount; vobj[i]=new veg; vobj[i]->accept1(vname,vcount);

} cout<<"\n You Have Entered\n";

for(int x=0;x<m;x++){

vobj[x]->display1();}break;

Page 6: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

case 2 : cout<<"\n Enter No. Of Items For Fruits U Want To Enter\t";cin>>n;for(int j=0;j<n;j++){

cout<<"\n Enter name of Fruit :-"<<j+1<<"\t"; cin>>fname; cout<<"\n Enter quantity of Fruit :-"<<j+1<<"\t"; cin>>fcount; fobj[j]=new fruits; fobj[j]->accept2(fname,fcount);

} cout<<"\n You Have Entered\n";for(int y=0;y<n;y++){

fobj[y]->display2();}

break;case 3 : sort(vobj,fobj,m,n );

break;

case 4 : exit(0);}}

return 0;}

Page 7: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

OUTPUT:-

===================================================================WELCOME TO FRUITS AND VEGTABLE MALL

====================================================================

!!!!!!!! Enter your choice !!!!!!!!!

-> 1 For Accept Vegtable data

-> 2 For Accept Fruits data

-> 3 For Display Sorted data

-> 4 For exit 1

Enter No. Of Items For Vegetable U Want To Enter 3

Enter name of vegtable :- 1 LADYFINGER

Enter quantity of LADYFINGER:= 30

Enter name of vegtable :- 2 SPINICH

Enter quantity of SPINICH:= 10

Enter name of vegtable :- 3 POTATO

Enter quantity of POTATO:= 20

You Have Entered

LADYFINGER 30SPINICH 10POTATO 20

===================================================================WELCOME TO FRUITS AND VEGTABLE MALL

====================================================================

!!!!!!!! Enter your choice !!!!!!!!!

-> 1 For Accept Vegtable data

-> 2 For Accept Fruits data

-> 3 For Display Sorted data

-> 4 For exit 2

Page 8: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

Enter No. Of Items For Fruits U Want To Enter 3

Enter name of Fruit :-1 APPLE

Enter quantity APPLE:= 30

Enter name of Fruit :-2 MANGO

Enter quantity MANGO:= 10

Enter name of Fruit :-3 WATERMELON

Enter quantity WATERMELON:= 20

You Have Entered

APPLE 30MANGO 10WATERMELON 20

===================================================================WELCOME TO FRUITS AND VEGTABLE MALL

====================================================================

!!!!!!!! Enter your choice !!!!!!!!!

-> 1 For Accept Vegtable data

-> 2 For Accept Fruits data

-> 3 For Display Sorted data

-> 4 For exit 3==================================================== VEGTABLE QUANTITY====================================================

LADYFINGER 30

SPINICH 20

POTATO 10

==================================================== FRUITS QUANTITY====================================================

APPLE 30

WATERMELON 20

MANGO 10

Page 9: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

ASSIGNMENT NO:2

PROBLEM STATEMENT: A Dictionary stores keywords & its meanings. Provide facility for adding new keywords, deleting keywords, & updating values of any entry. Also provide facility to display whole data sorted in ascending/ Descending order, Also find how many maximum comparisons may require for finding any keyword. Make use of appropriate data structures.

AIM:To get a Dictionary that stores keywords & its meanings, provide facility for adding new keywords, deleting keywords, & updating values of any entry.

FACILITIES (TOOLS USED):Linux Operating Systems, Turbo C++ / Eclipse Framework. ALGORITHM: 1. Start

2. Read Keyword to insert

3. Perform primitive operation on tree data structure (i.e. insert, delete, search, update)

4. Stop

THEORY: Dictionary is abstract data type consist of (key, value) pair. Following operations can be performed on Dictionary 1. Insert: inserting (key, value) in Dictionary

2. Delete: Deleting key from dictionary

3. Search: Search for value of specified key from dictionary.

4. Update: Update meaning of key in dictionary.

MATHEMATICAL MODEL K is set of keys and M is set of Meanings, K={K1,K2,…Kn} M={M1,M2,….Mn} Each key has exactly one meaning.

Page 10: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

Hence relation is one to one from key set to meaning set. To solve above problem link list or array can be used but insert /delete operation requires O(n) time in link list or array.search operation requires O(n) time in worst case. Insert/delete/search operations requires O(logn) in Binary Search Tree in best or average case. Worst case time for insert/delete search in binary search tree is O(n). Hence, dictionary is implemented here using Binary search tree.

INPUT: Keywords (Words)

OUTPUT: Data in ascending/Descending order

CONCLUSION: We have implemented dictionary using C++ programming.

FAQ: 1. What features are of object oriented programming? 2. What is abstract data type?

NAME OF FACULTY:

SIGNATURE: DATE:

Page 11: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

PROGRAM CODE Title: A Dictionary stores keywords & its meanings. Provide facility for adding new keywords, deleting keywords, & updating values of any entry. Also provide facility to display whole data sorted in ascending/ Descending order, Also find how many maximum comparisons may require for finding any keyword. Make use of appropriate data structures.

Name: Class:SEDiv: ARoll No: Batch:

#include<iostream.h>#include<string.h>#include<stdlib.h>#define MAX 10

struct dic{ char key[50];

char mean[50];}b1[MAX];

int insert(){int i,n;

cout<<"\n\n\t\t How Many Keywords You Wont To Enter:"; cin>>n;

for(i=0;i<=n-1;i++) {

cout<<"\n\t\tEnter The Keyword\n"; cin>>b1[i].key; cout<<"\n\t\tEnter The Meaning Of \t"<<b1[i].key<<"\t"; cin>>b1[i].mean;

}return n;}

void display(int n){

int i;cout<<"\n\n\t\t===========================\n";cout<<"\t\t Keyword \t Meaning\n";cout<<"\t\t===========================\n";for(i=0;i<=n-1;i++){ if(strcmp(b1[i].key,"")!=0) cout<<"\n\t\t "<< b1[i].key<<"\t\t"<< b1[i].mean<<"\t";}

Page 12: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

cout<<"\n\n"; }

void delete1(int n){ int i,x; char a[MAX]; cout<<"\n\t\t Enter The Keyword You Want To Delete\n"; cin>>a; for(i=0;i<n;i++) { x=strcmp(b1[i].key,a); if(x==0)

{ strcpy(b1[i].key,""); strcpy(b1[i].mean,""); cout<<"\n\n\t\t ***** Keyword Deleted *****";

} }}

void sort(int n){

int i,j,x;char w1[MAX];char w2[MAX];

for(j=0;j<n;j++){for(i=0;i<n-1-j;i++){

x=strcmp(b1[i].key,b1[i+1].key); if(x==1)

{ strcpy(w1,b1[i].key);

strcpy(b1[i].key,b1[i+1].key);strcpy(b1[i+1].key,w1);

strcpy(w2,b1[i].mean); strcpy(b1[i].mean,b1[i+1].mean);strcpy(b1[i+1].mean,w2);

} }}cout<<"\n\n\t\t***** DICTIONARY IN SORTED ORDER *****1";cout<<"\n\n\t\t===========================";cout<<"\n\n\t\t Keyword \t Meaning\n";cout<<"\n\n\t\t===========================";for(i=0;i<n;i++) {

Page 13: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

if(strcmp(b1[i].key,"")!=0)cout<<"\n\n\t\t "<<b1[i].key<<"\t\t"<< b1[i].mean<<"\t";

}

}

int update(int n){ int i,x; cout<<"\n\n\t\t How Many Key Words You Wont To Enter:"; cin>>x; if(n+x<MAX) {for(i=n;i<n+x;i++) { cout<<"\n\t\tEnter The Keyword\n"; cin>>b1[i].key; cout<<"\n\t\tEnter The Meaning Of "<<b1[i].key<<"\t"; cin>>b1[i].mean; } } else

cout<<"***** CANNOT UPDATE DATABASE IS FULL *****"; return (n+x);

}

void search(int n){

char w[MAX];int flag=0,cmp=0,i;

cout<<"\n\n\t\tEnter The Keyword You Want To Search:";cin>>w;for(i=0;i<n;i++){

if(strcmp(b1[i].key,"")!=0){

cmp++; if(strcmp(b1[i].key,w)==0)

{flag=1;break;

} }

}if(flag==1){

cout<<"\n\n\t\tThe Word Is Found:\n\n\t\t";cout<<"\n\n\t\t Keyword \t Meaning\n";cout<<b1[i].key<<"\t"<<b1[i].mean;cout<<"\n\n\t\tThe No. Of Comaparison : "<<cmp;

Page 14: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

}}

int main(){

int ch,x;while(1){ cout<<"\n\t\t$==================================================$\n "; cout<<"\n\t\t| ### PROGRAM FOR DICTIONARY ### |\n"; cout<<"\n\t\t| !!! Enter ur choice !!! |\n"; cout<<"\n\t\t| 1:- For Accepting keyword and it's meaning |\n"; cout<<"\n\t\t| 2:- For Display in whole Data |\n"; cout<<"\n\t\t| 3:- For Deleting any keyword |\n"; cout<<"\n\t\t| 4:- For Display Data in Sorted Order |\n"; cout<<"\n\t\t| 5:- For Updating any keyword |\n"; cout<<"\n\t\t| 6:- For Search any keyword |\n"; cout<<"\n\t\t| 7:- For Exit |\n"; cout<<"\n\t\t $=================================================$\n";cin>>ch;switch(ch){case 1:

x=insert();break;

case 2:display(x);break;

case 3:delete1(x);break;

case 4:sort(x);break;

case 5:x=update(x);break;

case 6:search(x);break;

case 7:exit (0);break;

default :cout<<"\n\n\t\t***** ENTERED CORRECT OPTION *****";break;

}}

return 0;}

Page 15: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

OUTPUT :-

program of dictionary

================================

1 for insert

2 for display

3 for delete

4 for sort

5 for update

6 for search

7 for exit

=================================

enter the option:1

how many key words you wont to enter:3

enter the keywordSACHIN

enter the meaning of SACHINDHAMAL

enter the keywordANIKET

enter the meaning of ANIKETDALAL

enter the keywordBALRAM

enter the meaning of BALRAMCHAVAN

program of dictionary

================================

1 for insert

2 for display

3 for delete

4 for sort

5 for update

6 for search

Page 16: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

7 for exit

=================================

enter the option:2

|===========================|

| keyword | meaning |

|===========================|

| SACHIN | DHAMAL |

| ANIKET | DALAL |

| BALRAM | CHAVAN |

|===========================|

program of dictionary

================================

1 for insert

2 for display

3 for delete

4 for sort

5 for update

6 for search

7 for exit

=================================

enter the option:3

enter the keyword you want to deleteBALRAM

keyword deleted:

program of dictionary

================================

1 for insert

2 for display

Page 17: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

3 for delete

4 for sort

5 for update

6 for search

7 for exit

=================================

enter the option:2

|===========================|

| keyword | meaning |

|===========================|

| SACHIN | DHAMAL |

| ANIKET | DALAL |

|===========================|

program of dictionary

================================

1 for insert

2 for display

3 for delete

4 for sort

5 for update

6 for search

7 for exit

=================================

enter the option:2

|===========================|

| keyword | meaning |

|===========================|

Page 18: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

| SACHIN | DHAMAL |

| ANIKET | DALAL |

|===========================|

program of dictionary

================================

1 for insert

2 for display

3 for delete

4 for sort

5 for update

6 for search

7 for exit

=================================

enter the option:5

how many key words you wont to enter:2

enter the keywordKIRAN

enter the meaning of KIRANYADAV

enter the keywordRAMESH

enter the meaning of RAMESHYADAV

program of dictionary

================================

1 for insert

2 for display

3 for delete

4 for sort

5 for update

6 for search

Page 19: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

7 for exit

=================================

enter the option:2

|===========================|

| keyword | meaning |

|===========================|

| SACHIN | DHAMAL |

| ANIKET | DALAL |

| KIRAN | YADAV |

| RAMESH | YADAV |

|===========================|

program of dictionary

================================

1 for insert

2 for display

3 for delete

4 for sort

5 for update

6 for search

7 for exit

=================================

enter the option:4

!!!!!!!dictionary in sorted order!!!!!!!!

|===========================|

|keyword | meaning |

|===========================|

| ANIKET | DALAL |

Page 20: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

| KIRAN | YADAV |

| RAMESH | YADAV |

| SACHIN | DHAMAL |

|===========================|

program of dictionary

================================

1 for insert

2 for display

3 for delete

4 for sort

5 for update

6 for search

7 for exit

=================================

enter the option:6

enter the keyword you want to search:RAMESH

the word is found:

keyword meaningRAMESH YADAV

the no of comaparison : 3

Page 21: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

program of dictionary

================================

1 for insert

2 for display

3 for delete

4 for sort

5 for update

6 for search

7 for exit

=================================

enter the option:7

Page 22: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

ASSIGNMENT NO:3 PROBLEM STATEMENT: A news paper delivery boy every day drops news paper in a society having many lanes & each lane have many houses. Design a program to provide different paths that he could follow & also suggest the path which will make him to finish his task with less effort. Solve the problem by suggesting appropriate data structures. Design necessary class.

AIM: 1. To find a path for the newspaper delivery boy this will make him to finish his task with less effort. 2. Finding Minimum Spanning Tree Using Prim’s Algorithm.

FACILITIES (TOOLS USED):Linux Operating System, Turbo C++/ Eclipse Framework. ALGORITHM: Create Function: Step 1: Start. Step 2: Create char, integer variable. Step 3: Take how many vertices of graph and then take vertices ofedges and cost of edges. Step 4: Store zero in visited array and matrix array for graph. Step 5: Vertex is -99 then break loop, otherwise stored arrayg[v1][v2]=cost. If cost is stored then also g[v2][v1] alsostore same cost. Step 6: Ask user whether he wants to enter more edges if ‘Yes’ thengoto Step 7. Step 7: Stop.

Display Function: Step 1: Start. Step 2: Using two for loop print cost of edges of matrix array onscreen. Step 3: Stop

Prims Function: Step 1: Start. Step 2: Initially declare cost, matrix, visited from distance array. Step 3: Using two for loop check if edge is present or not. If notthen stored infinity value else stored

cost of G matrix incost matrix and then stored zero in st matrix. Step 4: Take first vertex and using for take all distances in from thatvertex in distance array and put

zero in from and visited arrayat that vertex position. Step 5: Initialize min cost =0 and no of edge=n-1. Step 6: Using while loop take min distance infinity and again use forloop, check vertex is not visited and distance of that vertexis less min distance. If true then v = i and min distance=thatdistance.Step 7: Stored that cost in st matrix for both vertices, edges anddecrease no of edge. Visited array is initialized = 1. Step 8: Using for loop check vertex is not visited and distance isminimum. If true then stored that vertex in from array andCost of that edges in distance array. Step 9: Add all min cost stored in min cost and return min cost. Stop 10: Stop.

Page 23: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

Main Function: Step 1: Start. Step 2: Create object of graph and Integer and character variables. Step 3: Print Menu like

1. Create. 2. Display. 3. Spanning Tree and find minimum cost.

Step 4: Take choice from user. Step 5: If choice is 1 then call Create Function. Step 6: If choice is 2 then call Display Function. Step 7: If choice is 3 then call prims Function. Step 8: Ask user whether he wants to continue or not. Step 9: If yes then go to step 3. Step 10: Stop.

THEORY: 1. Create a tree containing a single vertex, chosen arbitrarily from the graph

2. Create a set containing all the edges in the graph

3. Loop until every edge in the set connects two vertices in the tree a. Remove from the set an edge with minimum weight that connects a vertex in the tree with a vertex not in the tree

b. Add that edge to the tree

INPUT 1. Weighted Graph with number of lanes i. e. edges and number of houses i. e. vertices

2. Starting house i. e. starting vertex.

OUTPUT 1. Minimum spanning tree of given weighted graph.

FAQ: 1. What is shortest path algorithm?

2. What is minimum spanning tree of a graph?

3. How to calculate shortest path of graph?

CONCLUSION: Thus, we have implemented minimum spanning tree algorithm for newspaper delivery boy tofind outpath which will cover all houses with less efforts.

NAME OF FACULTY:

SIGNATURE: DATE:

Page 24: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

PROGRAM CODE

Title: Name: A news paper delivery boy every day drops news paper in a society having many lanes & each lane have many houses. Design a program to provide different paths that he could follow & also suggest the path which will make him to finish his task with less effort. Solve the problem by suggesting appropriate data structures. Design necessary class.

Name: Class:SEDiv: ARoll No: Batch:

#include<iostream.h>#include<stdlib.h>

#define MAX 50#define INF 99999

struct table{ int dist; int pred; int status;};

struct edges{ int sr; //staring vertex int dt; //last vertex};class graph{ int n; int e; int adj[MAX][MAX]; public : graph()

{ n=0; e=0;

} void create(); void prim_mst(); };

void graph::create(){ cout<<"\n enter no. of houses \n"; cin>>n; int i,j,v1,v2,w=0; for(i=0;i<n;i++) { for(j=0;j<n;j++) { adj[i][j]=0;

Page 25: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

} } cout<<"\n enter no. of lanes\n"; cin>>e; for(i=0;i<e;i++) { cout<<"\n enter lane in v1,v2 form\n"; cin>>v1>>v2; cout<<"\n enter weight of Lane\n"; cin>>w; adj[v1][v2]=w; adj[v2][v1]=w; }}

void graph::prim_mst(){ int i;

struct table tab[MAX];struct edges ed[MAX];int cnt=0,wt=0;for(i=0;i<n;i++) {

tab[i].dist=INF;tab[i].pred=0;tab[i].status=0;

}int v=0;tab[v].dist=0;tab[v].status=1;cout<<tab[v].status;while(1)

{for(i=0;i<n;i++)

{if(adj[v][i]!=0){

if(tab[i].status==0){

if(tab[i].dist>adj[v][i]){

tab[i].dist=adj[v][i];tab[i].pred=v;

}}

}}

int minv=-1;int mind=INF;for(i=0;i<n;i++){

if(adj[v][i]!=0){

if(tab[i].status==0){

if(mind >tab[i].dist){

mind=tab[i].dist;

Page 26: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

minv=i;}

}}

}if(minv!=-1){

tab[minv].status=1;ed[cnt].sr=v;ed[cnt].dt=minv;wt=wt+adj[v][minv];cnt++;v=minv;

}else{

break;}

} cout<<"\n The o/p is :"; for(i=0;i<cnt;i++) {

cout<<"\n H "<<ed[i].sr<<"-->H "<<ed[i].dt<<"\n"; } cout<<"\n The Cost Of MST Is :"<<wt;

}int main(){ int ch; graph g;

while(1) { cout<<"\n\t\t 1 for create graph\n"; cout<<"\n\t\t 2 for prims_mst\n"; cout<<"\n\t\t 3 for exit\n"; cout<<"\n\t\t Enter Your Choice"; cin>>ch; switch(ch) { case 1 : g.create();

break; case 2 :g.prim_mst(); break; case 3 : exit(0);

break; default : cout<<"\n !!!! enterd wrong option !!!!"; break; } }return 0;}

Page 27: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

OUTPUT :-

1 for create graph

2 for prims_mst

3 for exit

Enter Your Choice1

enter no. of houses 5

enter no. of lanes8

enter lane in v1,v2 form0 1

enter weight of Lane3

enter lane in v1,v2 form1 2

enter weight of Lane3

enter lane in v1,v2 form2 3

enter weight of Lane4

enter lane in v1,v2 form3 0

enter weight of Lane3

enter lane in v1,v2 form3 4

enter weight of Lane1

enter lane in v1,v2 form4 1

enter weight of Lane2

enter lane in v1,v2 form0 4

enter weight of Lane

Page 28: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

2

enter lane in v1,v2 form4 2

enter weight of Lane1

1 for create graph

2 for prims_mst

3 for exit

Enter Your Choice21 The o/p is : H 0-->H 4 H 4-->H 2 H 2-->H 3 The Cost Of MST Is :7

1 for create graph

2 for prims_mst

3 for exit

Enter Your Choice3

Page 29: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

ASSIGNMENT NO:4

PROBLEM STATEMENT: Extending to problem 2. Consider dictionary data is stored in a file in random order. Thus, to search any word & its meanings from given data, program should create reasonably balanced tree (AVL Tree).

AIM: To study the concept of AVL tree and its implementation and its application in Computer Science.

FACILITIES (TOOLS USED):Linux Operating System, Turbo C ++/ Eclipse

ALGORITHM:

Insertion To make sure that the given tree remains AVL after every insertion, we must augment the standard BST insert operation to perform some re-balancing. Following are two basic operations that can be performed to re-balance a BST without violating the BST property (keys(left) < key(root) < keys(right)). 1) Left Rotation 2) Right Rotation T1, T2 and T3 are subtrees of the tree rooted with y (on left side) or x (on right side) y x / \ Right Rotation / \ x T3 – - – - – - – > T1 y / \ < - - - - - - - / \ T1 T2 Left Rotation T2 T3 Keys in both of the above trees follow the following order keys(T1) < key(x) < keys(T2) < key(y) < keys(T3) So BST property is not violated anywhere.

Steps to follow for insertion Let the newly nserted node be w 1) Perform standard BST insert for w. 2) Starting from w, travel up and find the first unbalanced node. Let z be the first unbalanced node, y be the child of z that comes on the path from w to z and x be the grandchild of z that comes on the path from w to z. 3) Re-balance the tree by performing appropriate rotations on the subtree rooted with z. There can be 4 possible cases that needs to be handled as x, y and z can be arranged in 4 ways. Following are the possible 4 arrangements: a) y is left child of z and x is left child of y (Left Left Case) b) y is left child of z and x is right child of y (Left Right Case) c) y is right child of z and x is right child of y (Right Right Case) d) y is right child of z and x is left child of y (Right Left Case) Following are the operations to be performed in above mentioned 4 cases. In all of the cases, we only need to re-balance the subtree rooted with z and the complete tree becomes balanced as the height of subtree (After appropriate rotations) rooted with z becomes same as it was before insertion.

a) Left Left Case T1, T2, T3 and T4 are subtrees. z y / \ / \ y T4 Right Rotate (z) x z / \ - - - - - - - - -> / \ / \

Page 30: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

x T3 T1 T2 T3 T4 / \ T1 T2 b) Left Right Case z z x / \ / \ / \ y T4 Left Rotate (y) x T4 Right Rotate(z) y z / \ - - - - - - - - -> / \ - - - - - - - -> / \ / \

T1 x y T3 T1 T2 T3 T4 / \ / \ T2 T3 T1 T2 c) Right Right Case z y / \ / \ T1 y Left Rotate(z) z x / \ - - - - - - - -> / \ / \ T2 x T1 T2 T3 T4 / \ T3 T4 d) Right Left Case z z x / \ / \ / \ T1 y Right Rotate (y) T1 x Left Rotate(z) z x / \ - - - - - - - - -> / \ - - - - - - - -> / \ / \ x T4 T2 y T1 T2 T3 T4 / \ / \ T2 T3 T3 T4

deletion. To make sure that the given tree remains AVL after every deletion, we must augment the standard BST delete operation to perform some re-balancing. Following are two basic operations that can be performed to re-balance a BST without violating the BST property (keys(left) < key(root) < keys(right)). 1) Left Rotation 2) Right Rotation T1, T2 and T3 are subtrees of the tree rooted with y (on left side) or x (on right side) y x / \ Right Rotation / \ x T3 – – – – – – – > T1 y

/ \ < - - - - - - - / \ T1 T2 Left Rotation T2 T3 Keys in both of the above trees follow the following order keys(T1) < key(x) < keys(T2) < key(y) < keys(T3) So BST property is not violated anywhere. Let w be the node to be deleted 1) Perform standard BST delete for w. 2) Starting from w, travel up and find the first unbalanced node. Let z be the first unbalanced node, y be the larger height child of z, and x be the larger height child of y. Note that the definitions of x and y are different from insertion here. 3) Re-balance the tree by performing appropriate rotations on the subtree rooted with

Page 31: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

z. There can be 4 possible cases that needs to be handled as x, y and z can be arranged in 4 ways. Following are the possible 4 arrangements: a) y is left child of z and x is left child of y (Left Left Case) b) y is left child of z and x is right child of y (Left Right Case) c) y is right child of z and x is right child of y (Right Right Case) d) y is right child of z and x is left child of y (Right Left Case) Like insertion, following are the operations to be performed in above mentioned 4 cases. Note that, unlike insertion, fixing the node z won’t fix the complete AVL tree. After fixing z, we may have to fix ancestors of z as well

a) Left Left Case T1, T2, T3 and T4 are subtrees. z y / \ / \ y T4 Right Rotate (z) x z / \ - - - - - - - - -> / \ / \ x T3 T1 T2 T3 T4 / \ T1 T2

b) Left Right Case z z x/ \ / \ / \ y T4 Left Rotate (y) x T4 Right Rotate(z) y z / \ - - - - - - - - -> / \ - - - - - - - -> / \ / \ T1 x y T3 T1 T2 T3 T4 / \ / \ T2 T3 T1 T2

c) Right Right Case z y / \ / \ T1 y Left Rotate(z) z x / \ - - - - - - - -> / \ / \ T2 x T1 T2 T3 T4 / \ T3 T4

d) Right Left Case z z x / \ / \ / \ T1 y Right Rotate (y) T1 x Left Rotate(z) z x / \ - - - - - - - - -> / \ - - - - - - - -> / \ / \ x T4 T2 y T1 T2 T3 T4 / \ / \ T2 T3 T3 T4 Unlike insertion, in deletion, after we perform a rotation at z, we may have to perform a rotation at ancestors of z. Thus, we must continue to trace the path until we reach the root.

Page 32: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

THEORY:

AVL tree:In computer science, an AVL tree is a self-balancing binarysearch tree, and it was the first such data structure to be invented. Inan AVL tree, the heights of the two child subtrees of any node differ byat most one.

Advantages of AVL Tree: Lookup, insertion, and deletion all take O(log n) time in both the average and worst cases, where n is the number of nodes in the tree prior to the operation. Insertions and deletions may require the tree to be rebalanced by one or more tree rotations. The AVL tree is named after its two soviet inventors, G.M. Adelson- Velskii and E.M. Landis, who published it in their 1962 paper "An algorithm for the organization of information. The balance factor of a node is the height of its left subtree minus the height of its right subtree (sometimes opposite) and a node with balance factor 1, 0, or −1 is considered balanced. A node with any other balance factor is considered unbalanced and requires rebalancing the tree. The balance factor is either stored directly at each node or computed from the heights of the subtrees. AVL trees are often compared with red-black trees because they support the same set of operations and because red-black trees also take O(log n) time for the basic operations. AVL trees perform better than red-black trees for lookup-intensive applications. The AVL tree balancing algorithm appears in many computer science curricula.

Operations on AVL Tree: Search: Lookup in an AVL tree is performed exactly as in an unbalanced binary search tree. Because of the height-balancing of the tree, a lookup takes O(log n) time. No special actions need to be taken, and the tree's structure is not modified by lookups. (This is in contrast to splay tree lookups, which do modify their tree's structure.) If each node additionally records the size of its subtree (including itself and its descendants), then the nodes can be retrieved by index in O(log n) time as well. Once a node has been found in a balanced tree, the next or previous nodes can be explored in amortized constant time. A few cases require traversing up to 2×log(n) links. However exploring all n nodes in the tree in this manner would use each link exactly twice, and there aren−1 links, so the amortized cost is 2×(n−1)/n, approximately 2. Insert: After inserting a node, it is necessary to check each of the node's ancestors for consistency with the rules of AVL. For each node checked, if the balance factor remains −1, 0, or +1 then no rotations are necessary. However, if the balance factor becomes ±2 then the subtree rooted at thisnode is unbalanced. If insertions are performed serially, after each insertion, at most two tree rotations are needed to restore the entire tree to the rules of AVL. There are four cases which need to be considered, of which two are symmetric to the other two. Let P be the root of the unbalanced subtree. Let R be the right child of P. Let L be the left child of P.

Right-Right case and Right-Left case: If the balance factor of P is −2, then the right subtree outweighs the left subtree of the givennode, and the balance factor of the right child (R) must be checked. Ifthe balance factor of R is ≤ 0, a left rotation is needed with P as theroot. If the balance factor of R is +1, a double left rotation (withrespect to P) is needed. The first rotation is a right rotation with R asthe root. The second is a left rotation with P as the root.

Left-Left case and Left-Right case: If the balance factor of P is +2, then the left subtree outweighs the right subtree of the given node, and the balance factor of the left child (L) must be checked. If the balance factor of L is ≥ 0, a right rotation is needed with P as the root. If the balance factor of L is −1, a double right rotation (with

Page 33: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

respect to P) is needed. The first rotation is a left rotation with L as the root. The second is a right rotation with P as the root.Algorithms for all the above four cases can be found here.

Rotation Algorithms for putting an out-of-balance AVL-treeback in balance: Note: After the insertion of each node the tree should bechecked for balance. The only nodes that need checked are the onesalong the insertion path of the newly inserted node. Once the tree isfound to be out-of-balance then re-balance it using the appropriatealgorithm. If the out-of-balance is detected as soon as it happens andthe proper algorithm is used then the tree will be back in balance afterone rotation.

Deletion: If the node is a leaf or has only one child, remove it. Otherwise,replace it with either the largest in its left subtree (inorderpredecessor) or the smallest in its right subtree (inorder successor),and remove that node. The node that was found as a replacement has at most one subtree. After deletion, retrace the path back up the tree(parent of the replacement) to the root, adjusting the balance factorsas needed.As with all binary trees, a node's in-order successor is the leftmostchildof its right subtree, and a node's in-order predecessor is theright-most child of its left subtree. In either case, this node will havezero or one children. Delete it according to one of the two simplercases above.Deleting a node with two children from a binary search treeIn addition to the balancing described above for insertions, if thebalance factor for the tree is 2 and that of the left subtree is 0, a rightrotation must be performed on P. The mirror of this case is alsonecessary.The retracing can stop if the balance factor becomes −1 or +1indicating that the height of that subtree has remained unchanged. Ifthe balance factor becomes 0 then the height of the subtree hasdecreased by one and the retracing needs to continue. If the balancefactor becomes −2 or +2 then the subtree is unbalanced and needs tobe rotated to fix it. If the rotation leaves the subtree's balance factorat 0 then the retracing towards the root must continue since theheight of this subtree has decreased by one. This is in contrast to aninsertion where a rotation resulting in a balance factor of 0 indicatedthat the subtree's height has remained unchanged.The time required is O(log n) for lookup, plus a maximum of O(logn) rotations on the way back to the root, so the operation can becompleted in O(log n) time.

INPUT: A text file containing Dictionary Database ie Word and its Meaning

OUTPUT: The Height Balanced Tree (AVL Tree) containing node value as word and its Meaning.

FAQ: 1. What is an AVL tree?

2. Explain rotations used in AVL tree?

3. Explain advantages of AVL tree?

CONCLUSION: Thus we have designed a dictionary using AVL tree.

NAME OF FACULTY:

SIGNATURE:

DATE:

Page 34: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

PROGRAM CODE

Title:Consider dictionary data is stored in a file in random order. Thus, to search any the word & its meanings from given data, program should create reasonably balanced tree (AVL tree).

Name: Class:SEDiv: ARoll No: Batch:

#include<iostream>#include<string.h>using namespace std;class diction{ char word[20],mean[40]; diction *left,*right; int ht; public:

diction* create(diction *);diction* insert(diction *,char *,char *);diction* Delete(diction *,char *);diction* RR(diction *);diction* LL(diction *);diction* LR(diction *);diction* RL(diction *);int height(diction *);void display(diction *);diction* rotateright(diction *);

diction* rotateleft(diction *);int BF(diction *);

};

diction* diction::create(diction *T){

int n,i;char w[20],m[50];cout<<"\n Enter the number of words";cin>>n;for(i=0;i<n;i++){

cout<<"\n Enter word "<<i+1<<" :";cin>>w;cout<<"\n Enter the meaning : ";cin>>m;T=insert(T,w,m);

}return T;

}

diction *diction::insert(diction *T,char w[],char m[]){

if(T==NULL)

Page 35: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

{T=new diction;strcpy(T->word,w);strcpy(T->mean,m);T->left=NULL;T->right=NULL;

}else{ if(strcmp(w,T->word)>0) {

T->right=insert(T->right,w,m);if(BF(T)==-2){ if(strcmp(w,T->right->word)>0) T=RR(T); else T=RL(T);}

} else {

if(strcmp(w,T->word)<0){ T->left=insert(T->left,w,m); if(BF(T)==2) { if(strcmp(w,T->left->word)<0) T=LL(T); else T=LR(T); }}

}}T->ht=height(T);return (T);

}

diction * diction::Delete(diction *T,char w[]){ diction *p; if(T==NULL)

{ cout<<"\n Word not found"; return NULL;

}else if(strcmp(w,T->word)>0){ T->right=Delete(T->right,w); if(BF(T)==2) { if(BF(T->left)>=0) T=LL(T); else T=LR(T);

Page 36: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

}}else if(strcmp(w,T->word)<0){

T->left=Delete(T->left,w); if(BF(T)==-2)

{ if(BF(T->right)<=0) T=RR(T); else T=RL(T);}

}else{if(T->right!=NULL){

p=T->right; while(p->left!=NULL) p=p->left; strcpy(T->word,p->word); strcpy(T->mean,p->mean); T->right=Delete(T->right,p->word); if(BF(T)==2) { if(BF(T->left)>=0)

T=LL(T); else

T=LR(T); }}elsereturn (T->left);}T->ht=height(T);return(T);

}

diction* diction::LL(diction *T){

T=rotateright(T);return (T);

}

diction* diction::RR(diction *T){

T=rotateleft(T);return (T);

}

diction* diction::LR(diction *T){

T->left=rotateleft(T->left);T=rotateright(T);return (T);

}

Page 37: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

diction* diction::RL(diction *T){

T->right=rotateright(T->right);T=rotateleft(T);return (T);

}

diction* diction::rotateright(diction *x){

diction *y;y=x->left;x->left=y->right;y->right=x;x->ht=height(x);y->ht=height(y);return(y);

}

diction* diction::rotateleft(diction *x){

diction *y;y=x->right;x->right=y->left;y->left=x;x->ht=height(x);y->ht=height(y);return (y);

}

int diction::BF(diction *T){

int lh,rh;if(T==NULL)return(0);if(T->left==NULL)lh=0;elselh=1+T->left->ht;if(T->right==NULL)rh=0;elserh=1+T->right->ht;int z=lh-rh;return (z);

}

void diction::display(diction *T){

if(T!=NULL){display(T->left);cout<<"\n"<<T->word<<" : "<<T->mean<<"(BF="<<BF(T)<<")";display(T->right);}

}

Page 38: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

int diction::height(diction *T){

int lh,rh;if(T==NULL)return 0;if(T->left==NULL)lh=0;elselh=1+T->left->ht;if(T->right==NULL)rh=0;elserh=1+T->right->ht;if(lh>rh){return (lh);}else{return (rh);}

}int main(){

diction d,*root;char w[20],m[40];root=NULL;int ch;do{cout<<"\n 1.Create \n 2.Insert \n 3.Delete \n 4.Display \n 5.Exit";cout<<"\n Enter a choice";cin>>ch;switch(ch){ case 1:root=d.create(root); break; case 2:cout<<"\n Enter word :"; cin>>w; cout<<"\n Enter the meaning : "; cin>>m; root=d.insert(root,w,m); break; case 3:cout<<"\n Enter which word you want to delete :"; cin>>w; root=d.Delete(root,w); break; case 4:d.display(root); break; case 5:break; default:cout<<"\n Invalid choice";}

}while(ch!=5);return 0;}

Page 39: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

OUTPUT :-

1.Create 2.Insert 3.Delete 4.Display 5.Exit Enter a choice1

Enter the number of words3

Enter word 1 :ANIKET

Enter the meaning : DALAL

Enter word 2 :SACHIN

Enter the meaning : DHAMAL

Enter word 3 :BALRAM

Enter the meaning : CHAVAN

1.Create 2.Insert 3.Delete 4.Display 5.Exit Enter a choice4

ANIKET : DALAL(BF=0)BALRAM : CHAVAN(BF=0)SACHIN : DHAMAL(BF=0) 1.Create 2.Insert 3.Delete 4.Display 5.Exit Enter a choice2

Enter word :RAMESH

Enter the meaning : YADAV

1.Create 2.Insert 3.Delete 4.Display 5.Exit Enter a choice4

ANIKET : DALAL(BF=0)BALRAM : CHAVAN(BF=-1)RAMESH : YADAV(BF=0)SACHIN : DHAMAL(BF=1)

Page 40: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

1.Create 2.Insert 3.Delete 4.Display 5.Exit Enter a choice3

Enter which word you want to delete :BALRAM

1.Create 2.Insert 3.Delete 4.Display 5.Exit Enter a choice4

ANIKET : DALAL(BF=0)RAMESH : YADAV(BF=0)SACHIN : DHAMAL(BF=0) 1.Create 2.Insert 3.Delete 4.Display 5.Exit Enter a choice5

Page 41: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

ASSIGNMENT NO:5

PROBLEM STATEMENT: Write a program using object oriented programming features to implement doubly circular linked list with different manipulation facilities in C++.

AIM: To understand the data structure link list and its variations and operations.

FACILITIES (TOOLS USED):Linux Operating System, Turbo C++, Eclipse Framework. ALGORITHM: [A] Algorithm for Inserting a node after or before particular node in CDLL (Circular Doubly Linked List). PROCEDURE INSERT_CDLL(T, KEY, POS) [Where pointer ‘T’ is a pointer which can be either pointing tofirst in or lasting element and key is the value after or before uwant to insert new node and pos is a variable which is givingdirection ‘right’ or ‘left’ of key value.] 1. [Checking the value of pointer and traversing the destination] if (T==HEAD) while (DATA(T) != KEY) T <-- RIGHT (T) else while (DATA(T) != KEY) T <-- LEFT (T). 2. [Inserting an element to the right of the destination] if (POS == ‘R’) if (T == P) Call GETNODE (S) DATA (S) <-- ‘xyz’RIGHT (P) <-- S LEFT (S) <-- P RIGHT (S) <-- HEAD LEFT (HEAD) <-- S P <-- S else Call GETNODE (S) DATA (S) <-- ‘xyz’ RIGHT (S) <-- RIGHT (T) LEFT (S) <-- T RIGHT (T) <-- S LEFT (RIGHT(S)) <-- S P <-- S. 3. [Inserting an element to the left side of destination] else if (T == HEAD) Call GETNODE (S) DATA (S) <-- ‘xyz’ RIGHT (S) <-- HEAD LEFT (HEAD) <-- S LEFT (S) <-- P RIGHT (P) <-- S HEAD <-- S else

Page 42: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

Call GETNODE (S) DATA (S) <-- ‘xyz’ RIGHT (S) <-- T LEFT (S) <-- LEFT (T) LEFT (T) <-- S RIGHT (LEFT(S)) <-- S.4. [FINISH] Return [B] Algorithm for Deleting a particular node in CDLL(Circular Doubly Linked List). PROCEDURE DELETE_CDLL(T, KEY) [Where pointer ‘T’ is a pointer which is pointing to first in orlasting element and key is the value which we want to delete.] 1. [Checking the value of pointer and traversing the estination] if (T==HEAD) while (DATA(T) != KEY) T <-- RIGHT (T) else while (DATA(T) != KEY) T <-- LEFT (T). 2. [Deleting node from the list]. Q <-- LEFT (T) RIGHT (Q) <-- RIGHT (T) LEFT (RIGHT(T)) <-- Q if (T == HEAD) HEAD <-- RIGHT (HEAD) else if (T == P) P <-- LEFT (P) Call REMOVE NODE (T). 3. [FINISH] return.[C] Algorithm for displaying node’s data in CDLL(Circular Doubly Linked List). PROCEDURE DISPLAY_CDLL(T) [Where pointer ‘T’ is a pointer which is pointing to first element.] 1. [Checking the value of pointer , displaying and traversing] if(T!=NULL) do PRINT DATA(T) T <-- RIGHT(T) while (T!=HEAD) THEORY: Linked List A linked list is a data structure consisting of a group of nodes which together represent a seequence. Under the simplest form, each node is composed of a data and a reference (in other words, alink) to the next node in the sequence.Linked lists are among the simplest and most common data structures. They can be used toimplement several other common abstract data types, including lists (the abstract data type), stacks,queues, etc. The principal benefit of a linked list over a conventional array is that the list elements caneasily be inserted or removed without reallocation or reorganization of the entire structure because thedata items need not be stored contiguously in memory. Types of linked list:

1) Singly linked list: Singly linked lists contain nodes which have a data field as well as a next field, which points to the next node in the linked list.

Page 43: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

2) Doubly linked list: In a doubly linked list, each node contains, besides the next-node link, a second link field pointing to the previous node in the sequence. The two links may be called forward(s) and backwards, or next and prev(ious).

3) Circular linked list: In the last node of a list, the link field often contains a null reference, a special value used to indicate the lack of further nodes. A less common convention is to make it point to the first node of the list; in that case the list is said to be circular or circularly linked; otherwise it is said to be open or linear.

4) A circular doubly-linked list: A circular list is formed by making use of variables which would otherwise be null: The last element of the list is made the predecessor of the first element; the first element, the successor of the last.

Applications : 1. We can use circular linked list in any application where the entries appear in a rotating

manner. 2. Circular linked list is the basic idea of round robin scheduling algorithm. 3. A circular linked list can be effectively used to create a queue (FIFO) or a deque (efficient insert and remove from front and back).

Page 44: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

INPUT: 1. Integer Data Values such as 1,2,3,……n

OUTPUT : 1. Doubly Circular Linked List containing node values as given integer data values.

FAQ: 1. What is linked list? 2. What is the difference between Array and Linked List? 3. What are different types of Linked List? 4. What is mean by Dynamic Memory Allocation? 5. What are the advantages of Linked List?

CONCLUSION: Thus we have implemented doubly circular linked list.

NAME OF FACULTY:

SIGNATURE:

DATE:

Page 45: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

PROGRAM CODE

Title:Write a program using object oriented programming features to implement doubly circular linked list with different manipulation facilities in C++. Name: Class: SEDiv: ARoll No: Batch:

#include<iostream.h>#include<stdlib.h>

struct node{

struct node *llink;int data;struct node *rlink;

};class DCLL{private:

struct node *head;public:

DCLL(){

head=NULL;}

struct node *getnode(){

struct node *temp;temp=(struct node*)malloc(sizeof(struct node));temp->rlink=NULL;temp->llink=NULL;return temp;

}struct node *create();void display (struct node *);struct node*insert(struct node*);struct node*delete1(struct node*);int count(struct node*);

};struct node *DCLL ::create(){

int n,i;struct node *newnode,*first;cout<<"\n Enter no. of nodes : ";cin >>n;for (i=0;i<n;i++){

newnode=getnode();cout<<"\n Enter data : ";cin>>newnode->data;

Page 46: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

if(head==NULL){

head=newnode;head->rlink=head;head->llink=head;first=head;

}else{

first->rlink=newnode;newnode->llink=first;newnode->rlink=head;head->llink=newnode;first=newnode;

}}return head;

}void DCLL ::display(struct node *head){

if(head==NULL){

cout<<"\n!!! DCLL IS EMPTY - CANNOT DISPLAY !!!";}else{

struct node *temp;temp=head;while(temp->rlink!=head){

cout<<"\t"<<temp->data;temp=temp->rlink;

}cout<<"\t"<<temp->data;

}}int DCLL::count(struct node*head){

int cnt=0;if(head==NULL){

cout<<"\n NO.OF NODES IS :"<<cnt;return cnt;

}else{

struct node *temp;temp=head;while(temp->rlink!=head){

cnt++;temp=temp->rlink;

}return (cnt+1);

}}

Page 47: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

struct node *DCLL::insert(struct node *head){

int i,pos,n;struct node *newnode,*first;n=count(head);newnode=getnode();cout<<"\n Enter Data : ";cin>>newnode->data;cout<<"\nEnter position :";cin>>pos;if(pos==1){

first=head;newnode->rlink=first;first->llink=newnode;while(first->rlink!=head){

first=first->rlink;}first->rlink=newnode;newnode->llink=first;head=newnode;

}else{

if(pos<=n){

first=head;for(i=1;i<pos-1;i++){

first=first->rlink;}newnode->rlink=first->rlink;first->rlink->llink=newnode;first->rlink=newnode;newnode->llink=first;

}else{

if(pos>n){

first=head;while(first->rlink!=head){

first=first->rlink;}first->rlink=newnode;newnode->llink=first;newnode->rlink=head;head->llink=newnode;

}}

}return head;

}struct node *DCLL::delete1(struct node *head){

Page 48: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

int i,n,pos;struct node *temp,*first;cout<<"\n Enter position\t";cin>>pos;if(pos==1){

temp=head;first=head;while(first->rlink!=head){

first=first->rlink;}first->rlink=temp->rlink;temp->rlink->llink=first;head=temp->rlink;free(temp);

}else{

if(pos<n){

first=head;for(i=1;i<pos-1;i++){

first=first->rlink;}temp=first->rlink;first->rlink=temp->rlink;temp->rlink->llink=first;temp->rlink=NULL;free(temp);

}else{

if(pos==n){

first=head;for(i=1;i<pos-1;i++){

first=first->rlink;}temp=first->rlink;first->rlink=head;head->llink=first;temp->rlink=NULL;free(temp);

}}

}return head;

}int main(){

DCLL d;int n,ch;struct node *temp;temp=NULL;

Page 49: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

while(1){cout<<"\n\t\t$=================================$\n ";cout<<"\n\t\t| $$$ WELCOME TO DCLL MENU $$$ |\n";cout<<"\n\t\t| 1. FOR CREATE NEW NODE |\n";cout<<"\n\t\t| 2. FOR DISPLAY CONTENT OF DCLL |\n";cout<<"\n\t\t| 3. FOR COUNT NO. OF NODES |\n";cout<<"\n\t\t| 4. FOR INSERT NEW NODE |\n";cout<<"\n\t\t| 5. FOR DELETE NODE |\n";cout<<"\n\t\t| 6. FOR EXIT |\n";cout<<"\n\t\t| ### ENTER CHOICE U WANT ### |\n ";cout<<"\n\t\t$================================$\n";cin>>ch;

switch(ch){case 1:

temp=d.create();break;

case 2:d.display(temp);break;

case 3:n=d.count(temp);break;

case 4:temp=d.insert(temp);d.display(temp);break;

case 5:temp=d.delete1(temp);d.display(temp);break;

case 6:exit(0);

}}return 0;

}

Page 50: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

OUTPUT :-

WELCOME TO DCLL MENU

1. FOR CREATE NEW NODE

2. FOR DISPLAY CONTENT OF DCLL

3. FOR COUNT NO. OF NODES

4. FOR INSERT NEW NODE

5. FOR DELETE NODE

6. FOR EXITENTER CHOICE U WANT

1

Enter no. of nodes : 5

Enter data : 11

Enter data : 22

Enter data : 33

Enter data : 44

Enter data : 55

WELCOME TO DCLL MENU

1. FOR CREATE NEW NODE

2. FOR DISPLAY CONTENT OF DCLL

3. FOR COUNT NO. OF NODES

4. FOR INSERT NEW NODE

5. FOR DELETE NODE

6. FOR EXITENTER CHOICE U WANT

211 22 33 44 55

Page 51: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

WELCOME TO DCLL MENU

1. FOR CREATE NEW NODE

2. FOR DISPLAY CONTENT OF DCLL

3. FOR COUNT NO. OF NODES

4. FOR INSERT NEW NODE

5. FOR DELETE NODE

6. FOR EXITENTER CHOICE U WANT

3 NO.OF NODES IS :5

WELCOME TO DCLL MENU

1. FOR CREATE NEW NODE

2. FOR DISPLAY CONTENT OF DCLL

3. FOR COUNT NO. OF NODES

4. FOR INSERT NEW NODE

5. FOR DELETE NODE

6. FOR EXITENTER CHOICE U WANT

4

Enter Data : 0

Enter position :10 11 22 33 44 55

Page 52: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

WELCOME TO DCLL MENU

1. FOR CREATE NEW NODE

2. FOR DISPLAY CONTENT OF DCLL

3. FOR COUNT NO. OF NODES

4. FOR INSERT NEW NODE

5. FOR DELETE NODE

6. FOR EXITENTER CHOICE U WANT

4

Enter Data : 66

Enter position :70 11 22 33 44 55 66

WELCOME TO DCLL MENU

1. FOR CREATE NEW NODE

2. FOR DISPLAY CONTENT OF DCLL

3. FOR COUNT NO. OF NODES

4. FOR INSERT NEW NODE

5. FOR DELETE NODE

6. FOR EXITENTER CHOICE U WANT

4

Enter Data : 45

Enter position :4

0 11 22 45 33 44 55 6

Page 53: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

WELCOME TO DCLL MENU

1. FOR CREATE NEW NODE

2. FOR DISPLAY CONTENT OF DCLL

3. FOR COUNT NO. OF NODES

4. FOR INSERT NEW NODE

5. FOR DELETE NODE

6. FOR EXITENTER CHOICE U WANT

5

Enter position 50 11 22 45 44 55 66

WELCOME TO DCLL MENU

1. FOR CREATE NEW NODE

2. FOR DISPLAY CONTENT OF DCLL

3. FOR COUNT NO. OF NODES

4. FOR INSERT NEW NODE

5. FOR DELETE NODE

6. FOR EXITENTER CHOICE U WANT

6

Page 54: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

ASSIGNMENT NO:6 (A) PROBLEM STATEMENT: Write a modular program using object oriented programming features to implement quicksort methods using Python.

AIM: To learn quick sort method and its implementation.

FACILITIES (TOOLS USED):Linux Operating System, Turbo C++, Eclipse Framework.

ALGORITHM: [I] Algorithm QuickSort(int a[], int p, int q, int n) Precondition : Accept the Array to be sorted Postcondition : Sorted array Return : Nil 1. int pass=0;

2. if(p<q)

3. j=partition(a,p,q);

4. pass++;

5. QuickSort(a,p,j-1,n);

6. QuickSort(a,j+1,q,n);

7. End if

[II] Algorithm Partition(int a[], int p, int q) v=a[p]; i=p; j=q+1; do

{ do {

i++; }while(a[i]<v && i<=q); do {

j--; }while(a[j]>v); if(i<j) {

temp=a[i]; a[i]=a[j]; a[j]=temp;

} }while(i<j); a[p]=a[j]; a[j]=v; return(j);

Page 55: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

THEORY: 1. To sort the subarray A[p . . r]:Divide: Partition A[p . . r], into two subarrays A[p . . q − 1] and A[q + 1 . . r], such that each element in the first subarray A[p . . q − 1] is A[q] and A[q] is each element in the second subarray A[q + 1 . . r].Conquer: Sort the two subarrays by recursive calls to Quicksort.

2. Combine: No work is needed to combine the subarrays, because they are sorted in place.

3. Perform the divide step by a procedure partition, which returns the index j that marks the position separating the subarrays.

INPUT: 1.Array of integer numbers. OUTPUT: 1. Sorted array of numbers FAQ: 1. What is sorting?

2. What are algorithmic steps for quick sort?

3. What is time and space complexity for quick sort?

CONCLUSION: Hence, we have studied quick sort implementation.

NAME OF FACULTY:

SIGNATURE:

DATE:

Page 56: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

PROGRAM CODE Title:Write a modular program using object oriented programming features to implement quick sort method using Python.

Name: Class: SEDiv: ARoll No: Batch:

num_array = list() num = raw_input("Enter how many elements you want:") print 'Enter numbers in array: ' for i in range(int(num)):

n = raw_input("num :") num_array.append(int(n))

print 'ARRAY: ',num_array

def merge(left, right): result = [] i, j = 0, 0 while i < len(left) and j < len(right):

if left[i] <= right[j]: result.append(left[i])

i += 1 else:

result.append(right[j]) j += 1result += left[i:] result += right[j:] return result

def mergesort(lst): if len(lst) <= 1:

return lst middle = int(len(lst) / 2) left = mergesort(lst[:middle]) right = mergesort(lst[middle:]) return merge(left, right)

def partition(list, start, end): pivot = list[end] bottom = start-1 top = end done = 0 while not done:

while not done: bottom = bottom+1 if bottom == top:

done = 1 break

Page 57: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

if list[bottom] > pivot: list[top] = list[bottom] break

while not done: top = top-1.

if top == bottom: done = 1 break

if list[top] < pivot: list[bottom] = list[top] break

list[top] = pivot # Put the pivot in its place. return top # Return the split point

def quicksort(list, start, end): if start < end:

split = partition(list, start, end) quicksort(list, start, split-1). quicksort(list, split+1, end)

else: return

print "Merge sort output is" print mergesort(num_array) print "Quick sort output is" end = len(num_array)-1 quicksort(num_array,1,end) print 'ARRAY: ',num_array

Page 58: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

OUTPUT:-[root@Rajesh-CentOS ~]# python quick.py Enter how many elements you want:4 Enter numbers in array: num :11 num :2 2num :33num :44ARRAY: [11, 22, 33, 44] Merge sort output is [11, 22, 33,4 4] Quick sort output is ARRAY: [11, 22, 33,4 4] [root@Rajesh-CentOS ~]# python quick.py Enter how many elements you want:5 Enter numbers in array: num :12 num :6 num :30 num :20 num :24 ARRAY: [11, 6, 30, 20, 24] Merge sort output is [6, 12, 20, 24, 30] Quick sort output is ARRAY: [12, 6, 20, 24, 30] [root@Rajesh-CentOS ~]#

Page 59: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

ASSIGNMENT NO:6 (B) PROBLEM STATEMENT: Write a modular program using object oriented programming features to implement mergesort methods using Python. AIM: To learn mergesort method and its implementation. FACILITIES (TOOLS USED):Linux Operating System, Turbo C++, Eclipse Framework. ALGORITHM: MergeSort (A, low, high) if low <high // at least two elements mid ← (low + high) / 2 // divide the list into two halves MergeSort(A, low, mid) MergeSort(A, mid + 1, high) Merge(low, mid, high) end MergeSort. Merge(A[0..n – 1], low, mid, high) Input: Semi sorted Array A Output: Merged sorted array A from low to high i ← h← low // i is for the first sublist j ← mid + 1 // j is for the second sublist while h <mid and j<high do // sublists not exhausted yet if A[h] <A[j] B[i]← A[h]h ← h + 1 else B[i]← A[j] j ←j + 1 i ←i + 1 if h >mid // first sublist exhausted – copy remaining elements. for k← j to high do B[i]← A[k] i ←i + 1 k ← k + 1 else // second sublist exhausted - copy remaining elements. for k← h to mid do B[i]← A[k] i ←i + 1 k ← k + 1 // Copy B to A for k← low to high do A[k]← B[k] k ← k + 1 end Merge. THEORY: To sort A[p .. r]:

1. Divide StepIf a given array A has zero or one element, simply return; it is already sorted. Otherwise, splitA[p .. r] into two subarrays A[p .. q] and A[q + 1 .. r], each containing about half of the elements of A[p .. r]. That is, q is the halfway point of A[p .. r].

2. Conquer Step Conquer by recursively sorting the two subarrays A[p .. q] and A[q + 1 .. r].

3. Combine Step

Page 60: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

Combine the elements back in A[p .. r] by merging the two sorted subarrays A[p .. q] and A[q + 1 .. r] into a sorted sequence. To accomplish this step, we will define a procedure MERGE (A, p, q, r). INPUT: 1. Array of integer numbers.

OUTPUT: 2. Sorted array of numbers

FAQ 1. What is sorting?

2. How to sort the element using Merge Sort?

3. What is searching?

4. Different types of searching methods.

5. Time complexities of sorting and searching methods.

6. How to calculate time complexity?

7. What are space complexity of all sorting and searching methods?

8. Explain what is best, worst and average case for each method of searching and sorting.

LGORITHM ANALYSIS 1. Time Complexity Of Merge Sort in best case is( when all data is already in sorted form):O(n)

2. Time Complexity Of Merge Sort in worst case is: O(n logn)

3. Time Complexity Of Merge Sort in average case is: O(n logn)

APPLICATIONS 1. Representing Linear data structure & Sequential data organization : structure & files

2. For Sorting sequential data structure

CONCLUSION Thus, we have studiedmerge sort implementation.

NAME OF FACULTY:

SIGNATURE: DATE:

Page 61: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

PROGRAM CODE Title:Write a modular program using object oriented programming features to implement merge sort using Python. Name: Class: SEDiv: ARoll No: Batch:

num_array = list() num = raw_input("Enter how many elements you want:") print 'Enter numbers in array: ' for i in range(int(num)): n = raw_input("num :") num_array.append(int(n)) print 'ARRAY: ',num_array def merge(left, right): result = [] i, j = 0, 0 while i < len(left) and j < len(right): if left[i] <= right[j]: result.append(left[i]) i += 1 else: result.append(right[j]) j += 1result += left[i:] result += right[j:] return result def mergesort(lst): if len(lst) <= 1: return lst middle = int(len(lst) / 2) left = mergesort(lst[:middle]) right = mergesort(lst[middle:]) return merge(left, right) def partition(list, start, end): pivot = list[end] # Partition around the last value bottom = start-1 # Start outside the area to be partitioned top = end done = 0 while not done: # Until all elements are partitioned... while not done: # Until we find an out of place element... bottom = bottom+1 # ... move the bottom up. if bottom == top: # If we hit the top... done = 1 # ... we are done. Breakif list[bottom] > pivot: # Is the bottom out of place? list[top] = list[bottom] # Then put it at the top... break # ... and start searching from the top. while not done: # Until we find an out of place element...

Page 62: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

top = top-1 # ... move the top down. if top == bottom: # If we hit the bottom... done = 1 # ... we are done. break if list[top] < pivot: # Is the top out of place? list[bottom] = list[top] # Then put it the bottom... break # ...and start searching from the bottom. list[top] = pivot # Put the pivot in its place. return top # Return the split point print "Merge sort output is" print mergesort(num_array)

Output: [root@Rajesh-CentOS ~]# python merg.py Enter how many elements you want:5 Enter numbers in array: num :6 num :20 num :5num :24 num :32 ARRAY: [6, 20, 5, 24, 32] Merge sort output is [5, 6, 20, 24, 32] [root@Rajesh-CentOS ~]#

Page 63: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

ASSIGNMENT NO:7

PROBLEM STATEMENT: Write a modular program using object oriented programming features to implement primitive operations on Queue using Java Frame/Applet. AIM: 1. To understand concepts of object oriented programming features.

2. To learn primitive operations on Queue.

FACILITIES (TOOLS USED):Linux Operating System, Eclipse Framework ALGORITHM: 1. Start

2. Read Number to insert in queue

3. Perform primitive operation on queue(I.e. insert, delete, display)

4. Stop

THEORY: Queue:It is also referred to the linear data structure as the object or item can be added in one terminal and the item can be retrieved from the other end. Item, which is added to one end, is called as REAR and the item that is retrieved from the other end is called as FRONT Example: Print jobs. Consider the systems are connected in the network with the common print using the print share methodology. Queue operation: - This operation is used to add an item to the queue at the rear end. So, the head of the queue will be now occupied with an item currently added in the queue. Head count will be incremented by one after addition of each item until the queue reaches the tail point. This operation will be performed at the rear end of the queue.- This operation is used to remove an item from the queue at the front end. Now the tail count will be decremented by one each time when an item is removed from the queue until the queue reaches the head point. This operation will be performed at the front end of the queue. – Checks whether the queue is empty. (If Is empty is true, then the addition of an item is possible. If this is false, then acknowledge with the message "Queue is empty") – Checks whether the queue is full. (If Is full is true, then the removal of an item is possible. If this is false, then acknowledge with the message "Queue is full") Mathematical Model of Queue Abstract data type(ADT) of data structure is considered as mathematical model. ADT for queue is: Data objects: A finite set of elements of same type Operations: Enqueue(Queue,Item): Inserts item on queue Dequeue(Queue,Item): Delete item from queue IS_FULL:checks if queue is full IS_EMPTY:checks if queue is empty. INPUT: 1. Number to insert in a queue. OUTPUT: 1. Queue of given numbers FAQ:

Page 64: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

1. What is Java Applet? 2. What is Life cycle of Applet? 3. What are primitive operations of queue? 4. What are applications of queue? 5. What is JFrame?

CONCLUSION: Thus we have implemented primitive operations on Queue using Java Frame/Applet.

NAME OF FACULTY:

SIGNATURE: DATE:

Page 65: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

PROGRAM CODE Title:- Write a modular program using object oriented programming features to implement primitive operations on Queue using Java Frame/Applet.

Name: Class: SEDiv: ARoll No: Batch: import java.applet.Applet;

import java.awt.*;

import java.awt.event.*;

import java.util.ArrayList;

public class queue extends Applet implements ActionListener{

Label label,l1;

TextField t1;

Button b1,b2,b3;

java.util.List<Integer>queue;

public void init()

{

queue=new ArrayList<Integer>(10);

label=new Label("Enter the no. to insert into queue: ");

l1=new Label(" ");

t1=new TextField(15);

b1=new Button("Enque the no.");

b2=new Button("Dequue the no.");

b3=new Button("Display the queue.");

add(label);

add(t1);

add(b1);

add(b2);

Page 66: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

add(b3);

add(l1);

b1.addActionListener(this);

b2.addActionListener(this);

b3.addActionListener(this);

}

public void actionPerformed(ActionEvent event){

Object cause=event.getSource();

String msg="";

if(cause==b1)

{int x=Integer.parseInt(t1.getText());

queue.add(x);

msg="number"+x+"added to queue";

l1.setText(msg);

}

else if(cause==b2)

{

if(queue.size()>0)

{

int num=queue.get(0);

queue.remove(0);

msg="Number"+num+"********Deleted from Queue**********";

l1.setText(msg);

}

else

{

msg="Queue is empty";

l1.setText(msg);

Page 67: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

}

}

else if(cause==b3)

{

if(queue.size()>0)

{

msg="Queue elements";

l1.setText(msg);

for(int i=0;i<queue.size();i++)

{

msg +=queue.get(i);

l1.setText(msg);

if(i!=(queue.size()-1))

{

msg +=" , ";

l1.setText(msg);

}

}

}

else

{

msg="queue is empty";

l1.setText(msg);

}

}

}

}

Page 68: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

OUTPUT:-

Page 69: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings
Page 70: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings
Page 71: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

ASSIGNMENT NO:8 PROBLEM STATEMENT: Write a program using object oriented programming using C++ to create a binary tree if inorder & preorder any two traversals are given.

AIM: 1. To understand the concept of binary tree.

2. To learn binary tree traversal method i. e. inorder, preorder & post-order.

FACILITIES (TOOLS USED):Linux Operating Systems, Turbo C++. ALGORITHM: 1. Start 2. Read the input sequence of nodes 3. Traverse the tree Pre-order: - Visit the root.

- Traverse the left subtree.

- Traverse the right subtree.

In-order: - Traverse the left subtree.

- Visit the root

- Traverse the right subtree.

Post-order: - Traverse the left subtree.

- Traverse the right subtree.

- Visit the root.

4. Display the sequence 6. Stop

ASSUMPTION: The given graph with set of vertices and edges. THEORY: A binary tree is a tree in which no node can have more than two children. Because there are only two children, named them as left and right. A binary tree is balancedif for every node in the tree the height of the left and right subtrees is within one as shown below.

A

B C

D E F G

Page 72: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

Fig. 1: Binary tree

A node with one child could have either a left or right child. Binary trees have many important uses. One use of the binary tree is in the expression tree, which is a central data structure in compiler design. The leaves of an expression tree are operands, such as constants or variable names; the other nodes contain operators. This particular tree is binary because all the operations are binary. The values obtained by recursively evaluating the left and right subtrees. Doing so yields the expression (a+ ((b-c) *d)).

Fig. 2: Huffman coding tree

A second use of the binary tree is the Huffman coding tree, which is used to implement a simple but relatively effective data compression algorithm. Each symbol in the alphabet is stored at a leaf. A left link corresponds to a 0 and a right link to a 1. Other uses of the binary tree are in binary search trees, which allow logarithmic time insertions and accessing of items, and priority queues, which support the access and deletion of the minimum in a collection of items. There are a number of algorithms for traversing a binary tree given a pointer to the root of the tree. The most common strategies are preorder, inorder, and postorder.

Preorder traversal: To traverse a binary tree in preorder, following operations are carried-out (i) Visit the root, (ii) Traverse the left subtree, and (iii) Traverse the right subtree. Therefore, the preorder traversal of binary tree shown in the fig. 1 will output:

A B E F D H I

Inorder traversal: To traverse a binary tree in inorder, following operations are carried-out (i) Traverse the left most subtree starting at the left external node, (ii) Visit the root, and (iii) Traverse the right subtree starting at the left external node. Therefore, the inorder traversal of binary tree shown in the fig. 1 will output:

E B F A H D I

Postorder traversal: To traverse a binary tree in postorder, following operations are carried-out (i) Traverse all the left external nodes starting with the left most subtree which is then followed by bubble-up all the internal nodes, (ii) Traverse the right subtree starting at the left external node which is then followed by bubble-up all the internal nodes, and (iii) Visit the root. Therefore, the postorder traversal of binary tree shown in the fig. 1 will output:

E F B H I D A

Page 73: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

INPUT: 1. Number of vertices

2. Number of edges

3. Each edge with first vertex of edge and second vertex of edge

OUTPUT: 1. Graph representation using adjacency matrix

2. Result after binary tree traversal

CONCLUSION: We have learned to create binary tree if preorder and postorder or inorder and postorder are given.

FAQ: 1) What is Tree?

2) What is Binary tree traversal?

3) What is the maximum number of nodes at level k in a binary tree?

4) What is the maximum number of nodes in a binary tree containing k levels? Here is an alternate form of the same question: How many nodes are in a full binary tree with k levels?

5) How many nodes are in a full binary tree having k levels?

NAME OF FACULTY: SIGNATURE: DATE:

Page 74: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

PROGRAM CODE Title:-Write a program using object oriented programming using C++ to create a binary tree if inorder & preorder any two traversals are given.

Name: Class: SEDiv: ARoll No: Batch:

#include<iostream>

#include<stdlib.h>

#include<string.h>

using namespace std;

class node{public:

char data;node *left,*right;node(){

left=right=NULL;

}node(int x){

data=x;left=right=NULL;

}};

class tree{

node *root;public:

tree(){

root=NULL;

}

node *create1(char *in,char *pre);void create(char *in,char *pre){

root=create1(in,pre);}

void preorder1(node *t);void preorder(){

preorder1(root);

Page 75: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

}

void partition(char *in,char *in1,char *in2,char *pre,char *pre1,char *pre2);int find(char,char *);

};

void tree::preorder1(node *t){

if(t){

preorder1(t->left);preorder1(t->right);cout<<"\n "<<t->data;

}}

node *tree::create1(char *in,char *pre){

node *p;p=NULL;char in1[10],in2[10],pre1[10],pre2[10];

if(strlen(pre)==0){return NULL;}p= new node(pre[0]);partition(in,in1,in2,pre,pre1,pre2);p->left=create1(in1,pre1);p->right=create1(in2,pre2);return p;

}

int tree::find(char c,char *in){

for(int i=0;in[i]!='\0';i++){

if(c==in[i])return (1);

}return 0;

}

void tree::partition(char *in,char *in1,char *in2,char *pre,char *pre1,char *pre2){

int i,j,k;for(i=0;in[i]!=pre[0];i++){

in1[i]=in[i];}

Page 76: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

in1[i]='\0';i++;for(j=0;in[i]!='\0';i++,j++){

in2[j]=in[i];}in2[j]='\0';j=0;k=0;

for(i=1;pre[i]!='\0';i++){

if(find(pre[i],in1)){

pre1[j++]=pre[i];

}else{

pre2[k++]=pre[i];}

}pre1[j]='\0';pre2[k]='\0';

}

int main(){

tree t;

char inorder[20],preorder[20];cout<<"\n enter inorder traversal :";cin>>inorder;cout<<"\n enter preorder traversal :";cin>>preorder;

t.create(inorder,preorder);cout<<"\n the tree after creation is and its postorder traversal is:";t.preorder();return 1;

}

Page 77: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

OUTPUT:-

enter inorder traversal :GDBEACHIF

enter preorder traversal :ABDGECFHI

the tree after creation is and its postorder traversal is: G D E B I H F C A

Page 78: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

ASSIGNMENT NO:9

PROBLEM STATEMENT: Write a C++ program to implement traversals on Threaded Binary Tree using object oriented programming features. Design necessary class. AIM: 1. To learn the Threaded binary tree Concept and its different operations

2. To introduce inorder-threading of binary trees, and to show how inthreaded trees can be traversed easily

FACILITIES (TOOLS USED): Linux Operating Systems, Eclipse framework ALGORITHM: 1. Algorithm node * Create(tbtnode *parent, int leftorright) //leftorright=0 for left child 1. Accept Data x (-1 for no data or NULL child ) 2. if(x==-1) 1. return 3. end if 4. p=new tbtnode() 5. p->data=x; 6. if(leftorright==0) //if it is left child 1. p->flag=0; 2. p->lbit=parent->lbit; 3. p->left=parent->left; 4. parent->left=p; 5. parent->lbit=1; 6. p->rbit=0; 7. p->right=parent; 7. else //if it is right child 1. p->flag=1; 2. p->rbit=parent->rbit; 3. p->right=parent->right; 4. parent->right=p; 5. parent->rbit=1; 6. p->lbit=0; 7. p->left=parent; 8. end if 9. create(p,0); 10. create1(p,1); 2. end Create()

2. Algorithm inOrder() 1. T=root->left; 2. Repeat while(T->lbit==1) 1. T=T->left

Page 79: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

3. end while 4. Repeat while T is not equal to root 1. Print T->data 2. if(T->rbit==1) 1. T=T->right; 2. Repeat while(T->lbit==1) 1. T=T->left; 3. end while 3. else 1. T=T->right 4. end if 5. end while end displayBFT

THEORY: A Threaded Binary Tree is a binary tree in which every node that does not have a right child has a THREAD (in actual sense, a link) to its INORDER successor. By doing this threading we avoid the recursive method of traversing a Tree, which makes use of stacks and consumes a lot of memory and time.

The node structure for a threaded binary tree varies a bit and its like this – struct NODE { struct NODE *leftchild; int node_value; struct NODE *rightchild; struct NODE *thread; } Let's make the Threaded Binary tree out of a normal binary tree...

The INORDER traversal for the above tree is -- D B A E C. So, the respective Threaded Binary tree will be –

B has no right child and its inorder successor is A and so a thread has been made in between them. Similarly, for D and E. C has no right child but it has no inorder successor even, so it has a hanging thread. Non recursive Inorder traversal for a Threaded Binary Tree As this is a non-recursive method for traversal, it has to be an iterative procedure; meaning, all the steps for the traversal of a node have to be under a loop so that the same can be applied to all the nodes in the tree.

Page 80: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

Consider the INORDER traversal again. Here, for every node, we'll visit the left sub-tree (if it exists) first (if and only if we haven't visited it earlier); then we visit (i.e print its value, in our case) the node itself and then the right sub-tree (if it exists). If the right sub-tree is not there, we check for the threaded link and make the threaded node the current node in consideration. Please, follow the example given below.

List of visited nodes:

INORDER:

step-1: 'A' has a left child i.e B, which has not been visited. So, we put B in our "list of visited nodes" and B becomes our current node in consideration.

B

step-2: 'B' also has a left child, 'D', which is not there in our list of visited nodes. So, we put 'D' in that list and make it our current node in consideration.

B D

step-3: 'D' has no left child, so we print 'D'. Then we check for its right child. 'D' has no right child and thus we check for its thread-link. It has a thread going till node 'B'. So, we make 'B' as our current node in consideration.

B D D

step-4: 'B' certainly has a left child but its already in our list of visited nodes. So, we print 'B'. Then we check for its right child but it doesn't exist. So, we make its threaded node (i.e 'A') as our current node in consideration.

B D D B

Page 81: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

step-5: 'A' has a left child, 'B', but its already there in the list of visited nodes. So, we print 'A'. Then we check for its right child. 'A' has a right child, 'C' and its not there in our list of visited nodes. So, we add it to that list and we make it our current node in consideration.

B D C D B A

step-6: 'C' has 'E' as the left child and its not there in our list of visited nodes even. So, we add it to that list and make it our current node in consideration.

B D C E D B A

and finally..... D B E A C

OUTPUT: In Order: 8 12 14 55 44 52

FAQ: 1. What is Threaded Binary tree?

2. What are TBT traversals? Why it requires?

3. What is Thread? Advantages of TBT.

Page 82: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

4. Real time Applications of TBT

ANALYSIS: Time Complexity : O(Nlog N)

APPLICATIONS: Where fast Traversal is required at that applications TBT is used

CONCLUSION:

1. A NULL pointer is, in a sense, "wasted space". In trying to optimize storage, can utilize the space occupied by NULL pointers to provide us with threads A thread is also a pointer, but is distinct from the pointers that form the connections in the tree

2. Use the special pointers to make traversals faster

3. Eliminates the need for the stack / queue to track the return path

4. Can use the right NULL pointer to point to the inorder successor

5. Can use the right NULL pointer to point to the inorder predecessor

NAME OF FACULTY:

SIGNATURE: DATE:

Page 83: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

PROGRAM CODE

Title:Write a C++ program to implement traversals on Threaded Binary Tree using object oriented programming features. Design necessary class.

Name: Class: SEDiv: ARoll No: Batch

#include<iostream.h>

class TBT{

public:char data;TBT *left,*right;int lbit,rbit;void create(TBT *head);void inorder(TBT *head);void preorder(TBT *head);void postorder(TBT *head);

};

void TBT::create(TBT *head){

char ch,ch1;TBT *root,*nw,*temp;root=new TBT;cout<<"\nEnter data for new root node\n";cin>>root->data;root->left=head;root->right=head;root->lbit=1;root->rbit=1;head->left=root;head->lbit=0;

do{

nw= new TBT;cout<<"Enter data for new node\n";cin>>nw->data;nw->left=nw->right=NULL;nw->lbit=nw->rbit=1;temp=root;while(1){

cout<<"\nPress L or R to insert new data "<<nw->data<<" in left or right of root "<<temp->data<<"\n";

cin>>ch;if(ch=='L'||ch=='l'){

Page 84: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

if(temp->lbit==1){

nw->left=temp->left;nw->right=temp;temp->left=nw;temp->lbit=0;cout<<"\nThe new node "<<nw->data<<" has been inserted in left

of "<<temp->data<<"\n";break;

}else

temp=temp->left;}if(ch=='R'||ch=='r'){

if(temp->rbit==1){

nw->right=temp->right;nw->left=temp;temp->right=nw;temp->rbit=0;cout<<"\nThe new node "<<nw->data<<" has been inserted in

right of "<<temp->data<<"\n";break;

}else

temp=temp->right;}

}cout<<"\nDo you want to insert new node(Y/N)\n";cin>>ch1;

}while(ch1=='Y'||ch=='y');

}

void TBT::inorder(TBT *head){

TBT *temp;temp=head->left;while(temp!=head){

while(temp->lbit==0){

temp=temp->left;}cout<<"\t"<<temp->data<<"\n";while(temp->rbit==1){

temp=temp->right;if(temp==head){

break;}cout<<"\t"<<temp->data<<"\n";

}temp=temp->right;

}

Page 85: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

}

void TBT :: preorder(TBT *head){

TBT *temp;temp=head->left;while(temp!=head){

while(temp!=head){

cout<<"\t"<<temp->data<<"\n";if(temp->lbit==0){

temp=temp->left;}else if(temp->rbit==0){temp=temp->right;}else{

while(temp->rbit==1){

temp=temp->right;}if(temp==head)

break;else

temp=temp->right;}

}}

}

void TBT :: postorder(TBT *head){

TBT *temp;temp=head->left;char post[40];int i=0,j;while(1){

while(1){

post[i]=temp->data;i=i+1;if(temp->rbit==1)

break;temp=temp->right;

}while(temp->rbit==1){

temp=temp->left;}if(temp==head)

break;

Page 86: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

temp=temp->left;}for(j=i-1;j>=0;j--)

cout<<post[j]<<"\n";}

int main(){

TBT *head,obj1;int ch;while(1){

cout<<"\n\t1. Create TBT\n";cout<<"\t2. Inorder TBT\n";cout<<"\t3. Postorder TBT\n";cout<<"\t4. Preorder TBT\n";cout<<"\t5. Exit\n";cout<<"\tEnter your choice\n";cin>>ch;switch(ch){case 1:

head=new TBT;head->left=NULL;head->right=head;head->lbit=head->rbit=0;obj1.create(head);break;

case 2:obj1.inorder(head);break;

case 3:obj1.postorder(head);break;

case 4:obj1.preorder(head);break;

case 5:exit(0);

}

}

}

Page 87: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

OUTPUT:-

1. Create TBT2. Inorder TBT3. Postorder TBT4. Preorder TBT5. ExitEnter your choice1Enter data for new root nodeaEnter data for new nodebPress L or R to insert new data b in left or right of root alThe new node b has been inserted in left of aDo you want to insert new node(Y/N)yEnter data for new nodecPress L or R to insert new data c in left or right of root arThe new node c has been inserted in right of aDo you want to insert new node(Y/N)yEnter data for new nodedPress L or R to insert new data d in left or right of root alPress L or R to insert new data d in left or right of root blThe new node d has been inserted in left of bDo you want to insert new node(Y/N)yEnter data for new nodeePress L or R to insert new data e in left or right of root alPress L or R to insert new data e in left or right of root brThe new node e has been inserted in right of bDo you want to insert new node(Y/N)yEnter data for new nodefPress L or R to insert new data f in left or right of root arPress L or R to insert new data f in left or right of root clThe new node f has been inserted in left of cDo you want to insert new node(Y/N)yEnter data for new nodegPress L or R to insert new data g in left or right of root arPress L or R to insert new data g in left or right of root c

Page 88: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

rThe new node g has been inserted in right of cDo you want to insert new node(Y/N)N1. Create TBT2. Inorder TBT3. Postorder TBT4. Preorder TBT5. ExitEnter your choice2

dbeafcg

1. Create TBT2. Inorder TBT3. Postorder TBT4. Preorder TBT5. ExitEnter your choice3

debfgca

1. Create TBT2. Inorder TBT3. Postorder TBT4. Preorder TBT5. ExitEnter your choice4

abdecfg

1. Create TBT2. Inorder TBT3. Postorder TBT4. Preorder TBT5. ExitEnter your choice5

Page 89: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

ASSIGNMENT NO:10 PROBLEM STATEMENT: Write a Java program to implement topological sorting on graph using object oriented programming features Design necessary class.

AIM: 1. To understand topological sorting on graph.

2. To learn object oriented programming features.

FACILITIES (TOOLS USED): Linux Operating Systems, Eclipse framework.

ALGORITHM: 1. Start 2. Read the input 3. Compute the indegree of graph 4. Compute the result after topological sorting 4. Display the sequence 6. Stop

ASSUMPTION: The given graph is directed acyclic graph (DAG).

THEORY:

Topological ordering of a directed acyclic graph (DAG) is a linear ordering of its vertices such that for every directed edge uv from vertex u to vertex v, u comes before v in the ordering. For instance, the vertices of the graph may represent tasks to be performed, and the edges may represent constraints that one task must be performed before another; in this application, a topological ordering is just a valid sequence for the tasks. A topological ordering is possible if and only if the graph has no directed cycles, that is, if it is a directed acyclic graph (DAG). Any DAG has at least one topological ordering, and algorithms are known for constructing a topological ordering of any DAG in linear time.Topological sort is a process of assigning a linear ordering to the vertices of a DAG so that if there is an arc from vertex ito vertexj, theniappears beforejin the linear ordering Useful in scheduling applications

Example: Consider the DAG in Figure below

Page 90: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

A topological sort is given by: B, A, D, C, E. There could be several topological sorts for a given DAG Topological sort can be easily accomplished by simply including an additional statement in the depth first search procedure of the given graph.

Let number [vertex] be the number that we assign in topological sort. We use a global integer variable n, whose initial value is zero.

int n = 0; void topsort (vertex v); /* assigns numbers to vertices accessible from v in reverse topological order */ vertex w; { mark[v] = visited; for (w L[v]) if (mark[w] == unvisited) topsort (w);number[v] = n+1 } This technique works because a DAG has no back arcs.

Consider what happens when the DFS leaves a vertex x for the last time. The only arcs emanating from v are tree, forward, and cross arcs. But all these arcs are directed towards vertices that have been completely visited by the search and therefore proceed x in the order being constructed.

COMPLEXITY

The number of operations is O(|E| + |V|), where |V| - number of vertices, |E| - number of edges. How many operations are needed to compute the indegrees? Depends on the representation: Adjacency lists: O(|E|) Matrix: O(|V|2) Note that if the graph is complete |E| = O(|V|2)

INPUT: 1. Number of vertices

2. Number of edges

3. Each edge with first vertex of edge and second vertex of edge

OUTPUT:

1. Graph representation using adjacency matrix

2. Result after topological sorting

APPLICATIONS Topological Sorting is mainly used for scheduling jobs from the given dependencies among jobs.

In computer science, applications of this type arise in instruction scheduling, ordering of formula cell evaluation when recomputing formula values in spreadsheets, logic synthesis.

FAQ: 1) What is Topological sorting?

Page 91: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

2) Why do we perform topological sorts only on DAGs?

3) Is there always a unique answer? 4) What is DAGs?

CONCLUSION: Thus, we have designed topological sorting algorithm.

NAME OF FACULTY:

SIGNATURE:

DATE:

Page 92: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

PROGRAM CODE

Title:- Write a Java program to implement topological sorting on graph using object oriented programming features. Design necessary class.

Name: Class: SEDiv: ARoll No: Batch:

package topo;

import java.util.Scanner;//import java.util.*;import java.util.ArrayList;

class graph{

int v;int e;int [][]adj=new int [50][50];

public graph() {

v=0; e=0;

}

public void create() {

Scanner ir=new Scanner(System.in); System.out.println("\n enter no. of vertex : "); v=ir.nextInt(); int i,j; for(i=0;i<v;i++) {

for(j=0;j<v;j++) {

adj[i][j]=0; }

}

System.out.println("\n enter no. of edges : "); e=ir.nextInt(); int v1,v2; for(i=0;i<e;i++) {

System.out.println("\n enter edges in (u,v) form: "); v1=ir.nextInt(); v2=ir.nextInt(); adj[v1][v2]=1;

} }

Page 93: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

public int find_indegree(int m){ int in_degree=0,i; for(i=0;i<v;i++) {

if(adj[i][m]==1) {in_degree++; }

} return in_degree; }

public void topological_sort(){

java.util.ArrayList<Integer>Q;Q=new ArrayList<Integer>(50);int []indegree=new int[50];int []topsort=new int[50];int i,j;for(i=0;i<v;i++){

indegree[i]=find_indegree(i);if(indegree[i]==0){

Q.add(i);}

}

int m=0;while(Q.size()>0){

int k=Q.get(0);

topsort[m++]=k;

Q.remove(0);for(j=0;j<v;j++){

if(adj[k][j]==1){

adj[k][j]=0;indegree[j]=indegree[j]-1;if(indegree[j]==0){

Q.add(j);}

}}

}System.out.println("\n The Sorting Is : ");for(i=0;i<m;i++){

System.out.println(topsort[i]);

Page 94: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

}}public static void main(String args[]){

graph g =new graph();g.create();g.topological_sort();

}}

OUTPUT :-

enter no. of vertex : 5

enter no. of edges : 7

enter edges in (u,v) form: 0 2

enter edges in (u,v) form: 2 4

enter edges in (u,v) form: 3 4

enter edges in (u,v) form: 3 2

enter edges in (u,v) form: 0 3

enter edges in (u,v) form: 1 0

enter edges in (u,v) form: 1 3

The Sorting Is : 10324

Page 95: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

ASSIGNMENT NO:11 PROBLEM STATEMENT: Write a program to find shortest path for given source & destination of a given graph using C features.

AIM: To find the shortest path from source vertex to Destination Vertex using Dijkstra’s Shortest Path Algorithm

FACILITIES (TOOLS USED):Linux Operating System, Eclipse ALGORITHM: Let the node at which we are starting be called the initial node. Let the distance of node Y be the distance from the initial node to Y. Dijkstra's algorithm will assign some initial distance values and will try to improve them step by step. 1. Assign to every node a tentative distance value: set it to zero for our initial node and to infinity for all other nodes. 2. Mark all nodes unvisited. Set the initial node as current. Create a set of the unvisited nodes called the unvisited set consisting of all the nodes. 3. For the current node, consider all of its unvisited neighbors and calculate their tentative distances. For example, if the current node A is marked with a distance of 6, and the edge connecting it with a neighbor B has length 2, then the distance to B (through A) will be 6 + 2 = 8. If this distance is less than the previously recorded tentative distance of B, then overwrite that distance. Even though a neighbor has been examined, it is not marked as "visited" at this time, and it remains in the unvisited set. 4. When we are done considering all of the neighbors of the current node, mark the current node as visited and remove it from the unvisited set. A visited node will never be checked again. 5. If the destination node has been marked visited (when planning a route between two specific nodes) or if the smallest tentative distance among the nodes in the unvisited set is infinity (when planning a complete traversal; occurs when there is no connection between the initial node and remaining unvisited nodes), then stop. The algorithm has finished. 6. Select the unvisited node that is marked with the smallest tentative distance, and set it as the new "current node" then go back to step 3. THEORY: Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra in 1956 and published in 1959, is a graph search algorithm that solves the single-source shortest path problem for a graph with non-negative edge path costs, producing a shortest path tree. This algorithm is often used in routing and as a subroutine in other graph algorithms. For a given source vertex (node) in the graph, the algorithm finds the path with lowest cost (i.e. the shortest path) between that vertex and every other vertex. It can also be used for finding costs of shortest paths from a single vertex to a single destination vertex by stopping the algorithm once the shortest path to the destination vertex has been determined. For example, if the vertices of the graph represent cities and edge path costs represent driving distances between pairs of cities connected by a direct road, Dijkstra's algorithm can be used to find the shortest route between one city and all other cities. As a result, the shortest path first is widely used in network routing protocols, most notably IS-IS and OSPF (Open Shortest Path First). INPUT: 1. Any Weighted Graph

2. Source Vertex and Destination Vertex

Page 96: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

OUTPUT: Shortest Path from Source Vertex to Destination Vertex and the shortest distance

FAQ: 1. Explain the working of Dijkstra’s Algorithm. 2. What are the applications of Dijkstra’s Algorithm? 3. How the Shortest Path will be calculated for Weighted and Unweighted Graph?

CONCLUSION: Thus we have implemented Dijkstra’s Shortest Path Algorithm for Weighted Graph.

NAME OF FACULTY: SIGNATURE: DATE:

Page 97: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

PROGRAM CODE Title:Write a program to find shortest path for given source & destination of a given graph using C features. Name: Class: SEDiv: ARoll No: Batch:

#define MAX 40#define INFINITY 9999#include<stdio.h>struct Table{

int dist;int pred;int status;

};

struct edges{

int sr;int dt;int wt;

};int main(){

struct edges ed[MAX];struct Table Tab[MAX];int adj[MAX][MAX];int cnt=0;int v,e,i,j,v1,v2;int cost=0;int w,sv,dv;int mind=INFINITY,minv=-1;printf("\n Enter the no of vertices");scanf("%d",&v);for(i=0;i<v;i++){

for(j=0;j<v;j++){adj[i][j]=0;

}}printf("\n Enter no of edges");scanf("%d",&e);for(i=0;i<e;i++){

printf("\n Enter no of edges in(v1,v2) form");scanf("%d %d",&v1,&v2);printf("\n Enter weight of edges");scanf("%d",&w);adj[v1][v2]=w;

}for(i=0;i<v;i++){

Tab[i].dist=INFINITY;Tab[i].status=0;

Page 98: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

Tab[i].pred=0;}

printf("\n Enter source and destination vertices");scanf("%d %d",&sv,&dv);Tab[sv].dist=0;Tab[sv].status=1;while(sv!=dv){

for(i=0;i<v;i++){

if(adj[sv][i]!=0){

if(Tab[i].status==0){

if(Tab[i].dist>(Tab[sv].dist+adj[sv][i])){

Tab[i].dist=Tab[sv].dist+adj[sv][i];Tab[i].pred=sv;

}}

}}

mind=INFINITY,minv=-1;for(i=0;i<v;i++){

if(adj[sv][i]!=0){

if(Tab[i].status==0){

if(mind>=Tab[i].dist){

mind=(Tab[i].dist);minv=i;

}}

}}

if(minv!=-1){

ed[cnt].sr=Tab[minv].pred;ed[cnt].dt=minv;ed[cnt].wt=adj[Tab[minv].pred][minv];Tab[minv].status=1;cnt++;cost=cost+adj[Tab[minv].pred][minv];sv=minv;

}else{

break;}

}printf("\nThe shortest path is");for(i=0;i<cnt;i++){

printf("\n V%d->v%d",ed[i].sr,ed[i].dt);}

Page 99: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

printf("\n The cost of shortest path is %d",cost);}

OUTPUT :-

Enter the no of vertices5

Enter no of edges7

Enter no of edges in(v1,v2) form0 2

Enter weight of edges8

Enter no of edges in(v1,v2) form2 4

Enter weight of edges4

Enter no of edges in(v1,v2) form4 1

Enter weight of edges6

Enter no of edges in(v1,v2) form1 0

Enter weight of edges2

Enter no of edges in(v1,v2) form3 0

Enter weight of edges1

Enter no of edges in(v1,v2) form1 3

Enter weight of edges9

Enter no of edges in(v1,v2) form2 3

Enter weight of edges7

Enter source and destination vertices1 2

The shortest path is V1->v0 V0->v2 The cost of shortest path is 10

Page 100: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

ASSIGNMENT NO:12 PROBLEM STATEMENT: Write a C program to perform insert node, delete node and display operations on B tree.

AIM: To learn the BTree Concept and its different operations FACILITIES (TOOLS USED):Linux Operating System, Eclipse ALGORITHM:

Insertion

A B Tree insertion example with each iteration. The nodes of this B tree have at most 3 children (Knuth order 3).

All insertions start at a leaf node. To insert a new element, search the tree to find the leaf node where the new element should be added. Insert the new element into that node with the following steps: 1. If the node contains fewer than the maximum legal number of elements, then there is room for the new element. Insert the new element in the node, keeping the node's elements ordered. 2. Otherwise the node is full, evenly split it into two nodes so: 1. A single median is chosen from among the leaf's elements and the new element.

Page 101: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

2. Values less than the median are put in the new left node and values greater than the median are put in the new right node, with the median acting as a separation value.

3. The separation value is inserted in the node's parent, which may cause it to be split, and so on. If the node has no parent (i.e., the node was the root), create a new root above this node (increasing the height of the tree).

If the splitting goes all the way up to the root, it creates a new root with a single separator value and two children, which is why the lower bound on the size of internal nodes does not apply to the root. The maximum number of elements per node is U−1. When a node is split, one element moves to the parent, but one element is added. So, it must be possible to divide the maximum number U−1 of elements into two legal nodes. If this number is odd, then U=2L and one of the new nodes contains (U−2)/2 = L−1 elements, and hence is a legal node, and the other contains one more element, and hence it is legal too. If U−1 is even, then U=2L−1, so there are 2L−2 elements in the node. Half of this number is L−1, which is the minimum number of elements allowed per node. Deletion[ There are two popular strategies for deletion from a B-tree. 1. Locate and delete the item, then restructure the tree to regain its invariants, OR

2. Do a single pass down the tree, but before entering (visiting) a node, restructure the tree so that once the key to be deleted is encountered, it can be deleted without triggering the need for any further restructuring The algorithm below uses the former strategy. There are two special cases to consider when deleting an element: 1. The element in an internal node is a separator for its child nodes

2. Deleting an element may put its node under the minimum number of elements and children

The procedures for these cases are in order below. Deletion from a leaf node 1. Search for the value to delete.

2. If the value is in a leaf node, simply delete it from the node.

3. If underflow happens, rebalance the tree as described in section "Rebalancing after deletion" below.

Deletion from an internal node Each element in an internal node acts as a separation value for two subtrees, therefore we need to find a replacement for separation. Note that the largest element in the left subtree is still less than the separator. Likewise, the smallest element in the right subtree is still greater than the separator. Both of those elements are in leaf nodes, and either one can be the new separator for the two subtrees. Algorithmically described below: 1. Choose a new separator (either the largest element in the left subtree or the smallest element in the right subtree), remove it from the leaf node it is in, and replace the element to be deleted with the new separator. 2. The previous step deleted an element (the new separator) from a leaf node. If that leaf node is now deficient (has fewer than the required number of nodes), then rebalance the tree starting from the leaf node.

Page 102: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

Rebalancing after deletion Rebalancing starts from a leaf and proceeds toward the root until the tree is balanced. If deleting an element from a node has brought it under the minimum size, then some elements must be redistributed to bring all nodes up to the minimum. Usually, the redistribution involves movingan element from a sibling node that has more than the minimum number of nodes. That redistribution operation is called a rotation. If no sibling can spare a node, then the deficient node must be merged with a sibling. The merge causes the parent to lose a separator element, so the parent may become deficient and need rebalancing. The merging and rebalancing may continue all the way to the root. Since the minimum element count doesn't apply to the root, making the root be the only deficient node is not a problem. The algorithm to rebalance the tree is as follows If the deficient node's right sibling exists and has more than the minimum number of elements, then rotate left 1. Copy the separator from the parent to the end of the deficient node (the separator moves down; the deficient node now has the minimum number of elements) 2. Replace the separator in the parent with the first element of the right sibling (right sibling loses one node but still has at least the minimum number of elements) 3. The tree is now balanced Otherwise, if the deficient node's left sibling exists and has more than the minimum number of elements, then rotate right 1. Copy the separator from the parent to the start of the deficient node (the separator moves down; deficient node now has the minimum number of elements) 2. Replace the separator in the parent with the last element of the left sibling (left sibling loses one node but still has at least the minimum number of elements) 3. The tree is now balanced Otherwise, if both immediate siblings have only the minimum number of elements, then merge with a sibling sandwiching their separator taken off from their parent 1. Copy the separator to the end of the left node (the left node may be the deficient node or it may be the sibling with the minimum number of elements) 2. Move all elements from the right node to the left node (the left node now has the maximum number of elements, and the right node – empty) 3. Remove the separator from the parent along with its empty right child (the parent loses an element)

If the parent is the root and now has no elements, then free it and make the merged node the new root (tree becomes shallower) Otherwise, if the parent has fewer than the required number of elements, then rebalance the parent THEORY: B-Tree is a self-balancing search tree. In most of the other self-balancing search trees (like AVL and Red Black Trees), it is assumed that everything is in main memory. To understand use of B-Trees, we must think of huge amount of data that cannot fit in main memory. When the number of keys is high, the data is read from disk in the form of blocks. Disk access time is very high compared to main memory access time. The main idea of using B-Trees is to reduce the number of disk accesses. Most of the tree operations (search, insert, delete, max, min, ..etc ) require O(h) disk accesses where h is height of the tree. B-tree is a fat tree. Height of B-Trees is kept low by putting maximum possible keys in a B-Tree node. Generally, a B-Tree node size is kept equal to the disk block size. Since h is low for B-Tree, total disk accesses for most of the operations are reduced significantly compared to balanced Binary Search Trees like AVL Tree, Red Black Tree, ..etc.

Page 103: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

PROPERTIES OF B-TREE

1) All leaves are at same level.

2) A B-Tree is defined by the term minimum degree ‘t’. The value of t depends upon disk block size.

3) Every node except root must contain at least t-1 keys. Root may contain minimum 1 key.

4) All nodes (including root) may contain at most 2t – 1 keys.

5) Number of children of a node is equal to the number of keys in it plus 1.

6) All keys of a node are sorted in increasing order. The child between two keys k1 and k2 contains all keys in range from k1 and k2.

7) B-Tree grows and shrinks from root which is unlike Binary Search Tree. Binary Search Trees grow downward and also shrink from downward.

8) Like other balanced Binary Search Trees, time complexity to search, insert and delete is O(Logn)

Following is an example B-Tree of minimum degree 3. Note that in practical B-Trees, the value of minimum degree is much more than 3.

Search Search is similar to search in Binary Search Tree. Let the key to be searched be k. We start from root and recursively traverse down. For every visited non-leaf node, if the node has key, we simply return the node. Otherwise we recur down to the appropriate child (The child which is just before the first greater key) of the node. If we reach a leaf node and don’t find k in the leaf node, we return NULL. Traverse Traversal is also similar to Inorder traversal of Binary Tree. We start from the leftmost child, recursively print the leftmost child, then repeat the same process for remaining children and keys. In the end, recursively print the rightmost child. INPUT: 1. Integer values and order of B tree. E.g. 5 9 3 7 1 2 8 6 0 4 and order of B Tree is t=2. OUTPUT: B tree of given order 2 and with given data values.

Page 104: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

FAQ: 1. What is B Tree? 2. What are the Different operations that can be performed on B Tree? 3. What are the Applications of B Tree?

CONCLUSION: Thus we have implemented B Tree and performed Insert and Delete Operations on it.

NAME OF FACULTY: SIGNATURE:

DATE:

Page 105: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

PROGRAM CODE Title:- Write a C program to perform insert node, delete node and display operations on B tree. Name: Class: SEDiv: ARoll No: Batch:

Page 106: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

ASSIGNMENT NO:13 PROBLEM STATEMENT: Tic-Tac- Toe gaming application using C++ Programming.

AIM: To learn Tic-Tac-Toe algorithm.

FACILITIES (TOOLS USED):Linux Operating Systems, Turbo C++.

ALGORITHM: 1. Start 2. Decide who is first player or the second player. 3. Learn the specific moves associated with the board 4. Make a move that blocks opponent’s attempt to win i. e. Counter-Attack. 5. Check winner 6. Display winner player name 7. Stop

ASSUMPTION: The given board is of 3x3.

THEORY: Tic-tac-toe is a well know game. Basically there is a 3x3 board and two players: one is X and the other is O. Learn the definitions and specific moves associated with the following words: Counter-Attack: Making a move that blocks your opponent’s attempt to win. Center: The only square on a Tic Tac Toe board completely surrounded by other squares. Edge: A square bordering the center. Corner: A square bordered by 2 edge squares. Checkwin: Checks if either one of the players connected three blocks in row, column, or diagonal (8 possibilities).

As the following figure shows, there are eight probabilities for connecting three blocks with the same symbol.

First step: Fill the center block. By this way I forbid the opponent from four opportunities and he still has another 4 as the following figure shows.

Page 107: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

Second step: However the opponent plays, there is no danger till now and I have to decreased his number of opportunities. The best location for playing now is the corners as it decreases his opportunities by two in one turn.

Third step: Check the two lines (1 and 2) as the previous figure shows, and the one which contains two similar symbols; the computer should set the third with the other opposite symbol so I don’t let the opponent win as the following figure shows.

Fourth step: Check the last available line for the opponent to win and check if he has two blocks set with his symbol and then check the third.

MATHEMATICAL MODEL: S = Universalset = {PlayerIwins; PlayerIIwins; gamedraw} n(S) = 3 A =Set for Player I is the winner = {Player I wins} n(A) = 1 B =Set for Player II is the winner = {Player II wins} n(B) = 1 C =Set for Game has been Draw = {Game is draw} n(C) = 1

Page 108: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

P(A) = n(A)/n(S) = 1/3 P(B) = n(B)/n(S) = 1/3 P(C) = n(C)/n(S) = 1/3

INPUT: 1. A number represents a square of a 3x3 board.

OUTPUT: 1. Game result

FAQ: 1) What is Tic-Tac-Toe algorithm? 2) Explain probabilities to win game using tic tac toe algorithm

CONCLUSION: Thus, We have designed tic-tac-toe game algorithm.

NAME OF FACULTY:

SIGNATURE:

DATE:

Page 109: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

PROGRAM CODE

Title:-Tic-Tac- Toe gaming application using C++ Programming.

Name: Class: SEDiv: ARoll No: Batch:

#include <iostream.h>#include<stdlib.h>

using namespace std;

char square[10] = {'o','1','2','3','4','5','6','7','8','9'};

int checkwin();void board();

int main(){

int player = 1,i,choice;

char mark;do{

board();player=(player%2)?1:2;

cout << "Player " << player << ", enter a number: ";cin >> choice;

mark=(player == 1) ? 'X' : 'O';

if (choice == 1 && square[1] == '1')

square[1] = mark;else if (choice == 2 && square[2] == '2')

square[2] = mark;else if (choice == 3 && square[3] == '3')

square[3] = mark;else if (choice == 4 && square[4] == '4')

square[4] = mark;else if (choice == 5 && square[5] == '5')

square[5] = mark;else if (choice == 6 && square[6] == '6')

square[6] = mark;else if (choice == 7 && square[7] == '7')

Page 110: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

square[7] = mark;else if (choice == 8 && square[8] == '8')

square[8] = mark;else if (choice == 9 && square[9] == '9')

square[9] = mark;else{

cout<<"Invalid move ";

player--;cin.ignore();cin.get();

}i=checkwin();

player++;}while(i==-1);board();if(i==1)

cout<<"==>\aPlayer "<<--player<<" win ";else

cout<<"==>\aGame draw";

cin.ignore();cin.get();return 0;

}

/*********************************************FUNCTION TO RETURN GAME STATUS1 FOR GAME IS OVER WITH RESULT-1 FOR GAME IS IN PROGRESSO GAME IS OVER AND NO RESULT

**********************************************/

int checkwin(){

if (square[1] == square[2] && square[2] == square[3])

return 1;else if (square[4] == square[5] && square[5] == square[6])

return 1;else if (square[7] == square[8] && square[8] == square[9])

return 1;else if (square[1] == square[4] && square[4] == square[7])

return 1;else if (square[2] == square[5] && square[5] == square[8])

return 1;else if (square[3] == square[6] && square[6] == square[9])

Page 111: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

return 1;else if (square[1] == square[5] && square[5] == square[9])

return 1;else if (square[3] == square[5] && square[5] == square[7])

return 1;else if (square[1] != '1' && square[2] != '2' && square[3] != '3'

&& square[4] != '4' && square[5] != '5' && square[6] != '6'&& square[7] != '7' && square[8] != '8' && square[9] != '9')

return 0;else

return -1;}

void board(){

cout << "\n\n\tTic Tac Toe\n\n";

cout << "Player 1 (X) - Player 2 (O)" << endl << endl;cout << endl;

cout << " | | " << endl;cout << " " << square[1] << " | " << square[2] << " | " << square[3] << endl;

cout << "_____|_____|_____" << endl;cout << " | | " << endl;

cout << " " << square[4] << " | " << square[5] << " | " << square[6] << endl;

cout << "_____|_____|_____" << endl;cout << " | | " << endl;

cout << " " << square[7] << " | " << square[8] << " | " << square[9] << endl;

cout << " | | " << endl << endl;}

Page 112: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

OUTPUT:-

Tic Tac Toe

Player 1 (X) - Player 2 (O)

| | 1 | 2 | 3_____|_____|_____ | | 4 | 5 | 6_____|_____|_____ | | 7 | 8 | 9 | |

Player 1, enter a number: 1

Tic Tac Toe

Player 1 (X) - Player 2 (O)

| | X | 2 | 3_____|_____|_____ | | 4 | 5 | 6_____|_____|_____ | | 7 | 8 | 9 | |

Player 2, enter a number: 5

Tic Tac Toe

Player 1 (X) - Player 2 (O)

| | X | 2 | 3_____|_____|_____ | | 4 | O | 6_____|_____|_____ | | 7 | 8 | 9 | |

Player 1, enter a number: 3

Page 113: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

Tic Tac Toe

Player 1 (X) - Player 2 (O)

| | X | 2 | X_____|_____|_____ | | 4 | O | 6_____|_____|_____ | | 7 | 8 | 9 | |

Player 2, enter a number: 2

Tic Tac Toe

Player 1 (X) - Player 2 (O)

| | X | O | X_____|_____|_____ | | 4 | O | 6_____|_____|_____ | | 7 | 8 | 9 | |

Player 1, enter a number: 8

Tic Tac Toe

Player 1 (X) - Player 2 (O)

| | X | O | X_____|_____|_____ | | 4 | O | 6_____|_____|_____ | | 7 | X | 9 | |

Player 2, enter a number: 4

Page 114: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

Tic Tac Toe

Player 1 (X) - Player 2 (O)

| | X | O | X_____|_____|_____ | | O | O | 6_____|_____|_____ | | 7 | X | 9 | |

Player 1, enter a number: 7

Tic Tac Toe

Player 1 (X) - Player 2 (O)

| | X | O | X_____|_____|_____ | | O | O | 6_____|_____|_____ | | X | X | 9 | |

Player 2, enter a number: 6

Tic Tac Toe

Player 1 (X) - Player 2 (O)

| | X | O | X_____|_____|_____ | | O | O | O_____|_____|_____ | | X | X | 9 | | ==> Player 2 win

Page 115: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

ASSIGNMENT NO:14 PROBLEM STATEMENT: Binary tree traversals BFS & DFS using Python classes.

AIM: To study and implement Binary Tree Traversals BFS and DFS

FACILITIES (TOOLS USED):Linux operating system, Turbo C++, Eclipse

ALGORITHM:

THEORY:

Tree traversal refers to the process of visiting (examining and/or updating) each node in a tree data structure, exactly once, in a systematic way. Such traversals are classified by the order in which the nodes are visited. Traversing a tree involves iterating (looping) over all nodes in some manner. Because from a given node there is more than one possible next node (it is not a linear data structure), then, assuming sequential computation (not parallel), some nodes must be deferred – stored in some way for later visiting. Traversing a tree involves iterating (looping) over all nodes in some manner. Because from a given node there is more than one possible next node (it is not a linear data structure), then, assuming sequential computation (not parallel), some nodes must be deferred – stored in some way for later visiting. This is often done via a stack (LIFO) or queue (FIFO). As a tree is a self-referential (recursively defined) data structure, traversal can naturally be described by recursion in which case the deferred nodes are stored implicitly – in the case of recursion, in the call stack. Nodes of the tree represented as: void print_tree(binary_tree *t) { if (! is_empty(t)) { print_tree(t->left); /* L */ print_tree(t->right); /* R */ printf("%d\n",t->value); /* N */ } }Tree Traversal can be done in two ways, those are given as below:

Depth-first search

To traverse any tree in depth-first order, perform the following operations recursively at each node: 1. Perform pre-order operation

2. For each i (with i = 1 to n − 1) do: 1. Visit i-th, if present

2. Perform in-order operation 3. Visit n-th (last) child, if present

4. Perform post-order operation

Breadth-first search Trees can also be traversed in level-order, where we visit every node on a level before going to a lower level. Example

Page 116: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

Depth-first search Pre-order traversal sequence: F, B, A, D, C, E, G, I, H (root, left, right)

In-order traversal sequence: A, B, C, D, E, F, G, H, I (left, root, right)

Post-order traversal sequence: A, C, E, D, B, H, I, G, F (left, right, root)

Breadth- first serach Level-order traversal sequence: F, B, G, A, D, I, C, E, H

Page 117: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

INPUT: 1. Binary Tree node values

OUTPUT: 1. BFS and DFS Traversal of given Binary Tree.

FAQ: 1. Explain BFS and DFS of a Binary Tree? 2. Which Data Structures are used for BFS and DFS Traversals of a Tree or Graph

CONCLUSION: Thus we have performed BFS and DFS traversal on given Binary Tree

NAME OF FACULTY:

SIGNATURE:

DATE:

Page 118: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

PROGRAM CODE Title:Binary tree traversals BFS & DFS using Python classes. Name: Class: SEDiv: ARoll No: Batch: BFS : class Node(object): def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right def traverse(rootnode): thislevel = [rootnode] while thislevel: nextlevel = list() for n in thislevel: print n.value, if n.left: nextlevel.append(n.left) if n.right: nextlevel.append(n.right) print thislevel = nextlevel t = Node(1, Node(2, Node(4, Node(7))), Node(3, Node(5), Node(6))) traverse(t)

OUTPUT: -[root@Rajesh-CentOS ~]# python bfs.py 1 2 3 4 5 6 7

Page 119: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

ASSIGNMENT NO:15 PROBLEM STATEMENT: Write a program in C++ to implement hash table and handle the collision using linear probing and chaining. (with or without replacement) for employee information. Using the above Implement direct access file mechanism.

AIM: To understand the concept of collision handling and implement the same using linear probing and chaining. (without replacement) for employee information

FACILITIES (TOOLS USED):Linux Operating Systems, Turbo C++ ALGORITHM: Init Function: Step 1: Start. Step 2: Using for loop acc no and link is -1. Step 3: “-“ is copy in booktitle and author name. Step 4: Stop. Hash Function: Step 1: Start. Step 2: Initialize adr and r as integer type. Step 3: Using do while loop performing modular operation upto n is not equal to 0. Step 4: Stop. Insert Function : Step 1: Start. Step 2: Checking of adr of acc no is -1 then acc no inserted. Step 3: Copy the booktitle and author into b array. Step 4: Prev is equal to -1 giving link otherwise start and prev is pointto adr of array. Step 5: Changing the address and checking acc no is not equal to-1 then increment adr.Step 6: Copy the booktitle and author in b array. Step 7: Stop. Print Function : Step 1: Start. Step 2: if start=-1 then print list is empty. Step 3: Print Index, Acc no, Book name, Author and Link. Using while loop print acc no, book title, author and link. Step 4: Stop. Print_Replace Function: Step 1: Start. Step 2: If start=-1 then print list is empty. Step 3: Using while loop print acc no, book title, author name. Step 4: Stop. Search Function : Step 1: Start. Step 2: Using while we check i is not equal to -1 then no is equal to link of array b then return this link. Step 3: Otherwise return -1. Step 4: Stop. Dlit Function : Step 1: Start. Step 2: Check if start is -1 or not. If -1 then return (-1). Step 3: Otherwise using while loop checking acc no of array and no of

Page 120: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

whose record is deleted. If this is found then return one. Step 4: Then call search function. Step 5: Copy “-“in book title and author and return zero. Step 6: Stop. Main Function : Step 1: Start. Step 2: Print Menu like 1. Insert record without replacement.2. Insert record with replacement. 3. Delete record. 4. Display for without replacement. 5. Display for with replacement. 6. Exit. Step 3: Taking choice from user. Step 4: If choice is 1 then call insert function. Step 5: If choice is 2 then call insert function. Step 6: if choice is 3 then call dlit function. Pass whose record of book is deleted. Step 7: If choice is 4 then call print function. Step 8: If choice is 5 then call print_replace function. Step 9: if choice is 6 then Exit. Step 10: Stop. INPUT: 1. Employee Information

OUTPUT: Hash Table containing Employee Information FAQ: 1. How to handle the collision using linear probing and chaining ? CONCLUSION: Thus we have implemented Hash Table for Employee Information and Handled Collision using Linear Probing without Replacement

NAME OF FACULTY:

SIGNATURE: DATE:

Page 121: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

PROGRAM CODE Title:Write a program in C++ to implement hash table and handle the collision using linear probing and chaining. (without replacement) for employee information. Using the above implement direct access file mechanism. Name: Class: SEDiv: ARoll No: Batch:

Page 122: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

ASSIGNMENT NO:16

PROBLEM STATEMENT: Write a program to create a binary tree if preorder & post-order traversals are given in JAVA. AIM: 1.To learn concept of binary tree. 2.To understand construction of binary tree and its Traversals. FACILITIES (TOOLS USED): Linux Operating Systems, Eclipse framework. ALGORITHM: Main 1. Set Inorder and Preorder traversals 2. startNode = buildTree(0, in.length-1) 3. printPreorder(startNode) 4. printInorder(startNode) 5. printPostorder(startNode) 6. Stop BuildTree(Start,End) 1. If (inStart>inEnd) return NULL End If 2. Create a new tree node tNode with tNode.data = preorder[preIndex]. 3. Increment a preIndex Variable to pick next element in next recursive call. 4. If(inStart == inEnd) return tNode End If5.Find the picked element’s index in Inorder. Let the index be inIndex.6. tNode.left = buildTree (inStart, inIndex-1) 7. tNode.right = buildTree ( inIndex+1, inEnd) 8. return tNode. THEORY: A binary tree is a tree in which no node can have more than two children. Because there are only two children, named them as left and right. A binary tree is balancedif for every node in the tree the height of the left and right subtrees is within one as shown below.

A node with one child could have either a left or right child. Binary trees have many important uses. One use of the binary tree is in the expression tree, which is a central data structure in compiler design. The leaves of an expression tree are operands, such as constants or variable names; the other nodes contain operators. This particular tree is binary because all the operations are binary. The values obtained by recursively evaluating the left and right subtrees. A second use of the binary tree is the Huffman coding tree, which is used to implement a simple but relatively effective data

Page 123: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

compression algorithm. Each symbol in the alphabet is stored at a leaf. A left link corresponds to a 0 and a right link to a 1. Other uses of the binary tree are in binary search trees, which allow logarithmic time insertions and accessing of items, and priority queues, which support the access and deletion of the minimum in a collection of items. There are a number of algorithms for traversing a binary tree given a pointer to the root of the tree. The most common strategies are preorder, inorder, and postorder.

Preorder traversal: To traverse a binary tree in preorder, following operations are carried-out (i) Visit the root, (ii) Traverse the left subtree, and (iii) Traverse the right subtree. Therefore, the preorder traversal of binary tree shown in the fig. 1 will output:

A B E F D H I

Inorder traversal: To traverse a binary tree in inorder, following operations are carried-out (i) Traverse the left most subtree starting at the left external node, (ii) Visit the root, and (iii) Traverse the right subtree starting at the left external node. Therefore, the inorder traversal of binary tree shown in the fig. 1 will output:

E B F A H D I

Postorder traversal: To traverse a binary tree in postorder, following operations are carried-out (i) Traverse all the left external nodes starting with the left most subtree which is then followed by bubble-up all the internal nodes, (ii) Traverse the right subtree starting at the left external node which is then followed by bubble-up all the internal nodes, and (iii) Visit the root. Therefore, the postorder traversal of binary tree shown in the fig. 1 will output:

E F B H I D A

INPUT: 1. Preorder Traversal

2. Inorder Traversal

OUTPUT: 1. Postorder Traversal

FAQ: 1) What is Tree?

2) What is Binary tree traversal?

3) What is the maximum number of levels in a binary tree containing n nodes? 4) What is the maximum number of nodes in a binary tree containing k levels? Here is an alternate form of the same question: How many nodes are in a full binary tree with k levels?

5) Can you draw an example of a balanced binary tree that is not perfectly balanced? CONCLUSION: We have learned to create binary tree if preorder and postorder or inorder and postorder are given.

NAME OF FACULTY:

SIGNATURE:

DATE:

Page 124: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

PROGRAM CODE Title:Write a program to create a binary tree if preorder & post-order traversals are given in JAVA. Name: Class: SERoll No: Batch:

import java.util.Arrays;

import java.util.List;

import java.util.*;

public class ReConstructBTree {

/**

* @param args

*/

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

System.out.println("Enter PreOrder Element With Spaces in between.");

String preString = in.nextLine();

System.out.println("Enter PostOrder Element with Spaces in between.");

String postString = in.nextLine();

String[] pre = preString.split("\\s");

String[] post = postString.split("\\s");

List preList = Arrays.asList(pre);

List postList = Arrays.asList(post);

Page 125: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

BTree tree = reBuildTree(preList, postList);

System.out.print("Post Order :");

tree.postOrder(tree);//print post order to re-check

System.out.println();

System.out.print("Pre Order :");

tree.preOrder(tree);//print pre order to re-check

System.out.println();

System.out.print("In - Order :");

tree.inOrder(tree); //print in-order

}

private static BTree reBuildTree(List preList, List postList) {

BTree tree = null;

if(preList.size() != 0 && postList.size() != 0) {

tree = new BTree();

String val = (String)preList.get(0);

tree.val = val;

if(preList.size() > 1 && postList.size() > 1) {

int postOrderPos = postList.indexOf(preList.get(1));

int preOrderPos = preList.indexOf(postList.get(postList.size()-2));

//find the two sub set of the list from pre-order

List leftPreOrder = preList.subList(1, preOrderPos);

List rightPreOrder = preList.subList(preOrderPos, preList.size());

Page 126: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

//find the two sub set of the list from post-order

List leftPostOrder = postList.subList(0, postOrderPos+1);

List rightPostOrder = postList.subList(postOrderPos+1, postList.size()-1);

tree.left = reBuildTree(leftPreOrder, leftPostOrder);

tree.right = reBuildTree(rightPreOrder, rightPostOrder);

}

}

return tree;

}

static class BTree {

String val;

BTree left;

BTree right;

void inOrder(BTree tree) {

if(tree.left != null)

inOrder(tree.left);

System.out.print(tree.val+" ");

if(tree.right != null)

inOrder(tree.right);

}

void preOrder(BTree tree) {

System.out.print(tree.val+" ");

Page 127: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

if(tree.left != null)

preOrder(tree.left);

if(tree.right != null)

preOrder(tree.right);

}

void postOrder(BTree tree) {

if(tree.left != null)

postOrder(tree.left);

if(tree.right != null)

postOrder(tree.right);

System.out.print(tree.val+" ");

}

}

}

Page 128: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

ASSIGNMENT NO:17

PROBLEM STATEMENT: Write bubble Sort program using Python programming.

AIM: To understand the concept of Bubble Sort

FACILITIES (TOOLS USED):Linux Operating system, Turbo C++

ALGORITHM:

Algorithm Bubble Sort: Bubble(A, N) //Let A be an array with N elements. //This algorithm sorts the elements in array A. 1. Repeat for I = 0 to N:

1. Repeat for J = 0 to N-1:

1. If A[J] > A[J + 1], then Interchange A[J] & A[J +1].

2. End for

2. End for.

End Bubble Sort

INPUT : Array of Integers

OUTPUT: Sorted array of Integers

FAQ: 1. What is sorting?

2. How to sort the element using bubble sort?

3. What is Time complexity of bubble Sort?

CONCLUSION: Hence, we have studied sorting: Bubble sort.

NAME OF FACULTY: SIGNATURE: DATE:

Page 129: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

PROGRAM CODE Title:Write bubble Sort program using Python programming. Name: Class: SEDiv: ARoll No: Batch:

print "Python Program to sort the numbers using Bubble Sort"arrNumbers = []i = 0j = 0n = 0a = 0sum = 0temp = 0

print "Total Numbers:",n = input()

for i in range (0, n): print "Enter", i + 1, "Number: ", a = input() arrNumbers.append(a)

for i in range (1, n): for j in range (0, n - i): if( arrNumbers[j] > arrNumbers[j + 1]): temp = arrNumbers[j] arrNumbers[j] = arrNumbers[j + 1] arrNumbers[j + 1] = temp print "After iteration: ", i for k in range (0, n): print arrNumbers[k], print "/*** ", i + 1, "biggest number(s) is(are) pushed to the end of the array***/"

print "The sorted array is: ",for i in range (0, n): print arrNumbers[i],

Page 130: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

OUTPUT :-

#Python Program to sort the numbers using Bubble Sort#Total Numbers: 5#Enter 1 Number: 5#Enter 2 Number: 4#Enter 3 Number: 3#Enter 4 Number: 2#Enter 5 Number: 1#After iteration: 1#4 3 2 1 5 /*** 2 biggest number(s) is(are) pushed to the end of the array***/#After iteration: 2#3 2 1 4 5 /*** 3 biggest number(s) is(are) pushed to the end of the array***/#After iteration: 3#2 1 3 4 5 /*** 4 biggest number(s) is(are) pushed to the end of the array***/#After iteration: 4#1 2 3 4 5 /*** 5 biggest number(s) is(are) pushed to the end of the array***/#The sorted array is: 1 2 3 4 5

Page 131: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

ASSIGNMENT NO:18

PROBLEM STATEMENT: Write Tree Traversal Program using Java programming AIM: To learn concept of tree traversal. FACILITIES (TOOLS USED):Linux Operating Systems, Eclipse framework. ALGORITHM: 1. Start 2. Read the input sequence of nodes 3. Traverse the tree 4. Display the sequence 6. Stop ASSUMPTION: The given graph with set of vertices and edges. THEORY: Tree traversal refers to the process of visiting (examining and/or updating) each node in a tree data structure, exactly once, in a systematic way. Such traversals are classified by the order in which the nodes are visited. Traversing a tree involves iterating (looping) over all nodes in some manner. Because from a given node there is more than one possible next node (it is not a linear data structure), then, assuming sequential computation (not parallel), some nodes must be deferred – stored in some way for later visiting. Traversing a tree involves iterating (looping) over all nodes in some manner. Because from a given node there is more than one possible next node (it is not a linear data structure), then, assuming sequential computation (not parallel), some nodes must be deferred – stored in some way for later visiting. This is often done via a stack (LIFO) or queue (FIFO). As a tree is a self- referential (recursively defined) data structure, traversal can naturally be described by recursion in which case the deferred nodes are stored implicitly – in the case of recursion, in the call stack. Nodes of the tree represented as: void print_tree(binary_tree *t) { if (! is_empty(t)) { print_tree(t->left); /* L */ print_tree(t->right); /* R */ printf("%d\n",t->value); /* N */ } } Tree Traversal can be done in two ways, those are given as below: Depth-first search To traverse any tree in depth-first order, perform the following operations recursively at each node: 5. Perform pre-order operation

6. For each i (with i = 1 to n − 1) do: 1. Visit i-th, if present

2. Perform in-order operation 7. Visit n-th (last) child, if present

8. Perform post-order operation

Breadth-first search Trees can also be traversed in level-order, where we visit every node on a level before going to a lower level.

Page 132: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

Depth-first search Pre-order traversal sequence: F, B, A, D, C, E, G, I, H (root, left, right)

In-order traversal sequence: A, B, C, D, E, F, G, H, I (left, root, right)

Post-order traversal sequence: A, C, E, D, B, H, I, G, F (left, right, root)

Page 133: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

Breadth-first serach Level-order traversal sequence: F, B, G, A, D, I, C, E, H

APPLICATIONS

1. Pre-order traversal while duplicating nodes and values can make a complete duplicate of a binary tree. It can also be used to make a prefix expression from expression trees: traverse the expression tree pre-orderly.

2. In-order traversal is very commonly used on binary search trees because it returns values from the underlying set in order, according to the comparator that set up the binary search tree (hence the name).

3. Post-order traversal while deleting or freeing nodes and values can delete or free an entire binary tree. It can also generate a postfix representation of a binary tree. INPUT: 1. Number of vertices.

2. Number of edges.

3. Each edge with first vertex of edge and second vertex of edge.

OUTPUT: 1. Graph representation using adjacency matrix

2. Result after tree traversal FAQ: 1. What is definition of tree?

2. What is Tree traversal?

3. What are methods of tree traversal?

4. What are applications of tree traversal?

CONCLUSION: Thus, We have designed tree traversal algorithm. NAME OF FACULTY: SIGNATURE: DATE:

Page 134: thirdyearengineering.weebly.comthirdyearengineering.weebly.com/.../38286065/dsps.docx  · Web viewFrequency of item’s cost . FAQ: 1. ... Thus, to search any word & its meanings

PROGRAM CODETitle:Write Tree Traversal Program using Java programming

Name: Class: SEDiv:ARoll No: Batch: