Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,954 questions

51,896 answers

573 users

How to find K most frequent elements in an unsorted array with C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>

#define MAX_NUMBER_SIZE 50 + 1

int CompareDescending(const void* a, const void* b) {
    return (*(int*)b - *(int*)a);
}

void PrintKMostFrequentNumbers(int arr[], int len, int K) {
    int frequency[MAX_NUMBER_SIZE] = { 0 };
    int equivalent_number[MAX_NUMBER_SIZE] = { 0 };

    for (int i = 0; i < len; i++) {
        frequency[arr[i]]++;
    }

    for (int i = 0; i < MAX_NUMBER_SIZE; i++) {
        equivalent_number[frequency[i]] = i;
    }

    qsort(frequency, MAX_NUMBER_SIZE, sizeof(int), CompareDescending);

    for (int i = 0; i < K; i++) {
        printf("%d ", equivalent_number[frequency[i]]);
    }
}

int main()
{
    // up to 50, at this time 
    int arr[] = { 4, 5, 19, 30, 7, 19, 8, 19, 3, 5, 6, 19, 27, 19, 3, 5, 5 }; 
    int len = sizeof(arr) / sizeof(arr[0]);
    int K = 2;

    PrintKMostFrequentNumbers(arr, len, K);

    return 0;
}





/*
run:

19 5

*/

 



answered Apr 28, 2023 by avibootz
edited Apr 28, 2023 by avibootz

Related questions

1 answer 143 views
1 answer 103 views
1 answer 100 views
1 answer 106 views
1 answer 120 views
1 answer 117 views
...