C++ 数据结构算法 学习笔记(16) - 堆排序练习 (终)
题目
请写出一个程序能快速的查找无序集合中前N大的记录
完整代码
#include <iostream>
#include <string>
using namespace std;
#define DataType int
#define MAX_SIZE 128
typedef struct sort_heap
{
DataType* arr;
int size;
int capacity;
}Heap;
bool init_heap(Heap& heap, DataType* data, int size);
static bool build_heap(Heap& heap);
static bool adjust_down(Heap& heap, int value);
bool Is_empty(Heap& heap);
bool is_full(Heap& heap);
void destroy_heap(Heap& heap);
void heapSort(Heap& heap, int i);
bool pop_heap(Heap& heap, DataType* element);
bool init_heap(Heap& heap, DataType* data, int size)
{
if (!data || size < 0) return false;
int capacity = (MAX_SIZE > size) ? MAX_SIZE : size;
heap.capacity = capacity;
heap.arr = new DataType[capacity];
if (!heap.arr) return false;
memcpy(heap.arr, data, size * sizeof(DataType));
heap.size = size;
build_heap(heap);
return true;
}
bool build_heap(Heap& heap)
{
for (int i = (heap.size - 2)/2; i >= 0; i--)
{
adjust_down(heap, i);
}
return true;
}
bool adjust_down(Heap& heap, int value)
{
if (value<0 || value> heap.size) return false;
DataType tmp = heap.arr[value];
int father, child;
for (father = value; (father*2)+1 < heap.size; father = child)
{
child = (father * 2) + 1;
if (heap.arr[child + 1] > heap.arr[child] && (child + 1) < heap.size)
{
child++;
}
if (heap.arr[child] > heap.arr[father])
{
heap.arr[father] = heap.arr[child];
heap.arr[child] = tmp;
}
else
{
break;
}
}
return true;
}
bool Is_empty(Heap& heap)
{
if (heap.size == 0) return true;
return false;
}
bool is_full(Heap& heap)
{
if (heap.size == heap.capacity) return true;
return false;
}
void destroy_heap(Heap& heap)
{
if (heap.arr) delete heap.arr;
return;
}
bool pop_heap(Heap& heap, DataType* element)
{
if (!element) return false;
if (Is_empty(heap)) return false;
*element = heap.arr[0];
heap.arr[0] = heap.arr[heap.size];
heap.size--;
if(adjust_down(heap, 0)) return true;
return false;
}
void heapSort(Heap& heap, int index)
{
if (index <= 0||Is_empty(heap) || index>heap.size) return;
int init_size = heap.size -1;
int tmp = 0;
while (tmp < index)
{
int value = heap.arr[0];
heap.arr[0] = heap.arr[heap.size - 1];
heap.arr[heap.size - 1] = value;
heap.size--;
adjust_down(heap,0);
tmp++;
}
for (int i = init_size; i > (init_size - index) ; i--)
{
cout << heap.arr[i] << " ";
}
}
int main()
{
int index = 0;
DataType tmp[] = {1,3,5,7,9,11,50,100,34};
Heap heap;
init_heap(heap, tmp, sizeof(tmp) / sizeof(tmp[0]));
for (int i = 0; i < heap.size; i++)
{
cout << heap.arr[i] << " ";
}
cout << endl;
cout << "After the sprting function" << endl;
cout << "Please enter how many value you want to sort from the heap" << endl;
cin >> index;
heapSort(heap, index);
system("pause");
return 0;
}