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.

IntermediateBoyer-MooreCandidateVerification

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
Majority = 2

COMPLETE C PROGRAM

Complete C implementation

dsa-boyer-moore-majority.c
Open in compiler
#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;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Majority = 2
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Cancel different values, then verify that the surviving candidate occurs more than half the time.
  3. 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.