排序算法之快速排序

排序算法之快速排序

算法描述:

通过一趟排序使待排记录分割成两个独立的两部分,其中左侧的部分都小于基准值,二右侧的部分都大于基准值,接着再分别对两部分进行快速排序(当low=high),以达到整个序列有序

算法描述,挑选第一个元素基准值,

①先从队尾开始向前扫描且当low < high时,如果a[high] > tmp,则high–,但如果a[high] < tmp,则将high的值赋值给low,即arr[low] = a[high],同时要转换数组扫描的方式,即需要从队首开始向队尾进行扫描了
②同理,当从队首开始向队尾进行扫描时,如果a[low] < tmp,则low++,但如果a[low] > tmp了,则就需要将low位置的值赋值给high位置,即arr[low] = arr[high],同时将数组扫描方式换为由队尾向队首进行扫描.
③不断重复①和②,知道low>=high时(其实是low=high),low或high的位置就是该基准数据在数组中的正确索引位置

代码实现;


public class QuickSort {
    public static void main(String[] args) {
        int[] a={19,98,19,96,12,2,3,2,45,96,71};
        System.out.println("未排序之前的序列");
        for(int s:a){
            System.out.println(s);
        }
        quick(a,0,a.length-1);
        System.out.println("排序之后的序列");
        for(int s:a){
            System.out.println(s);
        }
    }

    private static void quick(int[] a, int low ,int high) {
        if(low<high){
            int index=sorrt(a,low,high);
            quick(a,low,index-1);
            quick(a,index+1,high);
        }
        
    }

    private static int sorrt(int[] a, int low, int high) {
        int temp=a[low];
        int i=low ;
        int j=high;
        while(i<j){
            while(a[j]>=temp&&j>i){
                j--;
            }
            a[i]=a[j];
            while(a[i]<=temp&&i<j){
                i++;
            }
            a[j]=a[i];

        }
        a[i]=temp;
        return i;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值