#pragma warning(disable:4996)
#include<iostream>
using namespace std;
//堆调整
void HeapAdjust(int* a, int i,int size)
{
int max = i;
int left = 2 * i;
int right = 2 * i + 1;
if (i <= size / 2)
{
if (left <= size&&a[left] > a[max])
{
max = left;
}
if (right <= size&&a[right] > a[max])
{
max = right;
}
if (max != i)
{
int temp = a[max];
a[max] = a[i];
a[i] = temp;
HeapAdjust(a, max, size);
}
}
}
//建堆
void buildHeap(int* a,int size)
{
for (int i = size / 2; i >= 1; i--)
{
HeapAdjust(a, i, size);
}
}
//堆排序
void HeapSort(int *a,int size)
{
int i;
buildHeap(a, size);
for (i = size; i >=1; i--)
{
int temp = a[i];
a[i] = a[1];
a[1] = temp;
HeapAdjust(a, 1, i-1);
}
}
int main()
{
int a[10] = {11,0,1,4,2,3,111,8,23,45};
HeapSort(a, 9);
for (int i = 1; i <=9; i++)
{
cout << a[i] << " ";
}
cout << endl;
return 0;
}
#include<iostream>
using namespace std;
//堆调整
void HeapAdjust(int* a, int i,int size)
{
int max = i;
int left = 2 * i;
int right = 2 * i + 1;
if (i <= size / 2)
{
if (left <= size&&a[left] > a[max])
{
max = left;
}
if (right <= size&&a[right] > a[max])
{
max = right;
}
if (max != i)
{
int temp = a[max];
a[max] = a[i];
a[i] = temp;
HeapAdjust(a, max, size);
}
}
}
//建堆
void buildHeap(int* a,int size)
{
for (int i = size / 2; i >= 1; i--)
{
HeapAdjust(a, i, size);
}
}
//堆排序
void HeapSort(int *a,int size)
{
int i;
buildHeap(a, size);
for (i = size; i >=1; i--)
{
int temp = a[i];
a[i] = a[1];
a[1] = temp;
HeapAdjust(a, 1, i-1);
}
}
int main()
{
int a[10] = {11,0,1,4,2,3,111,8,23,45};
HeapSort(a, 9);
for (int i = 1; i <=9; i++)
{
cout << a[i] << " ";
}
cout << endl;
return 0;
}