Prime #### Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime #### Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

# Sorting element in array by frequency using C

## Sorting element in array by frequency

Here we will sort an array based on its frequency means the element will be sorted in the decreasing order of their frequency. We are given an array and we have to sort the array based on their frequency.

For Example:

Input:

Enter the Element in Array: 9 6 6 9 3 9

Output:

9 9 9 6 6 3 ## Algorithm

• Declare two arrays
• Initialize the first one.
• Calculate the frequency of each element
• Store it in the frequency array.
• Display the array element and its corresponding frequency.
• Now sort the frequency array
• display the result .

## C Code

`#include <stdio.h>#define maximum 256int main (){  int arr[maximum], array[maximum];  int k = 0, K, x, y;  printf ("Enter the Size:");  scanf ("%d", &K);  printf ("Enter the elements :");  for (int m = 0; m < K; m++)    {      scanf ("%d", &arr[m]);      arr[m] = 0;    }  for (int m = 0; m < K; m++)    {      if (arr[m])	continue;      y = 1;      for (int n = m + 1; n < K; n++)	{	  if (arr[m] == arr[n])	    {	      arr[n] = 1;	      y++;	    }	}      array[k] = arr[m];      array[k] = y;      k++;    }  K = k;  printf (" \nElements Frequency\n");  for (int m = 0; m < K; m++)    {      printf (" %d %d \n", array[m], array[m]);    }  for (int m = 0; m < K - 1; m++)    {      x = array[m];      for (int n = m + 1; n < K; n++)	{	  if (x < array[n])	    {	      x = array[n];	      array[n] = array[m];	      array[m] = x;	      x = array[n];	      array[n] = array[m];	      array[m] = x;	    }	}    }  printf (" Elements Sorted Frequency\n");  for (int m = 0; m < K; m++)    {      printf (" %d %d \n", array[m], array[m]);    }  printf ("\n New array:\n");  for (int m = 0; m < K; m++)    {      while (array[m] != 0)	{	  printf (" %d ", array[m]);	  array[m]--;	}    }  return 0;}`
`Input:Enter the Size:3Enter the elements : 6 9 96 9 9Elements       Frequency6                      1 9                      2 Output:Elements     Sorted Frequency9                     2 6                     1New array:9 9 6`