快速排序

import java.util.Scanner;

public class Main{
    public static void main(String []args){
        Scanner sc=new Scanner(System.in);
        while(sc.hasNext()){
            int n=sc.nextInt();
            int []a=new int[n+1];
            for(int i=1;i<=n;i++){
                a[i]=sc.nextInt();
            }
            QuikSort(a,1,n);
            for(int i=1;i<=n;i++){
                System.out.println(a[i]);
            }
        }
    }
    public static void QuikSort(int []a,int p,int r){
        if(p<r){
            int q=Partition(a,p,r);
            QuikSort(a,p,q-1);
            QuikSort(a,q+1,r);
        }
    }
    public static int Partition(int []a,int p,int r){
        int key=a[p];
        int i=p;
        int j=r;
        while(i<j){
            while(i<j&&a[j]>=key)
                j--;
            if(i<j)a[i++]=a[j];
            while(i<j&&a[i]<key)
                i++;
            if(i<j)a[j--]=a[i];
        }
        a[i]=key;
        return i;
    }
}

 

posted @ 2017-09-15 14:35  ybleeho  阅读(141)  评论(0编辑  收藏  举报