C# program to find majority number which appears more than 50% in the unsorted array
To find the majority number that appears more than 50% of the time in an unsorted array in C#, you can use the Boyer-Moore Voting Algorithm. Here's an example program that implements this algorithm:
using System;
public class Program {
public static void Main(string[] args) {
int[] numbers = { 3, 2, 3, 4, 3, 5, 3, 3, 3 };
int majorityNumber = FindMajorityNumber(numbers);
if (majorityNumber != -1) {
Console.WriteLine("Majority number: " + majorityNumber);
}
else {
Console.WriteLine("No majority number found.");
}
}
public static int FindMajorityNumber(int[] nums) {
int majorityNumber = 0;
int count = 0;
foreach (int num in nums) {
if (count == 0) {
majorityNumber = num;
count = 1;
}
else if (num == majorityNumber) {
count++;
}
else {
count--;
}
}
// Verify if the majority number is indeed the majority
count = 0;
foreach (int num in nums) {
if (num == majorityNumber) {
count++;
}
}
if (count > nums.Length / 2) {
return majorityNumber;
}
else {
return -1; // No majority number found
}
}
}
In this program, we have an array of integers called numbers. We use the FindMajorityNumber method to find the majority number that appears more than 50% of the time in the array. The method implements the Boyer-Moore Voting Algorithm, which performs a linear scan of the array. It maintains two variables: majorityNumber to track the current majority number candidate and count to keep track of the count of occurrences. Initially, the count is set to 0. For each number in the array, if the count is 0, we set the current number as the majorityNumber candidate and increment the count. If the current number is the same as the majorityNumber, we increment the count; otherwise, we decrement the count. After the linear scan, we verify if the majorityNumber is indeed the majority by counting its occurrences. If the count is greater than half the length of the array, we return the majorityNumber; otherwise, we return -1 to indicate that no majority number was found.
The program outputs the majority number if found, or a message indicating that no majority number was found.
For example, with numbers = { 3, 2, 3, 4, 3, 5, 3, 3, 3 }, the program will output:
Majority number: 3
In this case, the number 3 appears 6 times in the array, which is more than half the length of the array, making it the majority number.