#include <iostream>
#include <ctime>
using namespace std;
void print(int arr[],int n)
{
if (arr == NULL || n < 1)
{
return;
}
for (int i = 0; i < n; i++)
{
cout << *(arr + i) << " ";
}
cout << endl;
}
void swap(int arr[],int i,int j)
{
if (arr == NULL)
{
return;
}
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
void heapinsert(int arr[],int index)
{
while (arr[index] > arr[(index - 1) / 2])
{
swap(arr,index,(index-1)/2);
index = (index - 1) / 2;
}
}
void heapify(int arr[],int index,int heapsize)
{
int left = index * 2 + 1;
while (left<heapsize)
{
//选出两个孩子中较大的那一个
int largest = left + 1 < heapsize&&arr[left + 1] > arr[left] ? left+1 : left;
//选出父节点和较大孩子中较大的
largest = arr[index] > arr[largest] ? index : largest;
if (index == largest)
{
break;
}
swap(arr,index,largest);
index = largest;
left = index * 2 + 1;
}
}
void heapsort(int arr[], int n)
{
if (arr == NULL)
{
return;
}
for (int i = 0; i < n; i++)
{
heapinsert(arr,i);
}
int heapsize = n;
swap(arr,0,--heapsize);
while (heapsize>0)
{
//调好大根堆
heapify(arr,0,heapsize);
//把堆中最大的和最后一个进行交换
swap(arr, 0, --heapsize);
}
}
int main()
{
int arr[10] = {0};
srand((unsigned int)time(NULL));
int n = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i < n; i++)
{
*(arr + i) = rand() % 10 + 1;
}
print(arr,n);
cout << "================" << endl;
heapsort(arr,n);
print(arr, n);
system("pause");
return 0;
}