Wednesday, August 09, 2006

Majority element

/********
A majority element in an array A, of size N is an element that appears more than N/2 times (and hence there is atmost
one such element)

Write a function which takes an array and emits the majority element (if it exists), otherwise prints NONE as follows:

I/P : 3 3 4 2 4 4 2 4 4
O/P : 4

I/P : 3 3 4 2 4 4 2 4
O/P : NONE

Answer:

As we sweep through the sequence, we maintain a pair consisting of a current candidate and a counter. Initially, the current candidate is unknown and the counter is 0. When we move the pointer forward over an element e:
If the counter is 0, we set the current candidate to e and we set the counter to 1.
If the counter is not 0, we increment or decrement the counter according to whether e is the current candidate. When we are done, the current candidate is the majority element, if there is a majority.
If you must confirm that the chosen element is indeed the majority element, you must take one more linear pass through the data to do it.
******/
int find_majority(int *a, int n)
{
int count = 1;
currentIndex = 0;
for (i = 1 ; i lessThan n; i ++)
{
if (a[i] == a[currentIndex])
count++;
else
count--;
if (count == 0)
{
currentIndex = i;
count = 1;
}

}
return a[currentIndex];
}

9 comments:

Anonymous said...

will the above code work for this sequence
3 2 3 5 4

Ghotter said...

Thanks for ur interest in this blog.
there is no majority element in this case...
so it will return some value which we need to search in the array if its count is more than n/2...

Anonymous said...

Great stuff dude...
it took me some time to even understand, how this algo worked..

jackace said...

just curious will this work if there is no majority element and one element has n/2 occurrences that too skewed at the end.

Anonymous said...

above code did not work for the below case
{3,3,3,3,2,4,4,4,2,3,6,4};

Anonymous said...

The basic idea of this algorithm is:

#(majority elem) > #(other elements).

In the algorithm, if there is any difference when walking through the array, we could just cancel them out. Because the majority element (if it exists) will win out finally after this mechanism!

Anonymous said...

Thank you, this really help me....

Anonymous said...

The author is really cool. But some of the commentators are just posting stupid words.

Anonymous said...

I will add this blog to my favorites, it is great.