堆排序算法

// HeapSort.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <stdlib.h>
#include <time.h>

void BuildHeap(int a[], int count, bool minHeap);
void print(int a[], int count);
void swap (int &a, int &b);
void Rand (int a[], int count, int min, int max);

int _tmain(int argc, _TCHAR* argv[])
{
int a[10];
int count = sizeof(a)/sizeof(a[0]);

//產生10個範圍在10~100的隨機數,並保存在名爲a的數組中
Rand (a, 10, 10, 100);
printf ("Initial array\n");
print(a, count);
for (int i = 0; i < count; i++)
{
//建好小根堆後a[0]元素的值永遠是最小的, 反之建立大根堆a[0]永遠最大
//之後把a[0]與最後一個元素交換,再在剩下的元素中重新建堆
BuildHeap(a, count - i, false);
printf ("After build heap for the first %d elements\n", count - i);
print(a, count);
swap (a[0], a[count - i - 1]);
}


getchar();
return 0;
}


//產生count個範圍在min~max的隨機數,並保存在名爲a的數組中
void Rand (int *a, int count, int min, int max)
{
srand(unsigned int(time(0)));
int randValue;
int i = 0;
while (i < count)
{
randValue = rand() %max;
if (randValue > min)
{
a[i] = randValue;
i++;
}
}
}


void swap (int &a, int &b)
{
int temp;

temp = a;
a = b;
b = temp;
}


//minHeap - true:建立小堆, false:建立大堆
void BuildHeap(int a[], int count, bool minHeap)
{
//建立小堆(父節點小於等於子節點)
for (int i = 0; i < count; i++)
{
int child = i;
int parent = (child - 1) / 2;
while (parent >= 0 && child != 0)
{
if (minHeap)
{
//如果子節點都比父節點大了,代表已經找到放要插入值的位置,不再與父節點的父節點比
//因爲父節點的值肯定是小於子節點的值,小堆特性
if (a[child] > a[parent])  
break;
}
else
{
//如果子節點都比父節點小了,代表已經找到放要插入值的位置,不再與父節點的父節點比
//因爲父節點的值肯定是大於或等於子節點的值,大堆特性
if (a[child] < a[parent])
break;
}


//子節點設置爲當前父節點的值
swap (a[parent], a[child]);
child = parent;
parent = (child - 1) / 2;
}
}
}


void print(int a[], int count)
{
printf ("values of array from index 0 to %d are: ", count -1);
for (int i = 0; i < count; i++)
{
printf ("%d ", a[i]);
}
printf ("\n");
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章