要求将给定的n个整数从大到小排序后输出。
时间: 2024-06-14 20:05:21 浏览: 101
以下是使用堆排序算法将给定的n个整数从大到小排序后输出的示例代码:
```c
#include <stdio.h>
void heapify(int arr[], int n, int i) {
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && arr[left] > arr[largest]) {
largest = left;
}
if (right < n && arr[right] > arr[largest]) {
largest = right;
}
if (largest != i) {
int temp = arr[i];
arr[i] = arr[largest];
arr[largest] = temp;
heapify(arr, n, largest);
}
}
void heapSort(int arr[], int n) {
for (int i = n / 2 - 1; i >= 0; i--) {
heapify(arr, n, i);
}
for (int i = n - 1; i >= 0; i--) {
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
heapify(arr, i, 0);
}
}
int main() {
int n;
scanf("%d", &n);
int arr[n];
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
heapSort(arr, n);
for (int i = 0; i < n; i++) {
if (i == 0) {
printf("%d", arr[i]);
} else {
printf(" %d", arr[i]);
}
}
return 0;
}
```
阅读全文