# Sorting element in array by frequency using C

## Sorting element in array by frequency in C

Here we will learn about Sorting element in array by frequency in C programming language. To sort an array based on its frequency means we need to sort the given element in descending order of their frequency. We are given an array and we have to sort the array based on their frequency. ## Method :

• First we declare an array.
• Declare two 2d array arr[MAX] and brr[MAX].
• Store 1d array in 0th index of arr array.
• Set arr[] = 0for all indexes upto n.
• Now, count the frequency of elements of the array.
• If element is unique the push it at brr[] array, and its frequency will represent by brr[].
• Now, sort the brr on the basis of frequency.
• Print the brr array on basis of their frequency.

In this method we first count the frequency of each elements, so to know more about the algorithm for finding the frequency of elements of the array. You can check out the page given below,

### Code in C

```#include <stdio.h>
#define MAX 256
int main ()
{
int a[]={1, 2, 1, 1, 2, 3, 3, 3, 3, 0};
int n = sizeof(a)/sizeof(a);
int arr[MAX], brr[MAX];
int k = 0, temp, count;
for (int i = 0; i < n; i++)
{
arr[i] = a[i];
arr[i] = 0;
}
// Unique elements and its frequency are stored in another array
for (int i = 0; i < n; i++)
{
if (arr[i])
continue;
count = 1;
for (int j = i + 1; j < n; j++)
{
if (arr[i] == arr[j])
{
arr[j] = 1;
count++;
}
}
brr[k] = arr[i];
brr[k] = count;
k++;
}
n = k;

//Store the array and its frequency in sorted form
for (int i = 0; i < n - 1; i++)
{
temp = brr[i];
for (int j = i + 1; j < n; j++)
{
if (temp < brr[j])
{
temp = brr[j];
brr[j] = brr[i];
brr[i] = temp;

temp = brr[j];
brr[j] = brr[i];
brr[i] = temp;
}
}
}
for (int i = 0; i < n; i++)
{
while (brr[i] != 0)
{
printf (" %d ", brr[i]);
brr[i]--;
}
}
return 0;
}```

### Output

`3 3 3 3 1 1 1 2 2 0`