DSA code pdf
DSA code pdf
#include <iostream>
#include <string>
using namespace std;
public:
Hashing() : i(0), t(0), index(0) {}
index = i % size;
// Inserting record using linear probing in case of collision
for (int j = 0; j < size; j++) {
if (data[index].id == 0) {
data[index].id = i;
data[index].name = n;
data[index].tel = t;
break;
} else {
index = (index + 1) % size;
}
}
}
cout << "\nSearching for record with ID: " << key << endl;
if (!found) {
cout << "Record not found." << endl;
}
}
cout << "\nDeleting record with ID: " << key << endl;
if (!found) {
cout << "Record not found." << endl;
}
}
cout << "\nUpdating record with ID: " << key << endl;
if (found) {
n = " Raj Shah";
t = 23413421;
data[index1].name = n;
data[index1].tel = t;
// Driver code
int main() {
Hashing s;
Output :-
1. CREATE record
2. DISPLAY record
Displaying all records:
ID Name Telephone
4 Akshath Singh 23451234
3. SEARCH record
Record found:
ID: 4
Name: Akshath Singh
Telephone: 23451234
4. UPDATE record
5. DELETE record
class HashTable:
def __init__(self):
self.size = 10
self.slots = [None] * self.size
self.data = [None] * self.size
self.indices = [-1] * self.size
H = HashTable()
H[54] = "Rohit"
H[26] = "Anaya"
H[93] = "Nikita"
H[17] = "Amar"
H[77] = "Manali"
H[31] = "Shilpa"
H[44] = "Aniket"
H[99] = "Prasad"
H[20] = "Pawan"
print("Keys:")
print(H.slots)
print("Data at their respective Keys:")
print(H.data)
print(H.indices)
print(H[77])
H.delete(77)
Output:-
Keys:
[20, 31, None, 93, 54, 44, 26, 17, 77, 99]
Data at their respective Keys:
['Pawan', 'Shilpa', None, 'Nikita', 'Rohit', 'Aniket', 'Anaya', 'Amar', 'Manali', 'Prasad']
[-1, -1, -1, -1, 5, -1, -1, 8, -1, -1]
Manali
After deletion of data in H[77]
Keys:
[20, 31, None, 93, 54, 44, 26, 17, None, 99]
Data at their respective Keys:
['Pawan', 'Shilpa', None, 'Nikita', 'Rohit', 'Aniket', 'Anaya', 'Amar', None, 'Prasad']
[-1, -1, -1, -1, 5, -1, -1, -1, -1, -1]
#include<iostream>
#include <iostream>
#include <string.h>
using namespace std;
struct node // Node Declaration
{
string label;
//char label[10];
int ch_count;
struct node *child[10];
} * root;
class GT // Class Declaration
{
public:
void create_tree();
void display(node *r1);
GT()
{
root = NULL;
}
};
void GT::create_tree()
{
int tbooks, tchapters, i, j, k;
root = new node;
cout << "Enter name of book : ";
cin.get();
getline(cin, root->label);
cout << "Enter number of chapters in book : ";
cin >> tchapters;
root->ch_count = tchapters;
for (i = 0; i < tchapters; i++)
{
root->child[i] = new node;
cout << "Enter the name of Chapter " << i + 1 << " : ";
cin.get();
getline(cin, root->child[i]->label);
cout << "Enter number of sections in Chapter : " << root->child[i]->label << " : ";
cin >> root->child[i]->ch_count;
for (j = 0; j < root->child[i]->ch_count; j++)
{
root->child[i]->child[j] = new node;
cout << "Enter Name of Section " << j + 1 << " : ";
cin.get();
getline(cin, root->child[i]->child[j]->label);
//cout<<"Enter no. of subsections in "<<r1->child[i]->child[j]->label;
//cin>>r1->child[i]->ch_count;
}
}
}
void GT::display(node *r1)
{
int i, j, k, tchapters;
if (r1 != NULL)
{
cout << "\n-----Book Hierarchy---";
cout << "\n Book title : " << r1->label;
tchapters = r1->ch_count;
for (i = 0; i < tchapters; i++)
{
cout << "\nChapter " << i + 1;
cout << " : " << r1->child[i]->label;
cout << "\nSections : ";
for (j = 0; j < r1->child[i]->ch_count; j++)
{
cout << "\n"<< r1->child[i]->child[j]->label;
}
}
}
cout << endl;
}
int main()
{
int choice;
GT gt;
while (1)
{
cout << "-----------------" << endl;
cout << "Book Tree Creation" << endl;
cout << "-----------------" << endl;
cout << "1.Create" << endl;
cout << "2.Display" << endl;
cout << "3.Quit" << endl;
cout << "Enter your choice : ";
cin >> choice;
switch (choice)
{
case 1:
gt.create_tree();
case 2:
gt.display(root);
break;
case 3:
exit(1);
default:
cout << "Wrong choice!!!" << endl;
}
}
return 0;
}
Output:-
-----------------
Book Tree Creation
-----------------
1.Create
2.Display
3.Quit
Enter your choice : 1
Enter name of book : Dsa
Enter number of chapters in book : 2
Enter the name of Chapter 1 : Graph
Enter number of sections in Chapter : Graph : 1
Enter Name of Section 1 : introduction to graph
Enter the name of Chapter 2 : Tree
Enter number of sections in Chapter : tree : 2
Enter Name of Section 1 : Introduction to tree
Enter Name of Section 2 : tree treversal
-----Book Hierarchy---
Book title : Dsa
Chapter 1 : Graph
Sections :
introduction to graph
Chapter 2 : tree
Sections :
Introduction to tree
tree treversal
-----------------
Book Tree Creation
-----------------
1.Create
2.Display
3.Quit
Enter your choice :
Assignment 4
#include <iostream>
#include <algorithm>
return root;
}
swap(root->left, root->right);
swapChildren(root->left);
swapChildren(root->right);
}
if (root->data == data) {
return true;
} else if (data < root->data) {
return search(root->left, data);
} else {
return search(root->right, data);
}
}
int main() {
Node* root = NULL;
int choice, value;
while (true) {
cout << "\nMenu:";
cout << "\n1. Insert a node";
cout << "\n2. Find the number of nodes in the longest path from the root (height)";
cout << "\n3. Find the minimum data value in the BST";
cout << "\n4. Swap the roles of left and right pointers at every node";
cout << "\n5. Search for a value in the BST";
cout << "\n6. Exit";
cout << "\nEnter your choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Enter the value to insert: ";
cin >> value;
root = insert(root, value);
cout << "Node inserted.";
break;
case 2:
cout << "Height of the tree: " << findHeight(root);
break;
case 3:
if (root == NULL) {
cout << "BST is empty.";
} else {
cout << "Minimum value in the tree: " << findMin(root);
}
break;
case 4:
swapChildren(root);
cout << "Children swapped at every node.";
break;
case 5:
cout << "Enter the value to search: ";
cin >> value;
if (search(root, value)) {
cout << "Value found in the BST.";
} else {
cout << "Value not found.";
}
break;
case 6:
cout << "Exiting...";
return 0;
default:
cout << "Invalid choice. Try again.";
break;
}
}
return 0;
}
Output :-
Menu:
1. Insert a node
2. Find the number of nodes in the longest path from the root (height)
3. Find the minimum data value in the BST
4. Swap the roles of left and right pointers at every node
5. Search for a value in the BST
6. Exit
Enter your choice: 1
Enter the value to insert: 39
Node inserted.
Menu:
1. Insert a node
2. Find the number of nodes in the longest path from the root (height)
3. Find the minimum data value in the BST
4. Swap the roles of left and right pointers at every node
5. Search for a value in the BST
6. Exit
Enter your choice: 1
Enter the value to insert: 44
Node inserted.
Menu:
1. Insert a node
2. Find the number of nodes in the longest path from the root (height)
3. Find the minimum data value in the BST
4. Swap the roles of left and right pointers at every node
5. Search for a value in the BST
6. Exit
Enter your choice: 1
Enter the value to insert: 27
Node inserted.
Menu:
1. Insert a node
2. Find the number of nodes in the longest path from the root (height)
3. Find the minimum data value in the BST
4. Swap the roles of left and right pointers at every node
5. Search for a value in the BST
6. Exit
Enter your choice: 2
Height of the tree: 2
Menu:
1. Insert a node
2. Find the number of nodes in the longest path from the root (height)
3. Find the minimum data value in the BST
4. Swap the roles of left and right pointers at every node
5. Search for a value in the BST
6. Exit
Enter your choice:
Assignment 5
return 0;
}
Output:-
Inorder traversal of the created threaded tree is:
4251637
Assignment 6
#include <iostream>
#include <iomanip>
using namespace std;
// Forward declaration
class EdgeList;
public:
EdgeList() {
n = 0;
}
public:
PhoneGraph(int num) {
n = num;
}
// Prim's algorithm
for (int i = 0; i < n - 1; i++) {
int k = minCost(cost, visited); // Get the vertex with the minimum cost
visited[k] = true; // Mark as visited
return minCost;
}
// Kruskal's algorithm
for (int i = 0; i < elist.n; i++) {
int cno1 = find(belongs, elist.data[i].u); // Component of vertex u
int cno2 = find(belongs, elist.data[i].v); // Component of vertex v
do {
cout << "\n1. Find Minimum Total Cost (by Prim's Algorithm)"
<< "\n2. Find Minimum Total Cost (by Kruskal's Algorithm)"
<< "\n3. Re-Read Graph (INPUT)"
<< "\n4. Print Graph"
<< "\n0. Exit"
<< "\nEnter your choice: ";
cin >> choice; // Get user input
switch (choice) {
case 1:
cout << "Minimum cost of Phone Line to Cities is: " << p1.prim() << endl;
break;
case 2:
p1.kruskal(spantree); // Use Kruskal's Algorithm
spantree.print(); // Print the spanning tree
break;
case 3:
p1.readGraph(); // Re-read the adjacency matrix
break;
case 4:
p1.printGraph(); // Print the adjacency matrix
break;
case 0:
break; // Exit loop
default:
cout << "\nWrong Choice!" << endl;
}
return 0;
}
Output :-
1 1--0 = 4
Minimum cost of Flight path Graph = 4
#include <iostream>
#include <iomanip>
#include <limits>
// Forward declaration
class EdgeList;
class Edge {
public:
int u, v, w;
// EdgeList class
class EdgeList {
public:
Edge data[MAX];
int n;
EdgeList() {
n = 0;
}
void sort();
void print();
void EdgeList::print() {
int total_cost = 0;
for (int i = 0; i < n; i++) {
cout << "\n" << i + 1 << " " << data[i].u << "--" << data[i].v << " = " << data[i].w;
total_cost += data[i].w;
}
cout << "\nMinimum cost of Telephone Graph = " << total_cost;
}
// PhoneGraph class
class PhoneGraph {
int data[MAX][MAX];
int n;
public:
PhoneGraph(int num) {
n = num;
}
void readgraph();
void printGraph();
int mincost(int cost[], bool visited[]);
int prim();
void kruskal(EdgeList &spanlist);
int find(int belongs[], int vertexno);
void unionComp(int belongs[], int c1, int c2);
};
void PhoneGraph::printGraph() {
cout << "\nAdjacency (COST) Matrix:\n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << setw(3) << data[i][j];
}
cout << endl;
}
}
int PhoneGraph::prim() {
bool visited[MAX];
int parents[MAX];
int cost[MAX];
int mincost = 0;
for (int i = 1; i < n; i++) {
mincost += cost[i];
}
return mincost;
}
// Populate EdgeList
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
if (data[i][j] != 0) {
elist.data[elist.n] = Edge(i, j, data[i][j]);
elist.n++;
}
}
}
// Initialize components
for (int i = 0; i < n; i++) {
belongs[i] = i;
}
// Main program
int main() {
int vertices;
int choice;
EdgeList spantree;
PhoneGraph p1(vertices);
p1.readgraph();
do {
cout << "\n1. Find Minimum Total Cost (Prim's Algorithm)"
<< "\n2. Find Minimum Total Cost (Kruskal's Algorithm)"
<< "\n3. Re-read Graph"
<< "\n4. Print Graph"
<< "\n0. Exit"
<< "\nEnter your choice: ";
switch (choice) {
case 1:
cout << "Minimum cost of Phone Line to cities is: " << p1.prim() << endl;
break;
case 2:
p1.kruskal(spantree);
spantree.print();
break;
case 3:
p1.readgraph();
break;
case 4:
p1.printGraph();
break;
default:
cout << "\nInvalid choice. Please try again." << endl;
}
return 0;
}
Output :-
#include <iostream>
#include <climits>
// Driver Code
int main() {
int keys[] = {10, 12, 20};
int freq[] = {34, 8, 50};
int n = sizeof(keys) / sizeof(keys[0]);
return 0;
}
Output :-
#include <iostream>
#include <string>
using namespace std;
struct node {
string word;
string meaning;
node* left;
node* right;
};
int main() {
node* root = nullptr;
insert(root, "hello");
insert(root, "world");
inorder_rec(root);
return 0;
}
Output :-
hello :
world :
#include <iostream>
using namespace std;
while (j <= n) {
if (j < n && a[j + 1] > a[j])
j = j + 1;
a[j / 2] = a[j];
j = 2 * j;
}
a[j / 2] = temp;
}
while (j <= n) {
if (j < n && a[j + 1] < a[j])
j = j + 1;
a[j / 2] = a[j];
j = 2 * j;
}
a[j / 2] = temp;
}
int main() {
int n;
cout << "Enter the number of Students: ";
cin >> n;
return 0;
}
Output :-
#include <iostream>
#include <fstream>
#include <cstring>
#include <iomanip>
public:
// Default constructor
Student() : rollNo(0), div(0), year(0) {
strcpy(name, "");
strcpy(city, "");
}
// Parameterized constructor
Student(int rollNo, const char* name, int year, char div, const char* city)
: rollNo(rollNo), div(div), year(year) {
strcpy(this->name, name);
strcpy(this->city, city);
}
public:
// Constructor to open file
FileOperations(const char* filename) {
file.open(filename, ios::in | ios::out | ios::ate | ios::binary);
if (!file.is_open()) {
cerr << "Error: Unable to open file." << endl;
exit(1);
}
}
void insertRecord(int rollNo, const char* name, int year, char div, const char* city) {
Student s(rollNo, name, year, div, city);
file.seekp(0, ios::end);
file.write(reinterpret_cast<char*>(&s), sizeof(Student));
file.clear();
}
void displayAll() {
Student s;
file.seekg(0, ios::beg);
cout << setw(5) << "ROLL" << setw(20) << "NAME" << setw(5) << "YEAR" << setw(5) <<
"DIV" << setw(10) << "CITY" << endl;
while (file.read(reinterpret_cast<char*>(&s), sizeof(Student))) {
s.displayRecord();
}
file.clear();
}
if (!found) {
cout << "\nRecord of roll number " << rollNo << " is not present." << endl;
}
file.close();
outFile.close();
remove("student.dat");
rename("new.dat", "student.dat");
file.open("student.dat", ios::in | ios::out | ios::ate | ios::binary);
}
~FileOperations() {
file.close();
cout << "\nFile Closed." << endl;
}
};
// Main function
int main() {
ofstream newFile("student.dat", ios::app | ios::binary);
newFile.close();
FileOperations file("student.dat");
while (choice != 5) {
cout << "\n***** Student Database *****\n";
cout << "1) Add New Record\n";
cout << "2) Display All Records\n";
cout << "3) Display by RollNo\n";
cout << "4) Delete a Record\n";
cout << "5) Exit\n";
cout << "Choose your choice: ";
cin >> choice;
switch (choice) {
case 1: // Add new record
cout << "\nEnter RollNo and Name: ";
cin >> rollNo >> name;
cout << "Enter Year and Division: ";
cin >> year >> div;
cout << "Enter City: ";
cin >> city;
file.insertRecord(rollNo, name, year, div, city);
cout << "\nRecord Inserted." << endl;
break;
case 5: // Exit
cout << "\nExiting..." << endl;
break;
default:
cout << "\nInvalid choice. Please try again." << endl;
break;
}
}
return 0;
}
Output :-
#include <iostream>
#include <fstream>
#include <cstdio>
#include <cstring>
public:
void read();
void display();
int getEmpCode() { return code; }
float getSalary() { return salary; }
void updateSalary(float s) { salary = s; }
};
x.read();
if (!isFound) {
cout << "Record not found!!!\n";
}
file.close();
tempFile.close();
rename("TEMP.DAT", "EMPLOYEE.DAT");
cout << "Salary updated successfully." << endl;
}
Employee existingEmp;
bool isInserted = false;
while (file.read(reinterpret_cast<char*>(&existingEmp), sizeof(existingEmp))) {
if (existingEmp.getEmpCode() > newEmp.getEmpCode() && !isInserted) {
tempFile.write(reinterpret_cast<char*>(&newEmp), sizeof(newEmp));
isInserted = true;
}
tempFile.write(reinterpret_cast<char*>(&existingEmp), sizeof(existingEmp));
}
if (!isInserted) {
tempFile.write(reinterpret_cast<char*>(&newEmp), sizeof(newEmp));
}
file.close();
tempFile.close();
rename("TEMP.DAT", "EMPLOYEE.DAT");
cout << "Record inserted successfully." << endl;
}
switch (option) {
case 1:
appendToFile();
break;
case 2:
displayAll();
break;
case 3:
searchForRecord();
break;
case 4:
increaseSalary();
break;
case 5:
insertRecord();
break;
case 6:
cout << "Exiting..." << endl;
return 0; // Exit the program
default:
cout << "Invalid choice. Try again." << endl;
break;
}
return 0;
}
Output :-
Choose an option:
1. Add an employee
2. Display employees
3. Search employee
4. Increase salary
5. Insert employee
6. Exit
Make a choice: 1
Enter employee code: 002
Enter name: Akshath
Enter salary: 20000
Record added successfully.
Do you want to continue? (Y/N): y
Choose an option:
1. Add an employee
2. Display employees
3. Search employee
4. Increase salary
5. Insert employee
6. Exit
Make a choice: 2
Employee records with salary between 10,000 and 20,000:
2 Akshath 20000
Do you want to continue? (Y/N):