0% found this document useful (0 votes)
12 views

DSA-3

The document contains various implementations of data structures and algorithms including telephone book management using linear and quadratic probing, a hash table with chaining, binary search tree operations, a dictionary implemented as a binary search tree, a threaded binary tree, and graph traversal methods like DFS and BFS. Each section provides code snippets for creating, inserting, searching, and deleting elements in these data structures, along with user interaction through menus. The document serves as a comprehensive guide for understanding and implementing these fundamental data structures in programming.

Uploaded by

amkslade101
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

DSA-3

The document contains various implementations of data structures and algorithms including telephone book management using linear and quadratic probing, a hash table with chaining, binary search tree operations, a dictionary implemented as a binary search tree, a threaded binary tree, and graph traversal methods like DFS and BFS. Each section provides code snippets for creating, inserting, searching, and deleting elements in these data structures, along with user interaction through menus. The document serves as a comprehensive guide for understanding and implementing these fundamental data structures in programming.

Uploaded by

amkslade101
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

TELEPHONE BOOK

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")

n = int(input("Enter number of clients "))


hash = [None]*n
keys = []*n
i=0
while (i != n):
m = int(input("Enter the telephone number "))
length = len(str(m))
if (length==10):
keys.append(m)
i=i+1
else :
print("Invalid input , enter 10 digit number")

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

def _hash(self, key):


return hash(key) % self.size

def insert(self, key, value):


index = self._hash(key)
new_node = Node(key, value)

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

def find(self, key):


index = self._hash(key)
current = self.table[index]

while current:
if current.key == key:
return current.value
current = current.next
return None

def delete(self, key):


index = self._hash(key)
current = self.table[index]
prev = 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")

choice = input("Enter your choice: ")

if choice == '1':
key = input("Enter key: ")
value = input("Enter value: ")
ht.insert(key, value)
print()

elif choice == '2':


key = input("Enter key to find: ")
result = ht.find(key)
if result is not None:
print(f"Value for key '{key}': {result}")
else:
print(f"Key '{key}' not found")
print()

elif choice == '3':


key = input("Enter key to delete: ")
if ht.delete(key):
print(f"Key '{key}' deleted")
else:
print(f"Key '{key}' not found")
print()

elif choice == '4':


print("Exiting...")
break
else:
print("Invalid choice. Please try again.")
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;
}
};

Node* insert(Node* root, int value)


{
if (root == NULL)
{
return new Node(value);
}
else if (value < root->data)
{
root->left = insert(root->left, value);
}
else
{
root->right = insert(root->right, value);
}
return root;
}

int longestPath(Node* root)


{
if (root == NULL)
{
return 0;
}
int leftHeight = longestPath(root->left);
int rightHeight = longestPath(root->right);
return max(leftHeight, rightHeight) + 1;
}

void findMin(Node* root)


{
if (root == NULL)
{
cout << "tree is empty";
}
while (root->left != NULL)
{
root = root->left;
}
cout << "Minimum data value in the tree: " << root->data << endl;
}

bool search(Node* root, int value)


{
if (root == NULL)
{
return false;
}
if (root->data == value)
{
return true;
}
if (value < root->data)
{
return search(root->left, value);
}
return search(root->right, value);
}

void printInOrder(Node* root)


{
if (root != NULL)
{
printInOrder(root->left);
cout << root->data << " ";
printInOrder(root->right);
}
}

int main()
{
Node* root = NULL;
int n, value;

cout << "Enter the number of nodes to insert: ";


cin >> n;

cout << "Enter " << n << " values to insert into the BST:\n";
for (int i = 0; i < n; i++)
{
cin >> value;
root = insert(root, value);
}

cout << "In-order traversal of the BST: ";


printInOrder(root);
cout << endl;

cout << "Longest path (height of the tree): " << longestPath(root) << endl;

findMin(root);

cout << "Enter a value to search in the tree: ";


cin >> value;
if (search(root, value))
{
cout << "Value " << value << " found in the tree." << endl;
}
else
{
cout << "Value " << value << " not found in the tree." << endl;
}

return 0;
}

