DATA STRUCTURES PROGRAM • ARRAY TECHNIQUES
Find a Majority Element with Boyer-Moore Voting
Learn how to find a majority element with boyer-moore voting using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
Majority = 2
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
int main(void)
{
int values[] = {2, 2, 1, 1, 1, 2, 2};
int candidate = 0, votes = 0;
for (int index = 0; index < 7; index++) {
if (votes == 0) candidate = values[index];
votes += values[index] == candidate ? 1 : -1;
}
int frequency = 0;
for (int index = 0; index < 7; index++) if (values[index] == candidate) frequency++;
if (frequency > 7 / 2) printf("Majority = %d\n", candidate);
else puts("No majority element.");
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Majority = 2
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Cancel different values, then verify that the surviving candidate occurs more than half the time.
- Display the computed result.
Cancel different values, then verify that the surviving candidate occurs more than half the time.
EFFICIENCY
Time and space complexity
Time complexity
O(n)
Auxiliary space
O(1)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
