当前位置: 代码迷 >> 综合 >> 排序算法-堆排序(nlogn)
  详细解决方案

排序算法-堆排序(nlogn)

热度:34   发布时间:2023-12-24 22:55:16.0

堆排序

代码:

#include<iostream>
#include<string>using namespace std;
void MaxHeapFixDown(int a[], int i, int n);
void HeapSort(int a[], int n);int main()
{int buff[7] = { 5, 2, 1, 4, 9, 6, 0 };for (int i = 0; i < 7; i++)cout << buff[i] ;cout << endl;HeapSort(buff, 7);for (int i = 0; i < 7; i++)cout << buff[i];cout << endl;return 0;
}//构造最大堆
void MaxHeapFixDown(int a[], int i, int n)
{int j = 2 * i + 1;int temp = a[i];while (j<n){if (j + 1<n&&a[j]<a[j + 1])++j;if (temp>a[j])break;else{a[i] = a[j];i = j;j = 2 * i + 1;}}a[i] = temp;
}//堆排序
void HeapSort(int a[], int n)
{for (int i = n / 2 - 1; i >= 0; i--)MaxHeapFixDown(a, i, n);for (int i = n - 1; i >= 1; i--){swap(a[i], a[0]);MaxHeapFixDown(a, 0, i);}
}

结果:


  相关解决方案