DICTIONARY BST
#include <iostream>
using namespace std;

struct Node
{
int key;
string msg;
Node* left;
Node* right;

Node(int k, string value)


{
key = k;
msg = value;
left = nullptr;
right = nullptr;
}
};

class Dictionary
{
public:
Node* root;

Dictionary()
{
root = nullptr;
}

Node* insert(Node* root, int k, string msg)


{
if (root == nullptr)
{
Node* temp = new Node(k, msg); // temp for clarity
return temp;
}

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;
}

void update(Node* root, int k, string msg)


{
Node* temp = root;
while (temp != nullptr)
{
if (k < temp->key)
temp = temp->left;
else if (k > temp->key)
temp = temp->right;
else
{
temp->msg = msg;
cout << "Update done successfully..\n";
return;
}
}
cout << "Key not found..\n";
}

Node* search(Node* root, int k, int &count)


{
Node* temp = root;
count = 0;

while (temp != nullptr)


{
count++;
if (temp->key == k)
return temp;
if (k < temp->key)
temp = temp->left;
else
temp = temp->right;
}

return nullptr;
}
Node* minValueNode(Node* node)
{
Node* current = node;
while (current && current->left != nullptr)
{
current = current->left;
}
return current;
}

Node* deleteNode(Node* root, int k)


{
if (root == nullptr)
{
cout << "Key not found, deletion unsuccessful.\n";
return root;
}

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;
}

// Node with two children


Node* temp = minValueNode(root->right);
root->key = temp->key;
root->msg = temp->msg;
root->right = deleteNode(root->right, temp->key);
}

return root;
}

void displayAscending(Node* root)


{
if (root)
{
displayAscending(root->left);
cout << root->key << " -> " << root->msg << endl;
displayAscending(root->right);
}
}

void displayDescending(Node* root)


{
if (root)
{
displayDescending(root->right);
cout << root->key << " -> " << root->msg << endl;
displayDescending(root->left);
}
}
};

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;
}

THREADED BINARY TREE


#include <iostream>
using namespace std;

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;
}

// Right thread for the previous node


if (prev != nullptr && prev->right == nullptr) {
prev->right = root;
prev->rightThread = true;
}

prev = root;

createFullThreaded(root->right, prev);
}

// Step 2: Find leftmost node in tree (used in traversal)


Node* leftmost(Node* node) {
while (node != nullptr && !node->leftThread)
node = node->left;
return node;
}

// Step 3: Inorder traversal using threads (no recursion/stack)


void inOrder(Node* root) {
Node* curr = leftmost(root);

while (curr != nullptr) {


cout << curr->key << " ";

// If right thread exists, use it


if (curr->rightThread)
curr = curr->right;
else
curr = leftmost(curr->right);
}
}

// Utility function to create a sample binary tree


Node* createTree() {
Node* root = new Node(4);
root->left = new Node(2);
root->right = new Node(6);
root->left->left = new Node(1);
root->left->right = new Node(3);
root->right->left = new Node(5);
root->right->right = new Node(7);
return root;
}

int main() {
Node* root = createTree();

Node* prev = nullptr;


createFullThreaded(root, prev);

cout << "Inorder Traversal (Threaded): ";


inOrder(root);

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;
}
}

void addEdge(string u,string v){


adjList[u].push_back(v);
adjList[v].push_back(u);//Since it's an undirected Graph

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;
}
}

void DFSMatrix(string start){


vector<bool>visited(numNodes,false);
stack<string>s;
s.push(start);

cout<<"DFS using Adjacency Matrix: ";


while(!s.empty()){
string node =s.top();
s.pop();
int nodeIdx=nodeIndex[node];

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;
}

void DFSList(string start,map<string,bool> &visited){


cout<<start<<" ";
visited[start]=true;

for(auto neighbor:adjList[start]){
if(!visited[neighbor]){
DFSList(neighbor,visited);
}
}
}

void performDFS(string start){


cout<<"DFS using Adjacency List: ";
map<string,bool>visited;
DFSList(start,visited);
cout<<endl;
}

void BFS(string start){


map<string,bool>visited;
queue<string>q;
q.push(start);
visited[start]=true;

cout<<"BFS using Adjacency List: ";


while(!q.empty()){
string node=q.front();
q.pop();
cout<<node<<" ";

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;

using Graph = unordered_map<string, vector<pair<string, int>>>;

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);

return visited.size() == adjList.size();


}

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);

