#include <iostream>
#include <fstream>
#include <time.h>
using namespace std;
#define TXT_NUM_COUNT 1000001
int ImportToArray(const char *filename,int *array) //将filename内的纯数字文本导入数组array;
{
int count=0;
ifstream fin;
fin.open(filename);
if( fin.fail() )
{
cout<<"file read fail!"<<endl;
return -1;
}
while( fin.eof() ==false )
fin>>array[count++];
fin.close();
return count;
}
int ExportWithArray(const char *filename,int *array,int count)
{
ofstream fout;
fout.open(filename);
if(fout.fail())
{
cout<<"file wirte fail"<<endl;
return -1;
}
for(int i=0;i<count;i++)
fout<<array[i]<<endl;
fout.close();
}
void QuickSort(int *array,int size)
{
if(size>1)
{
int i=0;
int j=size;
int p=array[i];
do
{
do i++;
while(array[i]<p);
do j--;
while(array[j]>p);
if(i<j) swap(array[i],array[j]);
}while(i<j);
swap(array[0],array[j]);
QuickSort(array,j);
QuickSort(array+j+1,size-j-1);
}
}
void swap(int &a,int &b)
{
int t=a;
a=b;
b=t;
}
void main()
{
time_t t_start,t_end;
int *array=new int[TXT_NUM_COUNT]; //已经测得有1000001个数据,其中多测一个为空行
int count=ImportToArray("largeW.txt",array);
//printf("%d %d",count,array[count-1]);
cout<<count<<" "<<array[count-1]<<endl;
t_start=time(NULL);
// bubbleSort(array,count-1);
// mergeSort(array,count-1);
QuickSort(array,count-1);
t_end=time(NULL);
// cout<<"冒泡用时(S):"<<difftime(t_end,t_start)<<endl;
// cout<<"归并用时(S):"<<difftime(t_end,t_start)<<endl;
cout<<"快速用时(S):"<<difftime(t_end,t_start)<<endl;
// ExportWithArray("largeW_bubble.txt",array,count-1);
// ExportWithArray("largeW_merge.txt",array,count-1);
ExportWithArray("largeW_quick.txt",array,count-1);
delete [] array;
测试用
//int a[]={8,2,1,4,6,8,9,0,1,1};
bubbleSort(a,10);
//QuickSort(a,10);
//for(int i=0;i<10;i++)
// cout<<a[i]<<" ";
}
(2)经典算法面试题(至少选择其中1道题并作答,有自己的思考与理解)
怎样从顶部开始逐层打印二叉树结点数据?请编程。
答:当做一个图来使用广度优先遍历即可.