4.12快速分类

package test;

import java.util.Scanner;

public class T12Partition {
    public static int[] a;
    public int partition(int m,int p){
        int v=a[m];
        System.out.println("基准元素为:"+v);
        int i=m+1;
        while(i<=p){
            while(i<=p&&a[i]<v){
                i++;
            }
            while(i<=p&&a[p]>v){
                p--;
            }
            if(i<p){
                int temp=a[i];
                a[i]=a[p];
                a[p]=temp;
            }else{
                break;
            }
        }
        System.out.println(a[p]+"即将回到"+m+"位置");
        System.out.println(v+"即将回到"+p+"位置");
        a[m]=a[p];
        a[p]=v;
        return p;
    }
    public void quicksort(int p,int q){
        if(p<q){
            int j=partition(p,q);
            System.out.println("左边:"+p+" "+(j-1));
            quicksort(p,j-1);
            for(int i=0;i<9;i++){
                System.out.print(a[i]+" ");
            }
            System.out.println();
            System.out.println("右边:"+(j+1)+" "+q);
            quicksort(j+1,q);
            for(int i=0;i<9;i++){
                System.out.print(a[i]+" ");
            }
            System.out.println();
        }
    }
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.print("输入数组长度n:");
        int n=sc.nextInt(); 
        a=new int[n];
        System.out.println("输入数组元素:");
        for(int i=0;i<n;i++){
            a[i]=sc.nextInt();
        }
        new T12Partition().quicksort(0,n-1);
    }
}

输入数组长度n:9

输入数组元素:
65 70 75 80 85 60 55 50 45
]基准元素为:65
60即将回到0位置
65即将回到4位置
左边:0 3
基准元素为:60
55即将回到0位置
60即将回到3位置
左边:0 2
基准元素为:55
50即将回到0位置
55即将回到2位置
左边:0 1
基准元素为:50
45即将回到0位置
50即将回到1位置
左边:0 0
45 50 55 60 65 85 80 75 70
右边:2 1
45 50 55 60 65 85 80 75 70
45 50 55 60 65 85 80 75 70
右边:3 2
45 50 55 60 65 85 80 75 70
45 50 55 60 65 85 80 75 70
右边:4 3
45 50 55 60 65 85 80 75 70
45 50 55 60 65 85 80 75 70
右边:5 8
基准元素为:85
70即将回到5位置
85即将回到8位置
左边:5 7
基准元素为:70
70即将回到5位置
70即将回到5位置
左边:5 4
45 50 55 60 65 70 80 75 85
右边:6 7
基准元素为:80
75即将回到6位置
80即将回到7位置
左边:6 6
45 50 55 60 65 70 75 80 85
右边:8 7
45 50 55 60 65 70 75 80 85
45 50 55 60 65 70 75 80 85
45 50 55 60 65 70 75 80 85
右边:9 8
45 50 55 60 65 70 75 80 85
45 50 55 60 65 70 75 80 85

posted on 2016-04-21 23:09  step_step  阅读(151)  评论(0编辑  收藏  举报

导航