sandeshMC

Bully Algorithm

Apr 27th, 2015
221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.79 KB | None | 0 0
  1.  
  2. import java.util.Arrays;
  3. import java.util.Scanner;
  4.  
  5. public class BullyAlgorithm {
  6.  
  7.     static Scanner sc = new Scanner(System.in);
  8.     static boolean isCrashed[];
  9.  
  10.     static void holdElection(int elector) {
  11.         System.out.println("Enter the process to start election: ");
  12.         int flag = -1;
  13.         for (int i = elector; i < isCrashed.length; i++) {
  14.             if (!isCrashed[i]) {
  15.                 System.out.println("OK message from process " + i);
  16.                 flag = i;
  17.             }
  18.         }
  19.         if (flag == -1) {
  20.             System.out.println("The new Co Ordinator is process " + elector);
  21.         } else {
  22.             System.out.println("The new Co Ordinator is process " + flag);
  23.         }
  24.     }
  25.  
  26.     public static void main(String args[]) {
  27.  
  28.         int choice;
  29.         System.out.println("Enter the number of processes: ");
  30.         isCrashed = new boolean[sc.nextInt()];
  31.         do {
  32.             System.out.println("***Bully Algorithm***");
  33.             System.out.println("1. Crash Process\n2. Recover Process\n3. Exit");
  34.             choice = sc.nextInt();
  35.             switch (choice) {
  36.                 case 1:
  37.                     System.out.println("Enter the process to crash: ");
  38.                     isCrashed[sc.nextInt()] = true;
  39.                     System.out.println("Enter the process to start election");
  40.                     holdElection(sc.nextInt());
  41.                     break;
  42.                 case 2:
  43.                     System.out.println("Enter the process to recover");
  44.                     int rec = sc.nextInt();
  45.                     System.out.println("The recovered process " + rec + " will start election..");
  46.                     holdElection(rec);
  47.                     break;
  48.             }
  49.  
  50.         } while (choice != 3);
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment