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

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
赞同 展开评论 打赏

62
1
0
450
1
0
817
1
0
1487
1
0
391
1
0
997
1
0
4293
1
0
1642
1
0
655
0
0
1651
2
0

## 相关电子书

GPON Class C++ SFP O;T Transce 立即下载
GPON Class C++ SFP OLT Transce 立即下载