算法目的是希望取得一组数中,从大到小排序第k位(这里默认k=N/2)的元素。以下程序通过两个算法实现同样的功能。还有第三种更好的方法等待补充。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 #include <iostream> #include <vector> #include <time.h> using namespace std ;void insertNum (vector <int > & array , int num) { int index = 0 ; for (; index < array .size(); index++) { if (num > array [index]) { for (int i = (int )array .size() - 1 ; i != index; i--) { array [i] = array [i-1 ]; } array [index] = num; } } } double runTime (clock_t start, clock_t finish) { return 1000 * (double )(finish - start)/CLOCKS_PER_SEC; } int main (int argc, const char * argv[]) { clock_t start,finish; double totaltime; cout << "请输入数字的总个数" << endl ; int N; cin >> N; int k = N / 2 ; vector <int > array (k); start = clock(); int index = 0 ; while (index < k) { array [index] = rand(); index++; } for (int i = 0 ; i < array .size() - 1 ; i++) { for (int j = i+1 ; j < array .size(); j++) { if (array [i] < array [j]) { swap(array [i], array [j]); } } } for (; index < array .size(); index++) { int num = rand(); if (num > array [k-1 ]) { insertNum(array , num); } } finish = clock(); totaltime = runTime(start, finish); cout <<"\n算法1的运行时间为" <<totaltime<<"毫秒!" <<endl ; array .resize(N); start = clock(); for (int i = 0 ; i < N; i++) { array [i] = rand(); } for (int i = 0 ; i < array .size() - 1 ; i++) { for (int j = i+1 ; j < array .size(); j++) { if (array [i] < array [j]) { swap(array [i], array [j]); } } } finish = clock(); totaltime = runTime(start, finish); cout <<"\n算法2的运行时间为" <<totaltime<<"毫秒!" <<endl ; return 0 ; }