05_排序_快速排序

【原理】

整个过程其实只需三步:

1.在一列数组中,选择其中一个数据作为“基准”。

2.所有小于“基准”的数据,都移到“基准”的左边,所有大于“基准”的数据,都移到“基准”的右边。

3.对于“基准”左边和右边的两个子集,不断重复第一步和第二步。直到所有的数据子集只剩下一个数据为止。

 

【用例】

现有一组数据如下:

[ 8 , 2 , 6 , 4 , 1 , 3 , 9 , 5 ]

第一步:(假如选4为基准),

[ 8 , 2 , 6 , 4 , 1 , 3 , 9 , 5 ]

第二步:将每个数据与4对比,"<=4"左边,“>4”放右边。

[ 2 , 1 , 3 ]  4  [ 8 , 6 , 9 , 5 ]

第三步:两个子数组,重复第一步选“选基准”和第二步“放置数据”。4的位置后面都不会动的。

[ 2 , 1 , 3 ]  4  [ 8 , 6 , 9 , 5 ]

1 [ 2 , 3 ]  4  [ 5 ] 6 [ 8 , 9 ]

最后:

[ 1 , 2 , 3 , 4 , 5 , 6 , 8 , 9 ]

 

【代码实现】

 

package com.sort;

public class TestQuickSort {

    public static void sort(int[] array,int low,int high){
        if(low>high){  //一定要有这句
            return;
        }
        int i=low,j=high;
        int index=array[i];  //index为"基准"
        while(i<j){
            while(i<j&&array[j]>=index){ //寻找到array[j]<index,即发现小于基准值的数字,才退出,此时寻找到的数字的下标为j
                j--;
            }
            if(i<j){
                array[i]=array[j]; //将找到的那个小于基准值的数字覆盖了array[i],原先的array[i]存储在基准值index中
                i++;  //i下标右移
            }
            while(i<j&&array[i]<index){  //寻找>=基准值的数字array[i],退出循环
                i++;
            }
            if(i<j){    ////将找到的那个大于或等于基准值的数字覆盖了array[j],此时array[i]会有重复了
                array[j]=array[i];
                j--;
            }
        }  //这个一次循环结束:1.所有小于index的数字会都在index左边,所有大于或等于index的数字会在右边 
        array[i]=index;  //array[i]位置固定好了,刚好覆盖重复的那个值
        sort(array,low,i-1);  //递归左边的小于index但未排序的数据
        sort(array,i+1,high); //递归右边的大于index但未排序的数据
        
    }
    public static void quickSort(int[] array){
        sort(array,0,array.length-1);
    }
    public static void main(String[] args){
        int a[]={2,9,0,8,7,1,5,4,3,6};
        quickSort(a);
        for(int i=0;i<a.length;i++){
            System.out.print(a[i]+" ");
        }
    }
}

 

posted @ 2016-07-28 01:15  HigginCui  阅读(187)  评论(0编辑  收藏  举报