数据结构与算法分析ch01.1
编写一个程序解决选择问题. 令 k = N / 2, 也就是找第k个最大数.
//Exercise 1.1 :
//Write a program to solve the selection problem. Let k = n/2. that is find the k_th max num in N array.
//Draw a table showing the running time of your program for various values of n.
#include<iostream>
#include<ctime>
#include<fstream>
#include<random>
using namespace std;
int arr[100010];
void BubbleSort(int arr[], int n) {
int i, j;
for (int i = 0; i < n - 1; i ++) {
for (int j = i; j < n - i - 1; j ++) { // sort in increasing order
if (arr[j] > arr[j+1]) {
swap(arr[j], arr[j+1]);
}
}
}
}
int main() {
ifstream in("test.txt");
ofstream out("test.txt");
uniform_int_distribution<unsigned> u(0, 200000);
default_random_engine e;
for (size_t i = 0; i < 100000; ++i) {
out << u(e) << " ";
}
int N, num;
cin >> N;
int k = N / 2;
clock_t start_time;
start_time = clock();
for (int i = 0; i != N; i ++) {
in >> num; // read random unsigned interger from the file
arr[i] = num;
}
BubbleSort(arr, N);
clock_t end_time = clock();
cout << arr[k - 1] << endl;
cout << "It took " << static_cast<float>(end_time - start_time) / CLOCKS_PER_SEC << " seconds" << endl;
return 0;
}