快排的3种方式

复制代码
//(前两种时间复杂度为o(n^2) , 最后一种为o(n*logn)

public static void swap(int[] arr , int i , int j){
    arr[i] =arr[i] ^arr[j];
    arr[j] =arr[i] ^arr[j];
    arr[i] =arr[i] ^arr[j];
}
//使数组中以arr[R]划分,返回循环后arr[R]的所在地
public static int partition(int[] arr , int L ,int R ){
    if(L >R ){
        return -1;
    }
    if(L == R ){
        return L;
    }
    int lessEqual = L-1;
    int index = L;
    while (index <R ){
        if(arr[index] <=arr[R]){
            swap(arr ,index++ , ++lessEqual);
        }
    }
    swap(arr , ++lessEqual , R);
    return lessEqual;
}

//把一个数组以arr[R]划分,返回的是值为arr[R]的区间
public static int[] netherlandsFlag(int[] arr , int L , int R){
    if(L>R){
        return new int[] { -1 ,-1};
    }
    if(L ==R){
        return new int[] {L ,R};
    }
    int less = L-1;
    int more =R;
    int index = L;
    while (index <more){
        if(arr[index] ==arr[R]){
            index++;
        }else if(arr[index] <arr[R]){
            swap(arr ,index++ , ++less);
        }else{
            swap(arr ,index , --more);
        }
    }
    swap(arr ,more ,R );
    return new int[] {less+1 , more};
}
//递归1
public static void process1(int[] arr ,int L ,int R ){
    if(L >=R){
        return;
    }
    int M =partition(arr ,L ,R);
    process1(arr , L , M-1);
    process1(arr , M+1 ,R);
}
//快排1
public static void quickSort1(int[] arr){
    if(arr ==null || arr.length <2){
        return;
    }
    process1(arr ,0 , arr.length-1);
}

//递归2
public static void process2(int[] arr ,int L ,int R){
    if(L >=R){
        return;
    }
    int[] equalArea =netherlandsFlag(arr ,L ,R);
    process2(arr ,L ,equalArea[0] -1);
    process2(arr , equalArea[1] , R);
}
//快排2
public static void quickSort2(int[] arr){
    if(arr ==null || arr.length <2){
        return;
    }
    process2(arr ,0 , arr.length-1);
}

//递归3
public static void process3(int[] arr , int L ,int R){
    if(L > R ){
        return;
    }
    swap(arr ,L + (int) (Math.random() * (R - L+1)), R);
    int[] equalArea = netherlandsFlag(arr , L ,R);
    process3(arr , L , equalArea[0] -1);
    process3(arr , equalArea[1] +1, R );
}
//快排3
public static void quickSort3(int[] arr){
    if(arr == null ||arr.length <2){
        return;
    }
    process3(arr , 0  , arr.length-1);
}
相关推荐
特立独行的猫A21 分钟前
别再用 nohup 了:让应用在后台常驻的正确姿势与 systemd 服务详解
java·后端·python
一起_java43 分钟前
技术文章-基于Dify-Agent的智能问答系统设计与实现
java·spring boot·后端·agent·dify
Flynn Liang2 小时前
I/O 密集型高并发实战:Java 服务 10 维优化,从线程打满到 10 万 QPS
java·spring boot·性能优化·高并发·系统设计·虚拟线程·io密集型
吃我一窝jio3 小时前
Python与Go线程模型深度对比
java·开发语言·python
这个昵称不容易3 小时前
SpringBoot 购物推荐网站的设计与实现:120 个 Java 文件、147 个接口、13 张表,附真实运行截图
java·springboot·毕设
文丑颜不良啊3 小时前
LeetCode3041~3060题目解析
java·leetcode
罗西的思考4 小时前
【轻量化复现大模型 / KIMI K3】MTP / EAGLE‑3 模块交互式演示
人工智能·深度学习·算法
文丑颜不良啊5 小时前
LeetCode3101~3120题目解析
java·leetcode
Resean02235 小时前
SpringMVC 6+源码分析(十一)视图渲染与异步请求(收尾篇)
java·spring·springmvc
靠沿6 小时前
MySQL数据库进阶——存储过程和触发器
java·数据库·mysql