intRank(int a, int* arr, int n){ int i = 1, rank = 0; for (int j = 2; j <= n; j++) { while (arr[j] - arr[i] > a)//对于每一个j, 求得距离 i++; rank += (j - i);//这些距离之和就是名次 } return rank; }
intmain(){ int n; while (scanf_s("%d", &n) != EOF) { int* cat = newint[n + 10]; for (int i = 1; i <= n; i++) scanf_s("%d", &cat[i]);//后面一直出问题 就索性从1开始记位 sort(cat + 1, cat + n + 1);
int N = n * (n - 1) / 2;//新数组的元素个数 intbegin = 1, end = cat[n]; int aim = (N + 1) / 2;//目标中位数的位置,根据题意取的+1 int middle = 0; while (begin <= end) {//二分求中位数 middle = (begin + end) / 2; if (begin == end) break; int theRank = Rank(middle, cat, n);//当前名次 if (theRank >= aim)//in the left end = middle; if (theRank < aim)//in the right begin = middle + 1; } printf("%d\n", middle); } return0; }