您的位置:首页 > 其它

HDU 1157 Who's in the Middle (快速排序)

2015-08-17 15:43 239 查看
Problem Description

FJ is surveying his herd to find the most average cow. He wants to know how much milk this 'median' cow gives: half of the cows give as much or more than the median; half give as much or less.

Given an odd number of cows N (1 <= N < 10,000) and their milk output (1..1,000,000), find the median amount of milk given such that at least half the cows give the same amount of milk or more and at least half give the same or less.

Input

* Line 1: A single integer N

* Lines 2..N+1: Each line contains a single integer that is the milk output of one cow.

Output

* Line 1: A single integer that is the median milk output.

Sample Input

5

2

4

1

3

5

Sample Output

3

#include<stdio.h>
void sort(int *a,int l,int r)
{
int x=a[l];  //首先记下一个基准数
int i=l,j=r;
if(l>=r) return ;
while(i<j)
{
while(i<j&&a[j]>=x) // 从右向左找第一个小于x的数
j--;
a[i]=a[j];
while(i<j&&a[i]<=x)  // 从左向右找第一个大于等于x的数
 i++;
a[j]=a[i];
}
a[i]=x;
sort(a,l,i-1);  //递归调用对左半段排序
sort(a,i+1,r);  //递归调用对右半段排序
}
int main()
{
int i,n,a[10001];
while(~scanf("%d",&n))
{
for(i=0;i<n;i++)
scanf("%d",&a[i]);
sort(a,0,n-1);
printf("%d\n",a[n/2]);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: