Please login

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

Sorting element in array by frequency using C

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 256
int main ()
{
int arr[maximum][9], array[maximum][9];
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][0]);
arr[m][1] = 0;
}
for (int m = 0; m < K; m++)
{
if (arr[m][1])
continue;
y = 1;
for (int n = m + 1; n < K; n++)
{
if (arr[m][0] == arr[n][0])
{
arr[n][1] = 1;
y++;
}
}
array[k][0] = arr[m][0];
array[k][1] = y;
k++;
}
K = k;
printf (" \nElements Frequency\n");
for (int m = 0; m < K; m++)
{
printf (" %d %d \n", array[m][0], array[m][1]);
}
for (int m = 0; m < K - 1; m++)
{
x = array[m][1];
for (int n = m + 1; n < K; n++)
{
if (x < array[n][1])
{
x = array[n][1];
array[n][1] = array[m][1];
array[m][1] = x;

x = array[n][0];
array[n][0] = array[m][0];
array[m][0] = x;
}
}
}
printf (" Elements Sorted Frequency\n");
for (int m = 0; m < K; m++)
{
printf (" %d %d \n", array[m][0], array[m][1]);
}
printf ("\n New array:\n");
for (int m = 0; m < K; m++)
{
while (array[m][1] != 0)
{
printf (" %d ", array[m][0]);
array[m][1]--;
}
}
return 0;
}
Input:

Enter the Size:3
Enter the elements : 6 9 9
6 9 9

Elements       Frequency
6                      1
9                      2

Output:
Elements     Sorted Frequency
9                     2
6                     1

New array:
9 9 6