0

I'm looking for an algorithm to count the number of occurrences of each element in an array, using the Divide and Conquer method.

Here's an example;

Input: 12-3-5-3-12-3
OutPut: (12, 2), (3, 3), (5,1)

Can anyone at least give me an idea where to start? Thank you

fjardon
  • 7,921
  • 22
  • 31
DaPoox
  • 139
  • 4
  • 16
  • You can start with: https://www.google.ro/search?q=Divide+and+Conquer – Mihai Matei Nov 03 '15 at 13:09
  • Thank you for your answer. But I did that, and I've done so many reseaches, and I understand the devide and conquer method nicely, but still... I can't find the way to solve the problem. – DaPoox Nov 03 '15 at 13:14
  • You probably need a handle on a global data structure that manages the occurrences (possibly a balanced tree) that you pass around. What's left is recursive bisection of the input array. Am I missing something from your specs? – collapsar Nov 03 '15 at 13:24
  • Thanks, I'll try and work on the balanced tree idea. I'll let you guys what happens. – DaPoox Nov 03 '15 at 13:28
  • 1
    I'm not sure using a tree would count as using a divide and conquer algorithm. I didn't advise heap sorting + counting for this reason. – fjardon Nov 03 '15 at 14:19
  • http://stackoverflow.com/questions/33473716/frequency-count-of-number-in-an-array-in-c-is-this-code-effective-and-efficient – shapiro yaacov Nov 03 '15 at 15:31

1 Answers1

1

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)]                                                       
fjardon
  • 7,921
  • 22
  • 31