Sorting Approach
Sort the array and the majority element will be the middle element (n/2-th element).
Syntax:
arr.sort((a, b) => a - b);
return arr[majorityIndex];
Example: Below is the implementation of the above approach
Javascript
function findMajority(arr) { arr.sort((a, b) => a - b); const majorityIndex = Math.floor(arr.length / 2); return arr[majorityIndex]; } const arr2 = [2, 2, 3, 4, 2, 2, 5]; console.log(findMajority(arr2)); |
Output
2
JavaScript Program for Finding the Majority Element of an Array
Finding the majority element in an array is a common problem in computer science and data analysis. The majority element in an array is the element that appears more than n/2 times, where n is the length of the array. In other words, it’s the element that occurs more frequently than any other element in the array.
Examples:
Input: arr=[2, 2, 3, 4, 2, 2, 5]
Output: 2
Explanation: 2 appears more than n/2 times
Input: arr=[2, 3, 3, 3, 2, 2, 3]
Output: 3
Explanation: 3 appears more than n/2 times
Table of Content
- Brute Force Approach:
- Sorting Approach:
- Boyer-Moore Voting Algorithm:
Contact Us