各种排序算法比较--2015年7月23日22:33:43v1.0版

#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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值