Program - 6
Aim: Object of the assignment is to implement Bully Election Algorithm by message
passing through procedural calls and return values. Program should take as input list
of process numbers participating in election and the process that will start the
election procedure
Code:
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
set<int>queue;
cout<<"Enter count of processes: ";
cin>>n;
cout<<endl<<"Processes are: ";
for(int i = 1 ; i <= n ; i++){
cout<<i<<' ';
}
cout<<endl;
cout<<"Process "<<n<<" was the coordinator"<<endl;
cout<<"Process "<<n<<" failed!"<<endl;
cout<<endl;
cout<<"Enter process that starts the election: ";
int t; cin>>t;
cout<<"\nProcess "<<t<<" starts the election"<<endl;
queue.insert(t);
int last_call;
cout<<endl;
while(!queue.empty() && t != n){
cout<<"Process "<<t<<" sends election message to processes: ";
for(int i = t+1 ; i <= n ; i++ ){
queue.insert(i);
cout<<i<<' ';
}
cout<<endl;
queue.erase(t);
last_call = t;
t = *queue.begin();
}
cout<<endl;
cout<<"Process "<<*queue.begin()<<" doesn't respond"<<endl;
cout<<"Process "<<last_call<<" declares itself as the winner"<<endl;
cout<<"Process "<<last_call<<" is the new coordinator"<<endl;
}
Output: