DSA-3
DSA-3
def linear(keys,hash,n):
print ("Telephone || Count")
for key in keys :
cnt = 1
index = key % n
if hash[index] is None:
hash[index] = key
print (hash[index]," : ",cnt)
else:
for j in range (1,n):
p = (index+j)%n
cnt = cnt + 1
if hash[p] is None:
hash[p] = key
print (hash[p]," : ",cnt)
break
else :
print ("Table is full")
def quadratic(keys,hash,n):
print("Telephone || Count")
for key in keys :
index = key % n
cnt = 1
if hash[index] is None:
hash[index] = key
print(hash[index], " : ", cnt)
else:
for j in range (n):
p = (index+j**2)%n
if hash[p] is None:
hash[p] = key
print(hash[p], " : ", cnt)
break
else:
print("Table is full")
print()
print ("Entered telephone numbers are ")
i=0
while (i != n):
print(keys[i])
i = i+1
while (True):
print ("Enter your choice \n1.Linear probing\n2.Quadratic Probing\n3.Exit")
ch = int(input("Enter your choice "))
if (ch == 1):
hash = [None]*n
linear (keys,hash,n)
print(hash)
print()
elif (ch == 2):
hash = [None]*n
quadratic (keys,hash,n)
print(hash)
print()
elif (ch == 3):
break
else :
print ("Invalid Input")
CHAINING
class Node:
def __init__(self, key, value):
self.key = key
self.value = value
self.next = None
class HashTable:
def __init__(self, size=100):
self.size = size
self.table = [None] * self.size
if self.table[index] is None:
self.table[index] = new_node
else:
current = self.table[index]
while current:
if current.key == key:
print(f"Error: Key '{key}' already exists. Cannot insert duplicate keys.")
return
if current.next is None:
break
current = current.next
current.next = new_node
while current:
if current.key == key:
return current.value
current = current.next
return None
while current:
if current.key == key:
if prev:
prev.next = current.next
else:
self.table[index] = current.next
return True
prev = current
current = current.next
return False
def menu():
ht = HashTable()
while True:
print("Hash Table Operations")
print("1. Insert")
print("2. Find")
print("3. Delete")
print("4. Exit")
if choice == '1':
key = input("Enter key: ")
value = input("Enter value: ")
ht.insert(key, value)
print()
menu()
BST CONSTRUCT
#include <iostream>
using namespace std;
struct Node
{
int data;
Node* right;
Node* left;
Node(int value)
{
data = value;
right = NULL;
left = NULL;
}
};
int main()
{
Node* root = NULL;
int n, value;
cout << "Enter " << n << " values to insert into the BST:\n";
for (int i = 0; i < n; i++)
{
cin >> value;
root = insert(root, value);
}
cout << "Longest path (height of the tree): " << longestPath(root) << endl;
findMin(root);
return 0;
}
DICTIONARY BST
#include <iostream>
using namespace std;
struct Node
{
int key;
string msg;
Node* left;
Node* right;
class Dictionary
{
public:
Node* root;
Dictionary()
{
root = nullptr;
}
if (k < root->key)
{
Node* temp = insert(root->left, k, msg);
root->left = temp;
}
else if (k > root->key)
{
Node* temp = insert(root->right, k, msg);
root->right = temp;
}
return root;
}
return nullptr;
}
Node* minValueNode(Node* node)
{
Node* current = node;
while (current && current->left != nullptr)
{
current = current->left;
}
return current;
}
if (k < root->key)
{
Node* temp = deleteNode(root->left, k);
root->left = temp;
}
else if (k > root->key)
{
Node* temp = deleteNode(root->right, k);
root->right = temp;
}
else
{
// Node with only one child or no child
if (root->left == nullptr)
{
Node* temp = root->right;
delete root;
cout << "Key deleted successfully.\n";
return temp;
}
else if (root->right == nullptr)
{
Node* temp = root->left;
delete root;
cout << "Key deleted successfully.\n";
return temp;
}
return root;
}
int main()
{
int choice, k, displayChoice, comparisonCount;
string msg;
Dictionary d;
Node* root = nullptr;
do
{
cout << "\n1.Insert\n2.Update\n3.Delete\n4.Search\n5.Display\n6.Exit\n";
cout << "Enter Your choice: ";
cin >> choice;
if (choice == 1)
{
cout << "Enter key (integer) and message: ";
cin >> k >> msg;
Node* temp = d.insert(root, k, msg);
root = temp;
cout << "Insertion successful..\n";
}
else if (choice == 2)
{
cout << "Enter key to update: ";
cin >> k;
cout << "Enter new message: ";
cin >> msg;
d.update(root, k, msg);
}
else if (choice == 3)
{
cout << "Enter key to delete: ";
cin >> k;
Node* temp = d.deleteNode(root, k);
root = temp;
}
else if (choice == 4)
{
cout << "Enter key to search: ";
cin >> k;
Node* result = d.search(root, k, comparisonCount);
if (result)
cout << "Key found! Message: " << result->msg << " (Comparisons: " <<
comparisonCount << ")\n";
else
cout << "Key not found. (Comparisons: " << comparisonCount << ")\n";
}
else if (choice == 5)
{
cout << "\n1. Display in Ascending Order\n2. Display in Descending Order\n";
cout << "Enter your choice: ";
cin >> displayChoice;
if (displayChoice == 1)
{
cout << "\nDictionary in Ascending Order:\n";
d.displayAscending(root);
}
else if (displayChoice == 2)
{
cout << "\nDictionary in Descending Order:\n";
d.displayDescending(root);
}
else
{
cout << "Invalid choice!\n";
}
}
else if (choice == 6)
{
cout << "Exiting program...\n";
break;
}
else
{
cout << "Invalid choice! Try again.\n";
}
}
while (true);
return 0;
}
struct Node {
int key;
Node *left, *right;
bool leftThread;
bool rightThread;
Node(int key) {
this->key = key;
left = right = nullptr;
leftThread = rightThread = false;
}
};
// Step 1: Create fully threaded binary tree (both left and right threads)
void createFullThreaded(Node* root, Node*& prev) {
if (root == nullptr)
return;
createFullThreaded(root->left, prev);
// Left thread
if (root->left == nullptr) {
root->left = prev;
root->leftThread = true;
}
prev = root;
createFullThreaded(root->right, prev);
}
int main() {
Node* root = createTree();
return 0;
}
DFS BFS
#include<iostream>
#include<vector>
#include<map>
#include<queue>
#include<stack>
using namespace std;
class Graph{
private:
map<string,vector<string>>adjList;//Adjacency List
map<string,int>nodeIndex;
vector<vector<int>>adjMatrix;
vector<string>landmarks;
int numNodes;
public:
Graph(vector<string>nodes){
numNodes=nodes.size();
landmarks=nodes;
adjMatrix.resize(numNodes,vector<int>(numNodes,0));
for(int i=0;i<numNodes;i++){
nodeIndex[nodes[i]]=i;
}
}
int idxU=nodeIndex[u],idxV=nodeIndex[v];
adjMatrix[idxU][idxV]=1;
adjMatrix[idxV][idxU]=1;
}
void printAdjMatrix(){
cout << "Adjacency Matrix:\n";
for(int i=0; i<numNodes; i++){
for(int j=0; j<numNodes; j++){
cout << adjMatrix[i][j] << " ";
}
cout << endl;
}
}
if(!visited[nodeIdx]){
cout<<node<<" ";
visited[nodeIdx]=true;
}
for(int i=0;i<numNodes;i++){
if(adjMatrix[nodeIdx][i]==1 && !visited[i]){
s.push(landmarks[i]);
}
}
}
cout<<endl;
}
for(auto neighbor:adjList[start]){
if(!visited[neighbor]){
DFSList(neighbor,visited);
}
}
}
for(auto neighbor:adjList[node]){
if(!visited[neighbor]){
q.push(neighbor);
visited[neighbor]=true;
}
}
}
cout<<endl;
}
};
int main(){
vector<string> landmarks={"College","FC Road","JM Road","Shivajinagar","Deccan"};
Graph g(landmarks);
g.addEdge("College","FC Road");
g.addEdge("College","JM Road");
g.addEdge("FC Road","Shivajinagar");
g.addEdge("JM Road","Deccan");
g.addEdge("Shivajinagar","Deccan");
g.DFSMatrix("College");
g.printAdjMatrix();
g.performDFS("College");
g.BFS("College");
return 0;
}
FLIGHT PATHS
#include<iostream>
#include<unordered_map>
#include<vector>
#include<string>
#include<stack>
#include<set>
using namespace std;
class FlightGraph{
private:
Graph adjList;
public:
void addFlight(const string& from,const string& to,int cost){
adjList[from].push_back({to,cost});
adjList[to].push_back({from,cost});
}
void dfs(const string& city,set<string>& visited){
visited.insert(city);
for (const auto& neighbor : adjList[city]){
if(visited.find(neighbor.first)== visited.end()){
dfs(neighbor.first,visited);
}
}
}
bool isConnected(){
if(adjList.empty()) return true;
set<string>visited;
string startCity = adjList.begin()->first;
dfs(startCity,visited);
void displayGraph(){
for (const auto& pair : adjList){
cout<< pair.first <<" -> ";
for(const auto& neighbor : pair.second){
cout<< "(" << neighbor.first <<",cost: "<<neighbor.second << ")";
}
cout << endl;
}
}
};
int main(){
FlightGraph g;
g.addFlight("New York","London",7);
g.addFlight("London","paris",1);
g.addFlight("paris","Berlin",2);
g.addFlight("Berlin","Rome",3);
return 0;
}
return cost[1][n];
}
int main() {
int n;
cout << "Enter number of keys: ";
cin >> n;
vector<int> keys(n);
vector<float> p(n);
cout << "\nMinimum cost of Optimal BST: " << minCost << endl;
cout << "Root of the Optimal BST is key: " << keys[root[1][n] - 1] << endl;
return 0;
}
struct Node {
string key;
string meaning;
Node* left;
Node* right;
int height;
Node(string k, string m) {
key = k;
meaning = m;
left = nullptr;
right = nullptr;
height = 1;
}
};
Node* rotateRight(Node* y) {
Node* x = y->left;
Node* t2 = x->right;
x->right = y;
y->left = t2;
return x;
}
Node* rotateLeft(Node* x) {
Node* y = x->right;
Node* t2 = y->left;
y->left = x;
x->right = t2;
return y;
}
// Left Left
if (balance > 1 && key < root->left->key)
return rotateRight(root);
// Right Right
if (balance < -1 && key > root->right->key)
return rotateLeft(root);
// Left Right
if (balance > 1 && key > root->left->key) {
root->left = rotateLeft(root->left);
return rotateRight(root);
}
// Right Left
if (balance < -1 && key < root->right->key) {
root->right = rotateRight(root->right);
return rotateLeft(root);
}
return root;
}
return root;
}
int main() {
Node* root = nullptr;
int choice;
string key, meaning;
do {
cout << "\n--- Dictionary Menu ---\n";
cout << "1. Add or Update Keyword\n";
cout << "2. Delete Keyword\n";
cout << "3. Update Meaning\n";
cout << "4. Display in Ascending Order\n";
cout << "5. Display in Descending Order\n";
cout << "6. Search Keyword\n";
cout << "0. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
switch (choice) {
case 1:
cout << "Enter keyword: ";
cin >> key;
cout << "Enter meaning: ";
cin.ignore();
getline(cin, meaning);
root = insert(root, key, meaning);
break;
case 2:
cout << "Enter keyword to delete: ";
cin >> key;
root = deleteNode(root, key);
break;
case 3:
cout << "Enter keyword to update: ";
cin >> key;
cout << "Enter new meaning: ";
cin.ignore();
getline(cin, meaning);
updateMeaning(root, key, meaning);
break;
case 4:
cout << "Dictionary in Ascending Order:\n";
displayInOrder(root);
break;
case 5:
cout << "Dictionary in Descending Order:\n";
displayReverseOrder(root);
break;
case 6:
cout << "Enter keyword to search: ";
cin >> key;
searchKeyword(root, key);
break;
case 0:
cout << "Exiting program.\n";
break;
default:
cout << "Invalid choice. Try again.\n";
}
return 0;
}
int main() {
int n;
cout << "Enter number of students: ";
cin >> n;
vector<int> marks(n);
cout << "Enter marks of " << n << " students:\n";
for (int i = 0; i < n; ++i) {
cin >> marks[i];
}
priority_queue<int> maxHeap;
return 0;
}
EXTERNAL SORTING
import java.io.*;
import java.util.*;
public class Main {
static final int MEMORY_SIZE = 5;
public static void main(String[] args) throws IOException {
String inputFile = "input.txt";
String run1 = "run1.txt";
String run2 = "run2.txt";
String outputFile = "sorted_output.txt";
generateInputFile(inputFile);
createSortedRuns(inputFile, run1, run2);
mergeSortedRuns(run1, run2, outputFile);
System.out.println("Sorted output:");
BufferedReader reader = new BufferedReader(new FileReader(outputFile));
String line;
while ((line = reader.readLine()) != null) {
System.out.print(line + " ");
}
reader.close();
}
// Generate a sample unsorted input file
static void generateInputFile(String fileName) throws IOException {
int[] data = {42, 17, 8, 23, 4, 56, 19, 5, 30, 2};
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
for (int value : data) {
writer.write(Integer.toString(value));
writer.newLine();
}
writer.close();
}
// Divide input into sorted chunks
static void createSortedRuns(String inputFile, String run1, String run2) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writerA = new BufferedWriter(new FileWriter(run1));
BufferedWriter writerB = new BufferedWriter(new FileWriter(run2));
List<Integer> buffer = new ArrayList<>();
String line;
boolean writeToA = true;
while ((line = reader.readLine()) != null) {
buffer.add(Integer.parseInt(line));
if (buffer.size() == MEMORY_SIZE) {
Collections.sort(buffer);
writeBuffer(writeToA ? writerA : writerB, buffer);
buffer.clear();
writeToA = !writeToA;
}
}
if (!buffer.isEmpty()) {
Collections.sort(buffer);
writeBuffer(writeToA ? writerA : writerB, buffer);
}
reader.close();
writerA.close();
writerB.close();
}
static void writeBuffer(BufferedWriter writer, List<Integer> buffer) throws IOException {
for (int num : buffer) {
writer.write(Integer.toString(num));
writer.newLine();
}
}
// Merge two sorted files
static void mergeSortedRuns(String run1, String run2, String outputFile) throws IOException {
BufferedReader r1 = new BufferedReader(new FileReader(run1));
BufferedReader r2 = new BufferedReader(new FileReader(run2));
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile));
String s1 = r1.readLine();
String s2 = r2.readLine();
while (s1 != null && s2 != null) {
int n1 = Integer.parseInt(s1);
int n2 = Integer.parseInt(s2);
if (n1 <= n2) {
writer.write(Integer.toString(n1));
writer.newLine();
s1 = r1.readLine();
} else {
writer.write(Integer.toString(n2));
writer.newLine();
s2 = r2.readLine();
}
}
while (s1 != null) {
writer.write(s1);
writer.newLine();
s1 = r1.readLine();
}
while (s2 != null) {
writer.write(s2);
writer.newLine();
s2 = r2.readLine();
}
r1.close();
r2.close();
writer.close();
}
}
FILE HANDLING
import java.io.*;
import java.util.Scanner;
public class Main {
private static final String FILE_NAME = "students.txt";
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("\nStudent Information System");
System.out.println("1. Add Student");
System.out.println("2. Delete Student");
System.out.println("3. Display Student");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
int choice = scanner.nextInt();
scanner.nextLine(); // Consume newline character
switch (choice) {
case 1:
addStudent(scanner);
break;
case 2:
deleteStudent(scanner);
break;
case 3:
displayStudent(scanner);
break;
case 4:
System.out.println("Exiting...");
System.exit(0);
default:
System.out.println("Invalid choice. Please try again.");
}
}
}
public static void addStudent(Scanner scanner) {
System.out.print("Enter Roll Number: ");
String rollNumber = scanner.nextLine();
System.out.print("Enter Name: ");
String name = scanner.nextLine();
System.out.print("Enter Division: ");
String division = scanner.nextLine();
System.out.print("Enter Address: ");
String address = scanner.nextLine();
Student student = new Student(rollNumber, name, division, address);
if (found) {
file.delete();
tempFile.renameTo(file);
System.out.println("Student with roll number " + rollNumber + " deleted.");
} else {
System.out.println("Student with roll number " + rollNumber + " not found.");
}
} catch (IOException e) {
System.out.println("An error occurred while deleting the student record.");
}
}
public static void displayStudent(Scanner scanner) {
System.out.print("Enter Roll Number to display: ");
String rollNumber = scanner.nextLine();
try (BufferedReader reader = new BufferedReader(new FileReader(FILE_NAME))) {
String line;
boolean found = false;
while ((line = reader.readLine()) != null) {
Student student = Student.fromString(line);
if (student.rollNumber.equals(rollNumber)) {
System.out.println("Student Details:");
System.out.println("Roll Number: " + student.rollNumber);
System.out.println("Name: " + student.name);
System.out.println("Division: " + student.division);
System.out.println("Address: " + student.address);
found = true;
break;
}
}
if (!found) {
System.out.println("Student with roll number " + rollNumber + " not found.");
}
} catch (IOException e) {
System.out.println("An error occurred while reading the file.");
}
}
}
class Student {
String rollNumber;
String name;
String division;
String address;
public Student(String rollNumber, String name, String division, String address) {
this.rollNumber = rollNumber;
this.name = name;
this.division = division;
this.address = address;
}
public String toString() {
return rollNumber + "," + name + "," + division + "," + address;
}
public static Student fromString(String record) {
String[] parts = record.split(",");
return new Student(parts[0], parts[1], parts[2], parts[3]);
}
}