数据结构:生成N个随机数,找出其中第K大的数并输出
利用vector实现
#include <iostream>
#include<vector>//vector头文件
#include <time.h>
using namespace std;
vector<int> bubbling_sort(vector<int> rd_numbers)//冒泡排序,返回值为vector型,无需传入vector大小
{
for (int i = 0; i < rd_numbers.size(); ++i)//rd_numbers.size()获取vector大小
{
for (int j = i + 1; j < rd_numbers.size(); ++j)
{
if (rd_numbers[i] < rd_numbers[j])
{
int temp = rd_numbers[i];
rd_numbers[i] = rd_numbers[j];
rd_numbers[j] = temp;
}
}
}
return rd_numbers;//返回值为vector型
}
void main()
{
int N, K;
start:
cout << "Please input N and K:" << endl;
cin >> N >> K;//输入N和K的值
if (K > N)
{
cerr << "K must ba smaller than or equal to N. Reinput." << endl;
goto start;
}
cout << "N= " << N << ",K= " << K << endl;
cout << "Generating " << N << " random number ";
vector<int> rd_numbers;//定义rd_numbers
srand(time(0));//设定随机数种子为当前时间,使每次生成的随机数都不同
for (int i = 0; i < N; ++i)
{
rd_numbers.push_back(rand() % 1000);//用rand函数生成随机整数,范围在0~1000
cout << rd_numbers[i] << " ";
}
cout << endl;//换行
rd_numbers = bubbling_sort(rd_numbers);//对N个随机数进行冒泡排序
cout << "After sorting: ";
for (int i = 0; i < N; ++i)
cout << rd_numbers[i] << " ";
cout << endl;
cout << "The number you want is " << rd_numbers[K - 1];
}
数组实现
#include <iostream>
#include <time.h>
using namespace std;
void bubbling_sort(int* rd_numbers, int N)//冒泡排序
{
for (int i = 0; i < N; ++i)
{
for (int j = i + 1; j < N; ++j)
{
if (rd_numbers[i] < rd_numbers[j])
{
int temp = rd_numbers[i];
rd_numbers[i] = rd_numbers[j];
rd_numbers[j] = temp;
}
}
}
}
void main()
{
int N, K;
start:
cout << "Please input N and K:" << endl;
cin >> N >> K;//输入N和K的值
if (K > N)
{
cerr << "K must ba smaller than or equal to N. Reinput." << endl;
goto start;
}
cout << "N= " << N << ",K= " << K << endl;
cout << "Generating " << N << " random number ";
int* rd_numbers = new int[N];//声明一个动态数组(本质是指针)
srand(time(0));//设定随机数种子为当前时间,使每次生成的随机数都不同
for (int i = 0; i < N; ++i)
{
rd_numbers[i] = rand() % 1000;//用rand函数生成随机整数,范围在0~1000
cout << rd_numbers[i] << " ";
}
cout << endl;//换行
bubbling_sort(rd_numbers, N);//对N个随机数进行冒泡排序
cout << "After sorting: ";
for (int i = 0; i < N; ++i)
cout << rd_numbers[i] << " ";
cout << endl;
cout << "The number you want is " << rd_numbers[K - 1];
}
【编程总结】
- 动态数组a的本质是指针
声明方法:
C++:其中N为数组大小
int*a=new int[N];
C语言:利用指针
int**a;
a=(int**)malloc(sizeof(int*)*N);
for (int i = 0; i < r; ++i)
a[i] = (int*)malloc(sizeof(int) * c);
- 用rand 函数生成0~1000的N个随机数
存入数组a中:
for ( i = 0 ; i< N ; ++i)
a[i]=rand () % 1000;
存入vector中:
rd_numbers.push_back(rand() % 1000);
- 用srand函数设定随机数种子为当前时间,使每次生成随机数都不同:
srand ( time (0) );