Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

In các số theo thứ tự giảm dần kèm tần suất xuất hiện

Cho một mảng các phần tử int, nhiệm vụ là sắp xếp các phần tử theo thứ tự giảm dần và tìm số lần xuất hiện của chúng.

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

Thuật toán

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

Ví dụ

#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\n",a[i],to);
      en=i;
    }
  }
  to=en;
  printf("%d occurs: %d\n",a[0],to);
}

Kết quả

Nếu chúng ta chạy chương trình trên thì nó sẽ tạo ra đầu ra sau

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