zoukankan      html  css  js  c++  java
  • poj 2388 Who's in the Middle(快速排序求中位数)

    一、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.
    二、题解
            这道题就是求输入数据排序后的中位数,所以最重要的就是排序了。排序方法有很多种,我这里用了快速排序。它的基本思想是:通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。
    三、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]);
        } 
      } 
    


    版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 相关阅读:
    Android客户端消息推送原理简介
    优秀程序员的十个习惯
    能让你成为更优秀程序员的10个C语言资源
    成大事必备9种能力、9种手段、9种心态
    33个优秀的HTML5应用演示 (转)
    Maven学习:Eclipse使用maven构建web项目(转)
    使用fiddler模拟http get
    TLS握手
    风暴英雄 http 302重定向 正在等待游戏模式下载完成
    page template in kentico
  • 原文地址:https://www.cnblogs.com/AndyDai/p/4734179.html
Copyright © 2011-2022 走看看