The runtime of the described algorithm is O(n^2)
. The outer loop is executed n/2
times, thus the inner counter j
is resetted n/2
times, and thus the inner loop is executed total of O(n^2)
times.
I am not sure I am following the logic behind your idea, but here are two approaches how I'd implement it [in high level pseudo-code]:
(1) create a histogram out of the data:
- create a
Map<Integer,Integer>
[the key is the element and the value is the number of occurances]
- iterate the array, and for each element count how many times it appears
- iterate the histogram and find if there is a unique maxima.
- If there is - return true, else return false.
This approach is average of O(n)
if you use a HashMap
as the map.
(2) sort and find max occurances:
- Sort the array - as the result, all equal elements are adjacent to each other. You can use
Arrays.sort(array)
for sorting.
- Count how many times each element appears [similar to the histogram idea], and find if there is a unique maxima. You don't actually need to maintain the data for all elements, it's enough to maintain for the top 2, and at the end to see if they are identical.
This solution is O(nlogn)
average + worst case [actually, depending on the sort - merge sort gives you O(nlogn)
worst case, while quick-sort gives you O(n^2)
worst case, and both are O(nlogn)
on average case].
EDIT:
I misunderstood the problem at hand, I thought you are looking if there is a unique maxima. These 2 solutions still fits for the problem, you just need to modify the last step of each [to check if the most occuring element appears more then half of the times, which is again fairly easy and doable in O(n)
].
Also, there is another solution: Use selection algorithm to find the median, and after finding it, check if it is a majority element, and return if it is. Since selection algorithm is divide-and-conquer based solution, I think it fits your needs.