Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find max/min occurrence in integer array

I just finished writing an algorithm that finds values in an input integer array with max/min occurrences. My idea is to sort the array (all the occurrences are now in sequence) and use a <value:occurrences> pair to store for every value the number of occurrences correspondent.

It should be O(nlogn) complexity but I think that there are some constant multipliers. What can I do to improve performance?

#include <stdio.h>
#include <stdlib.h>
#include "e7_8.h"

#define N 20
/*Structure for <value, frequencies_count> pair*/
typedef struct {
    int value;
    int freq;
} VAL_FREQ;


void  get_freq(int *v, int n, int *most_freq, int *less_freq) {

    int v_i, vf_i, current_value, current_freq;

    VAL_FREQ* sp = malloc(n*sizeof(VAL_FREQ));
    if(sp == NULL) exit(EXIT_FAILURE);

    mergesort(v,n);

    vf_i = 0;
    current_value = v[0];
    current_freq = 1;
    for(v_i=1; v_i<n+1; v_i++) {
        if(v[v_i] == current_value) current_freq++;
        else{
            sp[vf_i].value = current_value;
            sp[vf_i++].freq = current_freq;
            current_value = v[v_i];
            current_freq = 1;
        }
    }
    /*Finding max,min frequency*/
    int i, max_freq_val, max_freq, min_freq_val, min_freq;

    max_freq = sp[0].freq;
    max_freq_val = sp[0].value;
    min_freq = sp[0].freq;
    min_freq_val = sp[0].value;
    for(i=1; i<vf_i; i++) {
        if(sp[i].freq > max_freq) {
            max_freq = sp[i].freq;
            max_freq_val = sp[i].value;
        }
        if(sp[i].freq < min_freq) {
            min_freq = sp[i].freq;
            min_freq_val = sp[i].value;
        }
    }

    *most_freq = max_freq_val;
    *less_freq = min_freq_val;

    free(sp);
}
like image 241
Fabio Carello Avatar asked Jun 30 '26 22:06

Fabio Carello


1 Answers

Use a hash-table to implement a key-value map? That should give you O(n) expected time.*


* However, note that it's O(n2) in the worst-case. This only occurs when all entries hash to the same bucket, and you effectively end up searching a linked-list for every iteration! For decent hash-table implementation, the probability of this occurring is very low indeed.
like image 89
Oliver Charlesworth Avatar answered Jul 02 '26 12:07

Oliver Charlesworth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!