3、冒泡排序BubbleSort()

时间:2022-12-29 22:12:16
//冒泡排序
#include<iostream>
#include<fstream>
#include<cstdlib>
#include<windows.h>
#include<ctime>
using namespace std;
const int MAXSIZE=501;//待排序数据规模,r[0]保留,实际数组是r[1]---r[500]
//冒泡排序BubbleSort()
void BubbleSort(int r[],int n)
{
int exchange=n;
int bound=0;
int temp=0;//交换函数的暂存变量
while(exchange!=0)
{
bound=exchange;
exchange=0;
for(int i=1;i<bound;i++)
if(r[i]>r[i+1])//交换两者顺序
{
temp=r[i+1];
r[i+1]=r[i];
r[i]=temp;
exchange=i;//一趟排序时最后交换的位置
}//在该位置之后都是排序好的
}
}

//从外存data.txt读取数据至内存数组
void read_data(int data[])
{
ifstream infile("data_salary.txt",ios::in);
if(!infile)
{
cerr<<"open data_salary.txt error!"<<endl;
system("pause");
//exit(1);
}
for(int i=1;i<MAXSIZE;i++)
infile>>data[i];
infile.close();
}
//输出内存数组至外存ordered_data_salary.txt文件
void write_data(int data[])
{
ofstream outfile("ordered_data_salary.txt",ios::out);
if(!outfile)
{
cerr<<"open ordered_data_salary.txt error!"<<endl;
system("pause");
//exit(1);
}
outfile<<"共用时:"<<data[0]<<"微秒"<<endl;
for(int i=1;i<MAXSIZE;i++)
outfile<<data[i]<<endl;
outfile.close();
}
//测试时间开始
inline LARGE_INTEGER time_begin()
{
LARGE_INTEGER start_time;
QueryPerformanceCounter(&start_time);//获取时钟计数
return start_time;
}
//测试时间结束
inline LARGE_INTEGER time_end()
{
LARGE_INTEGER end_time;
QueryPerformanceCounter(&end_time);
return end_time;
}
//主函数
int main(void)
{
int data[MAXSIZE];//建立待排序数据数组
read_data(data);//读数据

double time_test;//计算排序测试时间
LARGE_INTEGER Freq;//64位有符号整数值
QueryPerformanceFrequency(&Freq);//获取时钟周期,“1次/秒”,Hz
//测试时间开始
LARGE_INTEGER time1=time_begin();

//排序算法开始
int n=MAXSIZE-1;
BubbleSort(data,n);

//测试时间结束
LARGE_INTEGER time2=time_end();
time_test=( (time2.QuadPart - time1.QuadPart)*1000000/Freq.QuadPart );
//此处*1000,以毫秒为单位;*1000 000以微妙为单位
cout<<"冒泡排序法:已经排好顺序,请查看:ordered_data_salary.txt文件!"<<endl;
cout<<"排序时间:"<<time_test<<" 微秒"<<endl;
data[0]=time_test;//data[0]处存放排序时间
write_data(data);//写数据
system("pause");
return 0;
}