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.
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.
* 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.
二、题解
这道题就是求输入数据排序后的中位数,所以最重要的就是排序了。排序方法有很多种,我这里用了快速排序。它的基本思想是:通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。
三、java代码
二、题解
这道题就是求输入数据排序后的中位数,所以最重要的就是排序了。排序方法有很多种,我这里用了快速排序。它的基本思想是:通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。
三、java代码
import java.util.Scanner; public class Main { public static void QuickSort(int[] a){ QSort(a,0,a.length-1); } public static void QSort(int[] a,int p,int r){ if(p<r) { int q=Partition(a,p,r); QSort(a,p,q-1); QSort(a,q+1,r); } } public static int Partition(int[] a,int p,int r){ int x=a[r]; int i=p-1; for(int j=p;j<r;j++) { if(a[j]<=x){ i=i+1; swap(a, i, j); } } swap(a, i+1, r); return i+1; } public static void swap(int[] a, int i,int j){ int temp; temp=a[j]; a[j]=a[i]; a[i]=temp; } public static void main(String[] args) { Scanner cin = new Scanner(System.in); int n=cin.nextInt(); int[] a=new int[n]; for(int i=0;i<n;i++){ a[i]=cin.nextInt(); } QuickSort(a); System.out.println(a[n/2]); } }
版权声明:本文为博主原创文章,未经博主允许不得转载。