// algorithms.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "iostream"
using std::cout;
using std::endl;
int heapSize;
void maxHeapIFY(int *,int);
void buildHeap(int *,int length);
void swap(int &, int &);
void heapSotr(int *);
int main()
{
int a[10] = { 121, 22, 13, 34, 53, 62, 71, 48, 59, 104};
heapSotr(a);
for (size_t i = 0; i < 10;i++)
{
cout << a[i] << " ";
}
return 0;
}
void buildHeap(int *a,int length){
heapSize = length - 1;
for (int i = length>>1; i >= 0; i--)
{
maxHeapIFY(a, i);
}
}
void maxHeapIFY(int *a,int i){
int l = (i << 1) + 1;
int r = (i << 1) + 2;
int largest;
if (l <= heapSize && a[i] < a[l])
{
largest = l;
}
else
{
largest = i;
}
if (r <= heapSize && a[largest] < a[r])
{
largest = r;
}
while (largest!=i)
{
swap(a[largest], a[i]);
i = largest;
int l = (i << 1) + 1;
int r = (i << 1) + 2;
if (l <= heapSize && a[i] < a[l])
{
largest = l;
}
else
{
largest = i;
}
if (r <= heapSize && a[largest] < a[r])
{
largest = r;
}
}
}
void swap(int &i, int &j){
int temp = i;
i = j;
j = temp;
}
void heapSotr(int *a)
{
buildHeap(a, 10);
for (int i = 9; i >= 1;i--)
{
swap(a[i], a[0]);
heapSize = heapSize - 1;
maxHeapIFY(a, 0);
}
}
c++实现简单的建堆、维护堆和堆排序
最新推荐文章于 2024-04-21 12:08:44 发布