// FileToolsTest.cpp : Defines the entry point for the console application.
//
//#include "heapSort.h"
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
// #include <VECTOR>
using namespace std;
#define ARRAY_SIZE 1000
int heapcount = 0;//记录总共的比较次数
void FixHeap(int L[], int Hsize, int root, int k)
{
//int larger = 0;
if((2 * (root + 1)) > Hsize)//叶子节点
{
L[root] = k;
}
else
{
int larger = 0;
if((2*(root + 1)) == Hsize)//只有左子树
{
larger = 2 * root + 1;
}
else if(L[2 * root + 1] > L[2 * (root + 1)])//有左右子树
{
larger = 2 * root + 1;
}
else
{
larger = 2 * (root + 1);
}
if(k > L[larger])
{
heapcount++;
L[root] = k;
}
else
{
heapcount++;
L[root] = L[larger];
FixHeap(L, Hsize, larger, k);
}
}
return;
}
void BuildHeap(int L[], int n)
{
for(int i = n/2 - 1; i >= 0; i--)// 从第n/2-1个节点开始向上建堆
{
FixHeap(L, n, i, L[i]);
}
return;
}
void HeapSort(int L[], int n )
{
BuildHeap(L, n);
for(int i = n -1; i >= 0; i-- )
{
int temp = L[i];
L[i] = L[0];
FixHeap(L, i , 0, temp);
}
return;
}
// vector<string> vStr;
void HeapSort_Write()
{
//存储每行读入的数据,用于排序算法的调用
int sortArray[15]={0};
string strLine;
char achLine[ARRAY_SIZE];
const char* pchTok;
ifstream in_file("original.txt", ios::in);
ofstream out_file("heapResult.txt");
int precount = 0;//用于和thiscount作差来计算每次排序所需要比较的次数
int num = 0;//用来记录是第几行的排序结果
while(in_file.good())
{
num++;
//每次读一行并且拷贝到achLine中构成一个数组
strLine = "";
getline(in_file, strLine);
cout << "The num" << num << ": " <<strLine << endl;
strLine.copy(achLine, strLine.size(), 0);
achLine[strLine.size()] = (char)'\0';
//每行中的元素以空格为标识断开转换为int类型后存入数组
pchTok = strtok(achLine, " ");//strtok第一个参数第一使用时必须设
int i = 0;
while((pchTok != NULL))
{
sortArray[i] = atoi(pchTok);
//vStr.push_back(sortArray[i]);
i++;
cout << atoi(pchTok) << " ";
pchTok = strtok(NULL, " ");//strtok第一个参数往后的调用则将参数s设置成NULL。每次调用成功则返回被分割出片段的指针。
}
//使用堆排序算法并将结果,第几行的比较结果以及这一行排序所用的比较次数写入到heapResult.txt文件
HeapSort(sortArray, 15);
for(int j = 0; j < 15; j++)
{
//setw的使用方法
out_file << setw(3) << setiosflags(ios::right)<< sortArray[j] ;//数组中的每个数都在一个3字符的宽的空间右对齐输出
//cout << endl << setw(3) << setiosflags(ios::right)<< sortArray[j] ;//数组中的每个数都在一个3字符的宽的空间右对齐输出
}
int thiscount = heapcount;
out_file << "\n第" << setw(4) << num << "行总共比较了" << setw(4) << thiscount - precount << "次" <<"排序结果是:" << " ";
precount = thiscount;
out_file << endl;
cout << endl << endl;
}
out_file.close();
in_file.close();
}
int main()
{
HeapSort_Write();
/*
vector<string>::iterator iterStr;
for (iterStr=vStr.begin();iterStr!=vStr.end();iterStr++)
{
cout << *iterStr << endl;
}*/
return 0;
}
从文件中读取数字并排序
最新推荐文章于 2022-10-18 22:24:52 发布