快速排序

2017-07-27  本文已影响0人  Green_Apple

思路:通过找一个标志位,以标志位为大小分成两个区间 左小右大
再以每个区间分别递归进行左右区间大小区分,来进行排序
public class QuickSort {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    int value[]={2,1,7,5,3,8,4};
    getResult(value, 0, value.length-1);
    for(int i=0;i<value.length;i++){
        System.out.println(value[i]);
    }
}

public static int position(int [] value,int start,int end){
    int flag=value[start];//随便选取一个分割点 选取第一个元素              留出转换的空间 value[start]
    
    //end和start 相当于两个指针 一头一尾
    
    while(start<end){  
        while(start<end&&value[end]>flag) end--; //后指针数大于标志数则往前推
        value[start]=value[end];//当小于表指数时,则拿到标志数的左边,此时原本标志数的位置是最合适的位置 也就是转换空间   此时转换空间变成了value[end]
        while(start<end&&value[start]<flag) start++; //前指针数小于标志数则往后移
        value[end]=value[start];//大于时则和转换空间交换   转换空间又变成了value[start]
        
        //如此交换后,可确保在start-end的区间内的数以标志数左右大小分开
    }
    value[start]=flag;//将标志数放入中间位置
    
    return start;//返回中间位置的坐标
}

public static void getResult(int value[],int start,int end){
    int index;
    if(start<end){
        index=position(value,start,end);//得到切分的区间 标志位
        getResult(value,start,index-1);//左递归
        getResult(value,index+1,end);//右递归
    }
    
}

}

上一篇 下一篇

猜你喜欢

热点阅读