堆排序--C语言实现

来源:互联网 发布:网络借贷平台排行榜 编辑:程序博客网 时间:2024/05/17 02:58
#include<stdio.h>//arr是待调整的堆数组,length是数组的长度void HeapAdjust(int arr[], const int length) {for (int j = length - 1; j > 0; --j) {int parent = j / 2;int child = j;//得到子结点中较大的结点if (j < length - 1 && arr[j] < arr[j + 1]) {     ++child;}//如果较大的子结点大于父结点那么把较大的子结点往上移动,替换它的父结点if (arr[child] > arr[parent]) {int tmp = arr[child];arr[child] = arr[parent];arr[parent] = tmp;}}}void HeapSort(int arr[], const int length) {for (int j = length; j > 0; --j) {//不断缩小调整heap的范围,每一次调整完毕保证第一个元素是当前序列的最大值HeapAdjust(arr, j);//把第一个元素和当前的最后一个元素交换,//保证当前的最后一个位置的元素都是在现在的这个序列之中最大的int tmp = arr[0];arr[0] = arr[j - 1];arr[j - 1] = tmp;}}int main(){int arr[] = {5, 6, 1, 4, 9, 2, 7, 3, 8, 0 };int n = sizeof(arr) / sizeof(arr[0]);HeapSort(arr, n);for (int j = 0; j < n; ++j) {printf("%d ", arr[j]);}printf("\n");return 0;}

0 0
原创粉丝点击