//(前两种时间复杂度为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);
}
快排的3种方式
听风客12024-07-16 11:38
相关推荐
故事和你915 小时前
洛谷-数据结构1-1-线性表1脱氧核糖核酸__5 小时前
LeetCode热题100——53.最大子数组和(题解+答案+要点)脱氧核糖核酸__6 小时前
LeetCode 热题100——42.接雨水(题目+题解+答案)一 乐6 小时前
电影院|基于springboot + vue电影院购票管理系统(源码+数据库+文档)恼书:-(空寄6 小时前
JVM GC 日志分析 + 常见 GC 场景 + 实战参数调优消失的旧时光-19437 小时前
Spring Boot 实战(五):接口工程化升级(统一返回 + 异常处理 + 错误码体系 + 异常流转机制)王老师青少年编程7 小时前
csp信奥赛C++高频考点专项训练之贪心算法 --【线性扫描贪心】:数列分段 Section I王老师青少年编程7 小时前
csp信奥赛C++高频考点专项训练之贪心算法 --【线性扫描贪心】:分糖果_日拱一卒7 小时前
LeetCode:2两数相加py有趣7 小时前
力扣热门100题之零钱兑换