0

So, like the question says I want to arrange the occurrences of these elements in an ascending order of those elements. For example- if I input 7-3 times and 3-2 times, then output should be printed with 3-2 first and then (next line) 7-3. If you see the for loop with the comment to sort through the array, without that for loop the code works fine but doesn't print the elements in an ascending order. Let me know what you think about this and why that for loop isn't working?

#include<stdio.h>
    int x;
    int main()
    {    int a[10000],b[10000],i,j,n,x,c=0,p,q ;
        scanf("%d",&n);
        for(i=0; i<n; i++)
        {
            scanf("%d",&a[i]);
        }
    
      for(i=0; i<n; i++)
        {        c=1;
            if(a[i]!=-1)
            {    for(j=i+1; j<n; j++)
                {
                   if(a[i]==a[j])
                    {     c++;
                       a[j]=-1;
                   }
               }
               b[i]=c;
            }
        }
    for (i = 0; i < n; ++i) \\for loop to sort a[i] elements in ascending order
            {     for (j = i + 1; j < n; ++j)
                {
                    if (a[i] > a[j])
                    {
                        x =  a[i];
                        a[i] = a[j];
                        a[j] = x;
                    }
                }
            }
     for(i=0; i<n; i++)
        {
             if(a[i]!=-1 && b[i]>1)
            {
                printf("%d-%d\n",a[i],b[i]);
    
            }
    
        }
        return 0;
    }
dv24680
  • 63
  • 6
  • Does this answer your question? [how to find complete sorting of elements by frequency?](https://stackoverflow.com/questions/24251349/how-to-find-complete-sorting-of-elements-by-frequency) – Sneftel Sep 02 '20 at 07:51

1 Answers1

0

You can do it either in O(n * lg n) e.g. using sorting or in expected linear time using std::map, I'm not sure if there is something like this in C.

Example impl. w/ sorting:

#include <iostream>
#include <vector>
#include <algorithm>

std::vector<int> v = {3,7,7,7,3,7,7};
std::sort(v.begin(), v.end());
for (int i = 0; i < v.size(); ++i) {
    int number = v[i];
    int count = 1;
    while (v[i + count] == number) ++count;
    i = i + count;
    std::cout << number << " " << count << std::endl;
}   

If you know that range of elements in the array is small enough you can use radix sort and so get it done in linear time.


About your implementation.

You are good with the first loop.

In the second loop, you need to take into account -1 entries. Also you need to swap not only a but b entries as well.

Check for b[i] equals to 1. You can initialize it to 0 before c=1; and drop b[i] > 1 check.

Few more comments not related to correctness. Do not use magic number -1, give it a name, and then use it. Do not declare all variables at the beginning of the function, declare every variable as close as possible to the first use.

Yola
  • 18,496
  • 11
  • 65
  • 106