cout<<"Flight Network(Adjacency List):\n";


g.displayGraph();

cout<< "\nChecking connectivity....\n";


if(g.isConnected()){
cout<<"the Flight Graph is connected.\n";
}else{
cout<<"the flight graph is not connected.\n";
}

return 0;
}

OPTIMAL BINARY TREE


#include <iostream>
#include <vector>
#include <limits>
using namespace std;
float optimalBST(const vector<int>& keys, const vector<float>& p, int n, vector<vector<int>>&
root) {
vector<vector<float>> cost(n + 2, vector<float>(n + 1, 0));
vector<vector<float>> sum(n + 2, vector<float>(n + 1, 0));

for (int i = 1; i <= n + 1; i++) {


cost[i][i - 1] = 0;
}

for (int i = 1; i <= n; i++) {


sum[i][i] = p[i - 1];
for (int j = i + 1; j <= n; j++) {
sum[i][j] = sum[i][j - 1] + p[j - 1];
}
}

for (int length = 1; length <= n; length++) {


for (int i = 1; i <= n - length + 1; i++) {
int j = i + length - 1;
cost[i][j] = numeric_limits<float>::max();

for (int r = i; r <= j; r++) {


float c = cost[i][r - 1] + cost[r + 1][j];
if (c < cost[i][j]) {
cost[i][j] = c;
root[i][j] = r;
}
}
cost[i][j] += sum[i][j];
}
}

return cost[1][n];
}
int main() {
int n;
cout << "Enter number of keys: ";
cin >> n;

vector<int> keys(n);
vector<float> p(n);

cout << "Enter the keys in sorted order:\n";


for (int i = 0; i < n; i++) {
cout << "Key[" << i + 1 << "]: ";
cin >> keys[i];
}

cout << "Enter the search probabilities for each key:\n";


for (int i = 0; i < n; i++) {
cout << "p[" << keys[i] << "]: ";
cin >> p[i];
}

vector<vector<int>> root(n + 2, vector<int>(n + 1, 0));


float minCost = optimalBST(keys, p, n, root);

cout << "\nMinimum cost of Optimal BST: " << minCost << endl;
cout << "Root of the Optimal BST is key: " << keys[root[1][n] - 1] << endl;

return 0;
}

HEIGHT BALANCING TREE


#include <iostream>
#include <string>
using namespace std;

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;
}
};

int getHeight(Node* node) {


if (node == nullptr)
return 0;
return node->height;
}

int getBalance(Node* node) {


if (node == nullptr)
return 0;
return getHeight(node->left) - getHeight(node->right);
}

int maxHeight(int a, int b) {


return (a > b) ? a : b;
}

Node* rotateRight(Node* y) {
Node* x = y->left;
Node* t2 = x->right;

x->right = y;
y->left = t2;

y->height = maxHeight(getHeight(y->left), getHeight(y->right)) + 1;


x->height = maxHeight(getHeight(x->left), getHeight(x->right)) + 1;

return x;
}

Node* rotateLeft(Node* x) {
Node* y = x->right;
Node* t2 = y->left;

y->left = x;
x->right = t2;

x->height = maxHeight(getHeight(x->left), getHeight(x->right)) + 1;


y->height = maxHeight(getHeight(y->left), getHeight(y->right)) + 1;

return y;
}

Node* insert(Node* root, string key, string meaning) {


if (root == nullptr)
return new Node(key, meaning);

if (key < root->key)


root->left = insert(root->left, key, meaning);
else if (key > root->key)
root->right = insert(root->right, key, meaning);
else {
cout << "Keyword already exists. Updating meaning.\n";
root->meaning = meaning;
return root;
}

root->height = maxHeight(getHeight(root->left), getHeight(root->right)) + 1;

int balance = getBalance(root);

// 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;
}

Node* getMinNode(Node* node) {


Node* current = node;
while (current && current->left != nullptr)
current = current->left;
return current;
}

Node* deleteNode(Node* root, string key) {


if (root == nullptr)
return root;

if (key < root->key)


root->left = deleteNode(root->left, key);
else if (key > root->key)
root->right = deleteNode(root->right, key);
else {
// Node to be deleted found
if (root->left == nullptr || root->right == nullptr) {
Node* temp;
if (root->left != nullptr)
temp = root->left;
else
temp = root->right;
delete root;
return temp;
} else {
Node* temp = getMinNode(root->right);
root->key = temp->key;
root->meaning = temp->meaning;
root->right = deleteNode(root->right, temp->key);
}
}

root->height = maxHeight(getHeight(root->left), getHeight(root->right)) + 1;

int balance = getBalance(root);

if (balance > 1 && getBalance(root->left) >= 0)


return rotateRight(root);

if (balance > 1 && getBalance(root->left) < 0) {


root->left = rotateLeft(root->left);
return rotateRight(root);
}

if (balance < -1 && getBalance(root->right) <= 0)


return rotateLeft(root);

if (balance < -1 && getBalance(root->right) > 0) {


root->right = rotateRight(root->right);
return rotateLeft(root);
}

return root;
}

void updateMeaning(Node* root, string key, string newMeaning) {


while (root != nullptr) {
if (key == root->key) {
root->meaning = newMeaning;
cout << "Updated successfully.\n";
return;
} else if (key < root->key)
root = root->left;
else
root = root->right;
}
cout << "Keyword not found.\n";
}

void displayInOrder(Node* root) {


if (root == nullptr)
return;
displayInOrder(root->left);
cout << root->key << " : " << root->meaning << endl;
displayInOrder(root->right);
}

void displayReverseOrder(Node* root) {


if (root == nullptr)
return;
displayReverseOrder(root->right);
cout << root->key << " : " << root->meaning << endl;
displayReverseOrder(root->left);
}
int searchKeyword(Node* root, string key) {
int comparisons = 0;
while (root != nullptr) {
comparisons++;
if (key == root->key) {
cout << "Found: " << root->meaning << " (Comparisons: " << comparisons << ")\n";
return comparisons;
} else if (key < root->key)
root = root->left;
else
root = root->right;
}
cout << "Keyword not found.\n";
return comparisons;
}

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";
}

} while (choice != 0);

return 0;
}

HEAPS (STUDENT MARKS)


#include <iostream>
#include <vector>
#include <queue> // For priority_queue
using namespace std;

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;

priority_queue<int, vector<int>, greater<int>> minHeap;

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


maxHeap.push(marks[i]);
minHeap.push(marks[i]);
}

int maxMark = maxHeap.top();


int minMark = minHeap.top();

cout << "Maximum mark = " << maxMark << endl;


cout << "Minimum mark = " << minMark << endl;

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);

try (BufferedWriter writer = new BufferedWriter(new FileWriter(FILE_NAME, true))) {


writer.write(student.toString());
writer.newLine();
System.out.println("Student added successfully.");
} catch (IOException e) {
System.out.println("An error occurred while writing to the file.");
}
}
public static void deleteStudent(Scanner scanner) {
System.out.print("Enter Roll Number to delete: ");
String rollNumber = scanner.nextLine();

File file = new File(FILE_NAME);


File tempFile = new File("temp.txt");
try (BufferedReader reader = new BufferedReader(new FileReader(file));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile))) {
String line;
boolean found = false;
while ((line = reader.readLine()) != null) {
Student student = Student.fromString(line);
if (!student.rollNumber.equals(rollNumber)) {
writer.write(line);
writer.newLine();
} else {
found = true;
}
}

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]);
}
}

You might also like