博客
关于我
java快速排序算法
阅读量:409 次
发布时间:2019-03-05

本文共 1254 字,大约阅读时间需要 4 分钟。

package paixu;import org.junit.Test;import java.util.Arrays;public class KuaiSu {    public int getMiddle(int[] arr, int low, int high) {        int temp = arr[low]; // 选取中轴值        while (low < high) {            // 如果high指向的元素大于中轴值,则将high移动到中轴值前面            while (low < high && arr[high] > temp) {                high--;            }            // 将low指向的元素与high指向的元素交换位置            arr[low] = arr[high];            // 如果low指向的元素小于等于中轴值,则将low移动到中轴值后面            while (low < high && arr[low] <= temp) {                low++;            }            arr[high] = arr[low];        }        // 将中轴值放到正确的位置        arr[low] = temp;        return low; // 返回中轴的位置    }    public void quickSort(int[] arr, int low, int high) {        if (low < high) {            int middle = getMiddle(arr, low, high);            quickSort(arr, low, middle - 1);            quickSort(arr, middle + 1, high);        }    }    @Test    public void test01() {        int[] arr = {5, 8, 6, 4, 7, 2, 1, 5};        if (arr.length > 0) {            quickSort(arr, 0, arr.length - 1);        }        System.out.println(Arrays.toString(arr));    }}

以上代码是对QuickSort算法的实现,主要包含两个方法:getMiddlequickSortgetMiddle方法用于获取数组的中间索引,quickSort则是快速排序的核心方法。通过递归调用quickSort方法,将数组划分为左右两部分,直到整个数组排序完成。

转载地址:http://tyqwz.baihongyu.com/

你可能感兴趣的文章
postfix+ dovecot搭建邮件服务器
查看>>
postfix在邮件服务器中的使用
查看>>
PostGIS 3.1.2软件安装详细教程(地图工具篇.8)
查看>>
PostGIS中获取所有EPSG的编码以及对应Proj4字符串
查看>>
SpringBoot中集成海康威视SDK实现布防报警数据上传/交通违章图片上传并在linux上部署(附示例代码资源)
查看>>
PostGIS在Windows上的下载与安装
查看>>
Qt开发——网络编程之UDP客户端
查看>>
postgis数据库优化_postgresql 性能优化
查看>>
postgis求面积、交集等相关函数
查看>>
postgis相关函数
查看>>
Postgres Docker版本安装mysql_fdw 插件
查看>>
Postgres invalid command \N数据恢复处理
查看>>
Postgres like 模糊查询匹配集合
查看>>
Postgres 自定义函数内实现 in 操作符的递归查询
查看>>
Postgres 返回当前时间前后指定天数的集合
查看>>
postgres--vacuum
查看>>
postgres--wal
查看>>