博客
关于我
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/

你可能感兴趣的文章
Postgresql常用命令行操作_以及Navicat操作PostGis时的问题_自动截取长度_WKB structure does not match exp---PostgreSQL工作笔记005
查看>>
PostgreSQL忘记密码
查看>>
PostgreSQL数据库pg_dump命令行不输入密码的方法
查看>>
PostgreSQL新手入门
查看>>
postgresql树状结构查询示例
查看>>
PostgreSQL流复制参数max_wal_senders详解
查看>>
postgresql流复制配置
查看>>
PostgreSQL清空表并保留表结构、清空数据库还原数据库为新建时的状态的方法
查看>>
PostgreSQL的 initdb 源代码分析之九
查看>>
PostgreSQL的安装与使用指南
查看>>
postgresql编译安装及配置
查看>>
Postgresql运维常用命令_登录_权限设置_创建用户_创建数据库_创建postgis数据库_远程连接---Postgresql工作笔记009
查看>>
PostgreSQL远程连接配置
查看>>
PostgreSQL远程连接,发生致命错误:没有用于主机“…”,用户“…”,数据库“…”,SSL关闭的pg_hba.conf记录
查看>>
PostgreSQL配置文件--AUTOVACUUM参数
查看>>
PostgreSQL配置文件--QUERY TUNING
查看>>
PostgreSQL配置文件--WAL
查看>>
PostgreSQL配置文件--其他
查看>>
PostgreSQL配置文件--复制
查看>>
PostgreSQL配置文件--实时统计
查看>>