Advertisement
Guest User

Untitled

a guest
Feb 23rd, 2020
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.52 KB | None | 0 0
  1. public class Majority {
  2.     public static void main(String args[]) {
  3.         int[] arr = { 1, 1, 1, 2, 2, 1 ,2,2};
  4.         Integer majority = divideAndCompute(arr, 0, arr.length - 1);
  5.         System.out.println(majority == null ? "no majority" : majority);
  6.     }
  7.  
  8.     public static Integer divideAndCompute(int[] arr, int low, int high) {
  9.         if (low == high)
  10.             return arr[low];
  11.         if (low < high) {
  12.             int mid = (low + high) / 2;
  13.             int halfLengthOfSubArr = (high - low + 1) / 2;
  14.  
  15.             Integer majorityLeft = divideAndCompute(arr, low, mid);
  16.             Integer majorityRight = divideAndCompute(arr, mid + 1, high);
  17.        
  18.             if (majorityLeft != null && majorityRight != null) {
  19.                 if (majorityLeft == majorityRight)
  20.                     return majorityLeft;
  21.                 else {
  22.                     if (count(arr, low, high, majorityLeft) > halfLengthOfSubArr)
  23.                         return majorityLeft;
  24.                     else if (count(arr, low, high, majorityRight) > halfLengthOfSubArr)
  25.                         return majorityRight;
  26.                     return null;
  27.                 }
  28.             } else {
  29.                 // Implies left subArray has majority and right doesn't
  30.                 if (majorityLeft != null) {
  31.                     return count(arr, low, high, majorityLeft) > halfLengthOfSubArr ? majorityLeft : null;
  32.                 } else if (majorityRight != null) {
  33.                     return count(arr, low, high, majorityRight) > halfLengthOfSubArr ? majorityRight : null;
  34.                 }
  35.                 return null;
  36.             }
  37.         }
  38.        
  39.         return null;
  40.     }
  41.  
  42.     public static int count(int[] arr, int low, int high, int target) {
  43.         int count = 0;
  44.  
  45.         for (int i = low; i <= high; i++) {
  46.             if (arr[i] == target)
  47.                 count++;
  48.         }
  49.  
  50.         return count;
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement