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
| #include<iostream> using namespace std;
int Partition(int r[], int first, int end); void Quicksort(int r[], int first, int end); double Get_mid(int r[], int n);
int Partition(int r[], int first, int end) { int i = first, j = end; while (i < j) { while (i < j && r[i] <= r[j])j--; if (i < j) { int temp = r[i]; r[i] = r[j]; r[j] = temp; i++; } while (i < j && r[i] <= r[j])i++; if (i < j) { int temp = r[i]; r[i] = r[j]; r[j] = temp; j--; } } return i;
}
void Quicksort(int r[], int first, int end) { int pivot; if (first < end) { pivot = Partition(r, first, end); Quicksort(r, first, pivot - 1); Quicksort(r, pivot + 1, end); } }
double Get_mid(int r[], int n) { if (n % 2 == 0) return(r[n / 2] + r[n / 2 + 1]) / 2.0; else return(double)r[n / 2 + 1]; }
int main() { int r[100]; int n; float result; cout << "请输入序列元素个数" << endl; cin >> n; cout << "请输入序列:" << endl; for (int i = 1;i <= n;i++) { cin >> r[i]; } Quicksort(r, 1, n); cout << "次序列的中位数为:" << endl; cout << Get_mid(r, n) << endl; return 0; }
|