C语言代码把数组按照元素个数由多到少排序。 例如数组:[1,2,5,3,2], 排序后,输出[2,2,1,5,3]
时间: 2023-10-16 14:18:25 浏览: 66
以下是使用 C 语言实现将数组按照元素个数由多到少排序的代码:
```c
#include <stdio.h>
#define MAX_SIZE 100
int main() {
int arr[MAX_SIZE], freq[MAX_SIZE];
int n, i, j, temp;
printf("Enter the size of the array: ");
scanf("%d", &n);
printf("Enter the elements of the array:\n");
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
freq[i] = -1;
}
for (i = 0; i < n; i++) {
int count = 1;
for (j = i + 1; j < n; j++) {
if (arr[i] == arr[j]) {
count++;
freq[j] = 0;
}
}
if (freq[i] != 0) {
freq[i] = count;
}
}
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (freq[i] < freq[j]) {
temp = freq[i];
freq[i] = freq[j];
freq[j] = temp;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
printf("The array sorted by frequency of elements (from high to low):\n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}
```
运行程序后,输入数组的大小和元素,程序将输出按照元素个数由多到少排序后的数组。
阅读全文