Majority rule is a decision rule that selects the alternative which has a majority, that is, more than half the votes. Given a sequence of elements π1, π2, . . . , ππ, you would like to check whether it contains an element that appears more than π/2 times. A naive way to do this is the following.
MajorityElement(π1, π2, . . . , ππ):
for π from 1 to π:
currentElement β ππ
count β 0
for π from 1 to π:
if ππ = currentElement:
count β count + 1
if count > π/2:
return ππ
return βno majority elementβ
The running time of this algorithm is quadratic. Your goal is to use the divide-and-conquer technique to design an π(π log π) algorithm.
Task. The goal in this code problem is to check whether an input sequence contains a majority element.
The first line contains an integer π, the next one contains a sequence of π non-negative integers π0, π1, . . . , ππβ1.
1 β€ π β€ 105; 0 β€ ππ β€ 109 for all 0 β€ π < π.
Output 1 if the sequence contains an element that appears strictly more than π/2 times, and 0 otherwise.
- Input:
5
2 3 9 2 2
- Output:
1
2 is the majority element.
def merge_sort(array)
l = array.length
return array if l <= 1
mid = l/2
left = array[0...mid]
right = array[mid...l]
merge(merge_sort(left), merge_sort(right))
end
def merge(left, right)
sorted = []
until left.empty? || right.empty?
if left[0].to_i <= right[0].to_i
sorted << left.shift
else
sorted << right.shift
end
end
sorted + left + right
end
el_size = gets.chomp.to_i
string_arr = gets.chomp.split
if el_size == 1
puts 1
return
end
# merge sorting algorithm
sorted = merge_sort(string_arr)
half = el_size.odd? ? el_size.to_f/2 : el_size/2
mid_el = sorted[el_size/2]
mid_el_count = sorted.count(mid_el)
puts mid_el_count.to_i > half ? 1 : 0