#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
using namespace std;
void BubbleSort(int *a,int n) //冒泡排序
{
for(int i = 0;i < n-1;i++)
{
for(int j = 0;j < n-1;j++)
{
if(a[j] > a[j + 1])
{
int tmp = a[j];
a[j] = a[j+1];
a[j+1] = tmp;
}
}
}
}
void SelectSort(int *a,int n) //选择排序
{
for(int i = 0; i < n; i++)
{
for(int j = i; j < n; j++)
{
if(a[j] < a[i])
{
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
}
}
int Random(int m,int n) //指定范围内随机数
{
int pos,dis;
if(m == n) //m=n则表示范围内只有一个数字
{
return m;
}
else if(m > n) //m>n则说明取[m,n]区间内数字
{
pos = n;
dis = m - n + 1;
return rand() % dis + pos;
}
else //m>n则说明取[n,m]区间内数字
{
pos = m;
dis = n - m + 1;
return rand() % dis + pos;
}
}
int main()
{
int buffer[100000]; //排序数组
int i = 0;
int num = 0;
/*
//产生随机数
srand((int)time(NULL)); //根据时间产生相应种子值
ofstream filerand("G:\\need_sort.txt");
int m = 1; //上限
int n = 1000; //下限
for(i=0 ; i < 50000; i++)
{
filerand << Random(m,n) <<" ";
if(!((i + 1) % 10)) //数据量逢十换行
filerand << endl;
}
filerand.close();
*/
ifstream filein("G:\\need_sort.txt");//读文件
if(!filein.is_open()) //打开失败处理
{
cout<<"Error opening file";
return -1;
}
while(!filein.eof()) //循环读入数组
{
filein >> buffer[i++];
num++;
}
filein.close(); //关闭文件
//PS:测试只需要把调用算法注释去掉
// BubbleSort(buffer,num); //冒泡排序
// SelectSort(buffer,num); //选择排序
ofstream fileout("G:\\sorted.txt"); //写文件
if(!fileout.is_open()) //打开失败处理
{
cout<<"Error opening file";
return -1;
}
for(i = 0;i < num;i++) //循环写入文件
{
fileout << buffer[i]<<" ";
if(!((i+1) % 10)) //数据量逢十换行
fileout << endl;
}
fileout.close(); //关闭文件
return 0;
}
排序算法 数据量 | BubbleSort | SelectSort |
5000 | 1.31s | 1.27s |
50000 | 45.412s | 16.041s |