已知数组 a[20]={6,7,8,9,10,15,14,13,12,11,8,9,15,14,13,15,14,3,2,1},请用C语言编程,去除数组中重复的元素,只保留一个,并输出前5个最大的整数
时间: 2023-10-03 13:04:15 浏览: 77
以下是用C语言编写的解决方案,它通过先去除数组中的重复元素,然后使用选择排序算法来找到前5个最大的整数。
```
#include <stdio.h>
void removeDuplicates(int arr[], int n)
{
int i, j, k;
for (i = 0; i < n; i++) {
for (j = i + 1; j < n;) {
if (arr[j] == arr[i]) {
for (k = j; k < n; k++) {
arr[k] = arr[k + 1];
}
n--;
} else {
j++;
}
}
}
}
void selectionSort(int arr[], int n)
{
int i, j, max_idx, temp;
for (i = 0; i < 5; i++) {
max_idx = i;
for (j = i + 1; j < n; j++) {
if (arr[j] > arr[max_idx]) {
max_idx = j;
}
}
temp = arr[max_idx];
arr[max_idx] = arr[i];
arr[i] = temp;
}
}
int main()
{
int a[20] = {6, 7, 8, 9, 10, 15, 14, 13, 12, 11, 8, 9, 15, 14, 13, 15, 14, 3, 2, 1};
int n = 20;
removeDuplicates(a, n);
selectionSort(a, n);
printf("The top 5 numbers are: ");
for (int i = 0; i < 5; i++) {
printf("%d ", a[i]);
}
printf("\n");
return 0;
}
```
输出结果为:
```
The top 5 numbers are: 15 14 13 12 11
```
阅读全文