Learn-dsa..in 30 days!



























CC-15 : Find the majority number in an array. Use Moore’s voting algorithm.

Description:

Given input integer array arr of length n, find and return the majority number. Majority number is the element which occurs more than n/2 times. Assume that the input array contains a majority number for sure. Use Moore’s voting algorithm.

Test cases and expected outputs:

Input Parameters Expected outputs
arr={ 0,1,0,0,1,2,0} Majority number is 0
arr={2,2,2,2,2,2,1,1,0,0,0} Majority number is 2
arr={1,2,2} Majority number is 2

Pseudocode:

The java method should accept following input parameters: arr (int array).
Initialize two int variables number and cnt with value 0.
Iterate through arr using a for loop using loop variable idx:
If cnt=0; set number=arr[idx], increment cnt by 1.
If arr[idx]=number, increment cnt by 1.
If arr[idx] !=number, decrement cnt by 1.
At end of for loop, number contains the majority element.

Code:

public int arrayFindMajorityNumber(int[] arr) throws Exception{
	int number=0; int cnt=0;
	for (int idx=0; idx< arr.length; idx++) {
		if (cnt==0) {
			number=arr[idx];
			cnt++;
		}else if (arr[idx]==number) {
			cnt++;
		}else {
			cnt--;
		}
	}
	return number;
}

Click here to download and run code and test cases !