Professional Documents
Culture Documents
DSA Assignment 1
DSA Assignment 1
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <ctime>
class Scheduler {
public:
void loadProcessesFromFile(const string& filename);
void executeProcesses();
void printReadyQueue();
void runScheduler();
private:
vector<Process> readyQueue;
int currentTime = 0;
int totalWaitingTime = 0;
int totalTurnaroundTime = 0;
void updateWaitingTime();
};
// Load processes from a file and add them to the ready queue
void Scheduler::loadProcessesFromFile(const string& filename) {
ifstream file(filename);
if (!file.is_open()) {
cerr << "Error: Could not open the file " << filename << endl;
return;
}
Process process;
while (file >> process.name >> process.executionTime) {
process.arrivalTime = currentTime;
readyQueue.push_back(process);
}
file.close();
// Sort the ready queue based on execution time (highest-execution-time-first)
sort(readyQueue.begin(), readyQueue.end(), compareProcesses);
}
// Calculate and display average waiting time and average turnaround time
int numProcesses = readyQueue.size();
double averageWaitingTime = static_cast<double>(totalWaitingTime) / numProcesses;
double averageTurnaroundTime = static_cast<double>(totalTurnaroundTime) / numProcesses;
cout << "Average Waiting Time: " << averageWaitingTime << endl;
cout << "Average Turnaround Time: " << averageTurnaroundTime << endl;
}
int main() {
Scheduler scheduler;
scheduler.runScheduler();
return 0;
}
Question 2:
#include <iostream>
#include <ctime>
class Sorter {
public:
void sort(int* data, int size, bool ascending) {
// This is a generic sorting function that can be overridden if needed.
if (ascending) {
sortAscending(data, size);
}
else {
sortDescending(data, size);
}
}
protected:
void sortAscending(int* data, int size) {
// Default ascending sort
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (data[j] > data[j + 1]) {
swap(data[j], data[j + 1]);
}
}
}
}
int main() {
srand(time(0)); // Seed the random number generator
int size;
cout << "Enter the size of the dataset: ";
cin >> size;
if (data[0] == 0) {
generateRandomData(data, size);
cout << "Generated random data: ";
printData(data, size);
}
bool ascending;
cout << "Enter the order to sort data (1 for ascending, 0 for descending): ";
cin >> ascending;
int choice;
cout << "Choose a sorting algorithm:\n1. Insertion Sort\n2. Bubble Sort\n3. Selection Sort\n";
cin >> choice;
Sorter* sorter;
switch (choice) {
case 1:
sorter = new InsertionSorter();
break;
case 2:
sorter = new BubbleSorter();
break;
case 3:
sorter = new SelectionSorter();
break;
default:
cout << "Invalid choice. Exiting." << endl;
delete[] data;
return 1;
}
clock_t start_time = clock();
sorter->sort(data, size, ascending);
clock_t end_time = clock();
cout << "Execution time: " << execution_time << " milliseconds" << endl;
delete[] data;
delete sorter;
return 0;
}