快速排序
快速排序
快速排序(从小到大排序)其实思想就是,将比基准点小的移动到基准点前面,比基准点大的移动到基准点后面,并且基准点能在排序中找到确定的位置,并起到分割的作用。前面和后面两个相对有序的区间继续做快速排序。
写法一
对排序的数组进行左右扫描,根据基准点的值进行前后相换。
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;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)