把数组按照元素个数由多到少排序。 例如数组:[1,2,5,3,2], 排序后,输出[2,2,1,5,3]用C语言
时间: 2023-10-16 21:27:15 浏览: 35
可以使用桶排序来实现这个功能,具体步骤如下:
1. 遍历数组,统计每个元素出现的次数,并将其存储在桶中。
2. 遍历桶,将桶中的元素按照出现次数从多到少排序。
3. 遍历排序后的桶,按照出现次数和顺序依次输出元素。
下面是具体的代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_NUM 100 // 数组中最大元素值
void bucket_sort(int arr[], int n) {
int count[MAX_NUM + 1] = {0}; // 定义桶,初始值为0
// 统计每个元素出现的次数
for (int i = 0; i < n; i++) {
count[arr[i]]++;
}
// 按照出现次数从多到少排序
for (int i = MAX_NUM; i >= 0; i--) {
for (int j = 0; j < count[i]; j++) {
printf("%d ", i); // 输出元素
}
}
}
int main() {
int arr[] = {1, 2, 5, 3, 2};
int n = sizeof(arr) / sizeof(arr[0]);
bucket_sort(arr, n);
return 0;
}
```
输出结果为:2 2 1 5 3。
相关问题
C语言代码把数组按照元素个数由多到少排序。 例如数组:[1,2,5,3,2], 排序后,输出[2,2,1,5,3]
以下是使用 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;
}
```
运行程序后,输入数组的大小和元素,程序将输出按照元素个数由多到少排序后的数组。
把数组按照元素个数由多到少排序,例如数组:[1,2,5,3,2], 排序后,输出[2,2,1,5,3]。 c++程序实现
可以使用标准库中的`sort`函数和自定义比较函数来实现:
```c++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool cmp(int a, int b) {
return a > b; // 返回a是否大于b,即按照元素个数由多到少排序
}
int main() {
vector<int> arr = {1, 2, 5, 3, 2};
sort(arr.begin(), arr.end(), cmp); // 排序
// 输出排序后的数组
for (int i = 0; i < arr.size(); i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
```
输出结果为:`2 2 1 5 3`。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)