开发者社区> 问答> 正文

使用C++随机函数Rand()生成n个数,采用冒泡排序法.选择排序法这两种方法对n个数进行排序

设置种子 每次运行程序 随机出不一样的数字

展开
收起
知与谁同 2018-07-20 16:03:51 4094 0
1 条回答
写回答
取消 提交回答
  • #include <iostream>
    #include <string>
    #include <ctime>
    using namespace std;void Maopao_sort(int array[] ,int n)
    {//冒泡排序
    int tmp;
    for(int i = 0; i < n-1; i++)
    {
    for(int j = 0; j < n - i-1; j++)
    {
    if(array[j] < array[j+1])
    {
    tmp = array[j+1];
    array[j+1] =array[j];
    array[j] = tmp;
    }
    }
    }
    }void Select_sort(int array[],int n)
    {//选择排序
    int small;//临时变量寄存器
    for(int i=0;i<n-1;i++)
    {
    small = i;
    for(int j=i+1;j<n;j++)
    {
    if(array[small] > array[j])
    {
    small = j;
    }
    }
    if(small!=i)
    {
    int t = array[small];
    array[small]=array[i];
    array[i]=t;
    }
    }
    }void main()
    {
    int num_ary[10];
    cout << "原数组顺序:" << endl;
    srand((unsigned int) time(0));
    for(int i = 0 ; i < sizeof(num_ary)/4 ;i++)
    { num_ary[i] = rand()%50;//随机50之间的数字来 初始化数组num_ary
    cout << num_ary[i] << endl;
    }
    Select_sort(num_ary ,sizeof(num_ary)/4);//选择排序从小到大 cout << "选择排序从小到大:" << endl;
    for(int i = 0 ; i < sizeof(num_ary)/4 ;i++)
    {
    cout << num_ary[i] << " ,";
    } cout << endl; Maopao_sort(num_ary ,sizeof(num_ary)/4);//冒泡排序从大到小
    cout << "冒泡排序从大到小:" << endl;
    for(int i = 0 ; i < sizeof(num_ary)/4 ;i++)
    {
    cout << num_ary[i] << " ,";
    }
    }
    2019-07-17 22:50:16
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
使用C++11开发PHP7扩展 立即下载
GPON Class C++ SFP O;T Transce 立即下载
GPON Class C++ SFP OLT Transce 立即下载