# 堆排序

#include<iostream>
#include<iomanip>

using namespace std;

void keep_heap(int arr[], int i,int heap_size)
{
int Left = i * 2;
int Right = 2 * i +1 ;
int largest=i;
if (Left < heap_size && arr[Left] > arr[i])
largest = Left;
else
largest = i;
if (Right < heap_size && arr[Right] > arr[largest])
largest = Right;
if (largest != i)
{
int t = arr[i];
arr[i] = arr[largest];
arr[largest] = t;
keep_heap(arr, largest, heap_size);
}

}

void build_heap(int arr[], int heap_size)
{

for (int i = heap_size / 2 - 1; i >= 1; i--)
{
keep_heap(arr, i, heap_size);
}

}

void heap_sort(int arr[], int n)
{
int heap_size = n;
build_heap(arr, heap_size);
for (int i = n-1; i >= 1; i--)
{
int t = arr[1];
arr[1] = arr[i];
arr[i] = t;
heap_size--;
keep_heap(arr, 1, heap_size);
}

}

void main()
{
int arr[] = { 0, 9, 5, 7, 8, 6, 2, 4, 3, 1 };
int length = sizeof(arr) / sizeof(int);
for (int i = 1; i < length; i++)
cout << arr[i] << " ";
cout << endl;

heap_sort(arr, length);
for (int i = 1; i < length; i++)
cout << arr[i] << " ";
cout << endl;
system("pause");
}

08-29 1.1万

10-18 8615

04-21 1609

12-22 2658

05-31 6579

03-25 184

10-17 3450

10-09 2240

07-07 9034

01-24 2925