Home > Backend Development > C++ > Print numbers and their frequencies in descending order

Print numbers and their frequencies in descending order

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2023-09-01 10:29:06
forward
1236 people have browsed it

Print numbers and their frequencies in descending order

Given an array of int elements, the task is to sort the elements in descending order and find their number of occurrences. The Chinese translation of

Input : arr[]={1,1,1,2,2,2,3,3,4,5,6,7,7}
Output : 7 occurs: 2
   6 occurs: 1
   5 occurs: 1
   4 occurs: 1
   3 occurs: 2
   2 occurs: 3
   1 occurs: 3
Copy after login

Algorithm

START
Step 1 -> input array with elements in sorting order
Step 2 -> calculate size of an array by sizeof(a)/sizeof(a[0]
Step 3 -> store size in a variable say en
Step 4 -> Loop For i=siz-1 and i>0 and i==
   IF a[i]!=a[i-1]
      Set to=en-1
      Print a[i] and to
      Set en=i
   End
Step 5 -> print a[0] and to
STOP
Copy after login

Example

is:

Example

#include<stdio.h>
int main() {
   int a[]={1,1,1,2,2,2,3,3,4,5,6,7,7};
   int siz,i,en,st,to;
   siz=sizeof(a)/sizeof(a[0]);
   en=siz;
   for(i=siz-1;i>0;i--) {
      if(a[i]!=a[i-1]) {
         to=en-i;
         printf("%d occurs: %d</p><p>",a[i],to);
         en=i;
      }
   }
   to=en;
   printf("%d occurs: %d</p><p>",a[0],to);
}
Copy after login

Output

If we run the above program, it will Produces the following output

7 occurs: 2
6 occurs: 1
5 occurs: 1
4 occurs: 1
3 occurs: 2
2 occurs: 3
1 occurs: 3
Copy after login

The above is the detailed content of Print numbers and their frequencies in descending order. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template