首页  >  文章  >  后端开发  >  按照降序打印数字及其频率

按照降序打印数字及其频率

WBOY
WBOY转载
2023-09-01 10:29:061175浏览

按照降序打印数字及其频率

给定一个int元素的数组,任务是将元素按降序排列并找出它们的出现次数。

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

算法

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

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);
}

输出

如果我们运行上述程序,它将生成以下输出

7 occurs: 2
6 occurs: 1
5 occurs: 1
4 occurs: 1
3 occurs: 2
2 occurs: 3
1 occurs: 3

以上是按照降序打印数字及其频率的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除