快速排序算法

 

快速排序的原理是:先取数组中的一个数,一般取第一个x,然后从1开始遍历到n,取到比x大的i,接着从n-1遍历到2,取比x小的j,交换两者,最后把x和最后遍历的j交换位置。

public class Test {

    int a[] = {12,73,25,78,35,45};
    
    public static void main(String[] args){
        Test t = new Test();
        t._qSort(0,t.a.length-1);
        for (int i : t.a) {
            System.out.printf(i+" ");
        }
    }
    
    public void _qSort(int left,int right){
        if(left<right){
            int q = partition(left,right);
            _qSort(left,q-1);//对前半段进行排序
            _qSort(q+1,right);//对后半段进行排序
        }
    }

    public int partition(int left, int right) {
        int i = left;
        int j = right + 1;
        int x = a[i];
        while(true){
            while(compare(a[++i],x)&&i<right);//若比x小,继续遍历,直到比x大
                while(compare(x,a[--j]));//遍历找到比x小的,这样就可以交换i和j
            if(i>=j)break;//在交换之前,判断数组下标
            swap(i,j);//交换i和j
        }
        //交换x和a[j]的位置,因为,最后一个a[j]比x小,a[i]比x大
        a[left] = a[j];
        a[j] = x;
        return j;
    }
    //交换算法
    public void swap(int i, int j) {
        // TODO Auto-generated method stub
        int temp;
        temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
    //比较算法
    public boolean compare(int x,int y){
        if(x<y){
            return true;
        }
        return false;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值