USTC在线评测1359题 http://acm.ustc.edu.cn/ustcoj/problem.php?id=1359
该题要求读入n个整数,然后输出该n个整数的中位数。同时输入的数的个数是奇数的时候,中位数是唯一的;当输入的数是个数是是偶数的时候,求两个中位数的平均值,然后下取整输出。
一般来说,我们可以将这些数存在数组当中,然后对数组进行排序,最后利用数组下标查找即可。但也可以不排序找到中位数。毕竟排序是将所有数都放在合适的位置上,而查找中位数的操作只需要将中位数放在合适的位置即可。
下面就是不排序查找中位数的版本。事实上,下述解法其实是快速排序的一个变种。在n为奇数的情况下,下述代码运行时间较快排实现运行时间段,因为它每次将数组分成两部分之后只处理了其中一部分。
#include <stdio.h>
#include <stdlib.h>
int select_kth( int* data, int n, int k)
{
if (n < 1)
printf("Error!\n");
int big, small;
big = n-1, small = 0;
int v = data[k];//选取data[k]是因为假如data是基本有序的,这样能减少不必要的交换
int i = 0;
while (i <= big)
{
if (data[i] < v)
{
if (i != small)
data[small] = data[i];
i++;
small+