快速排序

快速排序

快速排序(从小到大排序)其实思想就是,将比基准点小的移动到基准点前面,比基准点大的移动到基准点后面,并且基准点能在排序中找到确定的位置,并起到分割的作用。前面和后面两个相对有序的区间继续做快速排序。

写法一

对排序的数组进行左右扫描,根据基准点的值进行前后相换。

在这里插入图片描述

public static void sort(int[] arr,int start,int end){
		
        if (end-start <= 0) return;
    	//进行快速排序,并返回基准点
        int index = patition(arr,start,end);
		//通过基准点分割出左右两块区间,向下递归
        sort(arr,start,index-1);
        sort(arr,index+1,end);
    }
    public static int patition(int[]arr ,int start,int end){
        //第一个作基准点
        int curr = arr[start];
        //左右扫描
        while (start<end){
        	//寻找比基准点小的数值,然后交换(为了将小于基准点的数放到前面)
            while (start<end && arr[end]>curr) end--;
            arr[start] = arr[end];
            //寻找比基准点大的数值,然后交换(为了将大于基准点的数放到前面)
            while (start<end && arr[start]<curr) start++;
            arr[end] = arr[start];
        }
        //最后基准点放到对应位置
        arr[start] = curr;
        return start;
    }

写法二

第二种写法是:从左到右扫描,根据基准点移动节点。

在这里插入图片描述

public static void sort(int[] arr,int start,int end){
        if (end-start <= 0) return;
        //进行快速排序,并返回基准点
        int index = patition(arr,start,end);
		//通过基准点分割出左右两块区间,向下递归
        sort(arr,start,index-1);
        sort(arr,index+1,end);
    }

    public static int patition(int[]arr ,int start,int end){
        //以最后一个为基准点
        int pos = arr[end];
        //前移标志
        int index = start-1;
        while (start<=end) {
            //比基准点小的可以前移
            if (arr[start] <= pos) {
                index++;   //前移位置向前+1
                //判断是否可以前移
                //如果start>index证明已经出现过比基准点大的数了,start和index位置交换即可,小的向前交换,大的向后
                if (start>index){
                    int tem = arr[start];
                    arr[start] = arr[index];
                    arr[index] = tem;
                }
            }
            start++;   //移动
        }

        return index;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值