c语言用堆排序实现对数字的从小到大排列
时间: 2023-12-03 14:43:40 浏览: 87
下面是使用堆排序算法对一个整型数组进行从小到大排序的C语言代码:
```c
#include <stdio.h>
// 数组交换函数
void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
// 堆调整函数
void heapify(int arr[], int n, int i)
{
int largest = i;
int l = 2*i + 1;
int r = 2*i + 2;
// 如果左子节点比根节点大,则更新最大值
if (l < n && arr[l] > arr[largest])
largest = l;
// 如果右子节点比最大值大,则更新最大值
if (r < n && arr[r] > arr[largest])
largest = r;
// 如果最大值不是根节点,则交换
if (largest != i)
{
swap(&arr[i], &arr[largest]);
// 递归调整子树
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--)
{
swap(&arr[0], &arr[i]);
heapify(arr, i, 0);
}
}
int main()
{
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);
heapSort(arr, n);
printf("排序后的数组:\n");
for (int i=0; i<n; ++i)
printf("%d ", arr[i]);
printf("\n");
return 0;
}
```
在上述代码中,`heapify`函数实现堆的调整,能够确保当前节点的值大于或等于其子节点的值;`heapSort`函数则使用`heapify`函数构建最大堆,并依次取出根节点并调整堆,最终实现了数组的从小到大排序。
阅读全文
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.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://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)