You can merge sort the array and then output the values with their count in a single pass of the sorted array.
Alternatively, you could also map your input array to an array of pairs: (number, 1)
. Then divide and conquer as in the merge sort, but in the merge phase, you increment the count of the same numbers instead of outputting it multiple times.
Example code in python
#!python
input = [12, 3, 5, 3, 12, 3];
def count_occurrences(input):
""" Divide """
if(len(input) == 0):
return []
if(len(input) == 1):
return [(input[0], 1)]
left = count_occurrences(input[:len(input)/2])
right = count_occurrences(input[len(input)/2:])
""" Conquer """
result = []
i=0
j=0
imax=len(left)
jmax=len(right)
while(i<imax and j<jmax):
if(left[i][0] < right[j][0]):
result.append(left[i])
i = i+1
elif(left[i][0] > right[j][0]):
result.append(right[j])
j = j+1
else:
result.append((left[i][0], left[i][1]+right[j][1]))
i = i+1
j = j+1
while(i<imax):
result.append(left[i])
i = i+1;
while(j<jmax):
result.append(right[j])
j = j+1;
return result
print (count_occurrences(input))
This will print:
$ python how-to-count-occurrences-with-divide-and-conquer-method.py
[(3, 3), (5, 1), (12, 2)]