Exp 7
Exp 7
AIM:
Write a program to implement Ring Election Algorithm.
CODE:
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter No of Processes : ";
cin >> n;
cout << "Order of Processes in Ring : ";
vector<int> a(n), b(n);
for (int i = 0; i < n; i++)
cin >> a[i] >> b[i];
cout << "\n";
cout << "Process " << n << " is the Coordinator\n";
cout << "Process " << n << " Fails\n";
vector<int> active_list;
int temp;
for (int i = 0; i < n; i++) {
if (b[i] == n) {
active_list.push_back(a[i]);
temp = i;
cout << "Process " << a[i] << " Starts Election\n";
cout << "Process " << a[i] << " added to Active List\n";
break;
}
}
int count = 0;
int f = 0;
while (count < n) {
temp++;
if (temp >= n)
temp = 0;
for (int i = 0; i < active_list.size(); i++) {
if (b[temp] == active_list[i]) {
int max = 0;
for (int i = 0; i < active_list.size(); i++) {
if (max < active_list[i])
max = active_list[i];
}
cout << "Process " << max << " is new Coordinator\n";
f = 1;
}
if (f == 1)
break;
}
if (f == 1)
break;
active_list.push_back(b[temp]);
cout << "Process " << b[temp] << " added to Active List\n";
count++;
}
return 0;
}
OUTPUT: