2
Not to delay too much I go straight to the point, I am trying to make a program for an exercise that possessed the following instruction:
Build a function
int ordenaFreq(int v[], int n)
efficient, that is, the running time worst case must be O(n log n), able to sort a vector of elements v of size n by frequency of appearance of each element.For example, given a vector V = [2, 5, 2, 6, 1, 9999999, 5, 8, 8], its function must return a vector W such that W = [8, 8, 8, 2, 2, 5, 5, 6, 1, 9999999].
I have to use this function in my program but I can’t think of how to solve this problem I’ve used Insertion Sort to organize the vector, but after that I don’t know how to develop this function, mainly taking into account the complexity that has to be used in the function. I currently have the following code made:
#include<stdio.h>
const int max=100;
//Function Prototyping
int InsetionSort(int[],int);
int ordenaFreq(int[],int);
int saida(int);
//Main Function
int main(void)
{
int escolha=10;
do
{
int v[max];
int end;
printf("Entre com o tamanho do arranjo:\n");
scanf("%d",&end);
printf("Entre com os elementos do arranjo:\n");
printf("Numeros com virgula use ponto para separar a parte decimal!\n");
for(int i=0; i<end; i++)
scanf("%d",&v[i]);
InsetionSort(v,end);
printf("Ordenado fica:\n");
printf("[");
for(int i=0; i<end; i++)
printf("%d ",v[i]);
printf("]\n");
}
while(saida(escolha)!=0);
return 0;
}
//Auxiliary Functions
int InsetionSort(int v[],int end)
{
int first,before;
int aux;
for(first=1; first<end; first++)
{
aux=v[first];
for(before=first-1;before>=0 && v[before]<aux;before--)
v[before+1]=v[before];
v[before+1]=aux;
}
}
int ordenaFreq(int v[], int end)
{
int saida(int escolha)
{
printf("Deseja encerrar o programa?\n");
printf("Digite 0 para fechar ou qualquer outro numero para continuar.\n");
scanf("%d",&escolha);
if(escolha==0)
return 0;
else return 10;
}
If possible I would also ask you to help me understand the complexity, if it is not too much bother because it is quite recent for me this part so I do not understand very well how it works right.
I would make use of the data structure
heap
, at this point I can not do this solution, but tomorrow I will post my answer. Complexity can be as for exampleN + N.log(N)
? My idea was to go all the way through the vectorO(N)
and after knowing how many times it occurs to insert into aheap
O(N log(N))
– Fábio Morais
Yes, n added or subtracted has not much problem, the teacher despises them in calculating the complexity of the program, I think I understand more or less the idea you had, how we are still learning such content really is complex to see these paths especially when you have this complexity limit involved.
– Vinícius
Can I do this implementation that I said? As N + Nlog(N) stands Nlog(N), because it is despised. If you want me to do this implementation say something.
– Fábio Morais
Yes, please do I’d like to see what the code you’re thinking would look like.
– Vinícius