项目介绍
-
从txt文件中读取输入(在本例中为整数)。
-
将其添加到当前堆的最后一个元素。
3.把它筛到正确的位置,做一个最小堆。
-
读取完所有整数后,打印出最小堆数组的前五个元素。
-
之后将数组转换为最大堆并再次打印前5个元素。
不使用类或STL来实现堆。堆使用固定大小的整数数组来实现。
文件输入为任意的整数,本例的数量为100个整数。
代码实现
先声明函数,中间是main,函数的定义我们放在最后。
本项目的核心是对堆结构的了解,如最小堆和最大堆的新元素的插入与排序。
可以看一下我的这篇文章来简单理解:
https://blog.youkuaiyun.com/Jifu_M/article/details/112792801
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
const int MAX = 200;
void MaxHeapAdjust(int array[], int i, int nLength);
void MaxHeapSort(int array[], int length);
int MinHeapAdjust(int array[], int i, int nLength);
void MinHeapSort(int array[], int length);
int main()
{
int Array[MAX];
int index = 0;
string a;// display a prompt for the file name
cout << "Please enter the filename: " << endl;
cin >> a;
ifstream read;//read in the file name
read.open(a.c_str());// try to open the file
if (!read)//if the file fails to open print an error message on the screenand exit
{
cout << "Error! Can't find the file" << endl;
exit(1);
}
while (!read.eof())
{
read >> Array[index];
if (read.eof())
break;
index++;
MinHeapSort(Array, index);//insert the int into the array(to make a min heap)
}
read.close();// close the file
cout << "The first 5 elements in min heap are:" << endl;//print the first 5 elements of the heap
for (int i = 0; i < 5; ++i)
{
cout << Array[i] << endl;
}
cout << "The first 5 elements in max heap are:" << endl;
//Max Heap Sort
MaxHeapSort(Array, index);//to make a max heap
for (int i = 0; i < 5; ++i)//print the first 5 elements of the heap
{
cout << Array[i] << endl;
}
return 0;
}
int MinHeapAdjust(int array[], int i, int nLength)
{
int nChild;
int tool;
int swap = 0;
for (; 2 * i + 1 < nLength; i = nChild)
{
//child's position = 2*father's position+1
nChild = 2 * i + 1;
//get the min child
if (nChild < nLength - 1 && array[nChild + 1] < array[nChild])
++nChild;
if (array[i] > array[nChild])
{
tool = array[i];
array[i] = array[nChild];
array[nChild] = tool;
swap = 1;//swap happen
}
else
//break,swap not happen
break;
}
return swap;
}
//adjust to min heap
void MinHeapSort(int array[], int length)
{
int f;
// length/2-1 is length's father position
for (int i = length / 2 - 1; i >= 0; i = i / 2 - 1) {
f = MinHeapAdjust(array, i, length);
if (f == 0) {
break;
}
}
}
void MaxHeapAdjust(int array[], int i, int nLength)
{
int nChild;
int nTool;
for (; 2 * i + 1 < nLength; i = nChild)
{
//child's position = 2*father's position+1
nChild = 2 * i + 1;
//get the max child
if (nChild<nLength - 1 && array[nChild + 1]>array[nChild])
++nChild;
if (array[i] < array[nChild])
{
nTool = array[i];
array[i] = array[nChild];
array[nChild] = nTool;
}
else
//break
break;
}
}
//Max Heap Sort
void MaxHeapSort(int array[], int length)
{
//length/2-1 is the last position that not leaf
for (int i = length / 2 - 1; i >= 0; --i)
MaxHeapAdjust(array, i, length);
}
程序输出如下: