排序法输出数组中众数C语言
时间: 2023-08-04 22:39:26 浏览: 124
排序算法 C语言
以下是使用快速排序法输出数组中众数的 C 语言代码:
```c
#include <stdio.h>
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = (low - 1);
for (int j = low; j < high; j++) {
if (arr[j] <= pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
void quickSort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
int findMode(int arr[], int n) {
quickSort(arr, 0, n - 1);
int mode = arr[0], count = 1, maxCount = 1;
for (int i = 1; i < n; i++) {
if (arr[i] == arr[i - 1]) {
count++;
} else {
if (count > maxCount) {
maxCount = count;
mode = arr[i - 1];
}
count = 1;
}
}
if (count > maxCount) {
maxCount = count;
mode = arr[n - 1];
}
return mode;
}
int main() {
int arr[] = {1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int mode = findMode(arr, n);
printf("The mode of the array is %d", mode);
return 0;
}
```
这段代码中,使用快速排序算法对数组进行排序,然后遍历数组,找到出现次数最多的数,即为众数。
阅读全文