You are given a sequence of element. WAP to find which element of the sequence is in Majority, provided there is such a element.
Java Code :
Refer : http://www.geeksforgeeks.org/archives/4722
Java Code :
public class LinearTimeMajorityAlgorithm {
public static void main(String[] args) {
// find an element which repeats majority times
int[] a = { 1, 2, 3, 4, 2, 1, 3, 2, 4, 1, 2, 2, 3, 2, 2, 2 };
if (a.length == 0)
return;
int count = 1;
int maorityTracker = a[0];
for (int i = 0; i < a.length; i++) {
if (count == 0) {
maorityTracker = a[i];
count = 1;
} else {
if (a[i] == maorityTracker) {
count++;
} else {
count--;
}
}
}
System.out.println("Majority occuring element position is :"
+ maorityTracker);
}
}
Refer : http://www.geeksforgeeks.org/archives/4722
No comments:
Post a Comment