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

Sort elements by frequency of occurrences code in C

Sort elements by frequency of occurrences

 

Here, in this page we will discuss the C program to sort array elements in such a way that the element with the highest number of occurrences comes first. If the number of occurrences are equal then the print the number which appeared first in the array.

Input:  arr[] = {3,3,3,3,3,4,4,1,2,2,2}

Output: arr[] = {3,3,3,3,3,2,2,2,4,4,1}

 

sort elements by frequency of occurrence in C

Algorithm :

  • Take the size of the array and store it in variable n.
  • Declare two array of n size and named them as arr[] and mp[].
  • Take the elements of the array from the user and store them in one array.
  • Calculate the frequency of each element of the array and store it in frequency array.
  • Then sort the frequency array. And print the elements according to their frequency count.

Code based on above algorithm

#include <stdio.h>

int main ()
{
int k = 0, n, temp, count;

printf ("\nEnter the number of elements:\n");
scanf ("%d", &n);

int arr[n][2], mp[n][2];

printf ("\nEnter the array elements :\n");
for (int i = 0; i < n; i++){
scanf ("%d", &arr[i][0]);
arr[i][1] = 0;
}

for (int i = 0; i < n; i++){

if (arr[i][1])
continue;

count = 1;
for (int j = i + 1; j < n; j++){

if (arr[i][0] == arr[j][0]){
arr[j][1] = 1;
count++;
}
}

mp[k][0] = arr[i][0];
mp[k][1] = count;
k++;


}
n = k;

for (int i = 0; i < n - 1; i++){

temp = mp[i][1];
for (int j = i + 1; j < n; j++){

if(temp < mp[j][1]){
temp = mp[j][1];
mp[j][1] = mp[i][1];
mp[i][1] = temp;

temp = mp[j][0];
mp[j][0] = mp[i][0];
mp[i][0] = temp;
}
}

}


printf ("\n Sorted Array based on its frequency:\n");
for (int i = 0; i < n; i++){

while (mp[i][1] != 0){

printf (" %d ", mp[i][0]);
mp[i][1]--;

}

}
return 0;
}
Input :

1 2 3 3 2 4 1 4 4 5

Output :

4 4 4 3 3 2 2 1 1 5