一.讨论的问题
1.有一数组存放N个数,确定数组位置k的最大者(k左侧数要都比k位置存放数小,k右侧则都要比k的数大); 选择问题(selection problem)
未学数据结构构思解决方案一:
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { //设置N值数量 cout << "请输入随机数个数:"; int N; cin >> N; //设置k值 cout << endl << "请输入k值:"; int k; cin >> k; int init[30000] = {0}; int temp = 0; //产生随机数初始化数组 srand(time(NULL)); for (int i = 0; i < N; i++) { init[i] = rand() % N; } //输出原始数组 for (int i = 0; i < N; i++) { cout << init[i] << " "; } cout << endl; //由小到大排序数组 for (int j = 0; j < N; j++) { for (int i = j + 1; i < N; i++) { if (init[j] > init[i]) { temp = init[i]; init[i] = init[j]; init[j] = temp; } } } //由小到大输出数组 for (int i = 0; i < N; i++) { cout << init[i] << " "; } cout << "所求k位置的最大值:" << init[k] << endl; return 0; }
书中记录解决方案二:(将k值之前的数进行排序 ,k值之后的依次比较)