博客
关于我
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算法的实现,主要包含两个方法:getMiddle和quickSort。getMiddle方法用于获取数组的中间索引,quickSort则是快速排序的核心方法。通过递归调用quickSort方法,将数组划分为左右两部分,直到整个数组排序完成。

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

你可能感兴趣的文章
Python——基础知识细节
查看>>
Python——正则表达式
查看>>
Python—面向对象2
查看>>
Python“和“带整数的运算符
查看>>
Python“文件存在“制作目录时出错
查看>>
Python“文件存在“制作目录时出错
查看>>
Python、IMAP 和 GMail.将消息标记为已查看
查看>>
python一个一个获取迭代器的元素
查看>>
python一维数组 提取_python – 如何从numpy中的1维数组中提取零维切片
查看>>
python三大库之--numpy(一)
查看>>
python三大库之--numpy(二)
查看>>
python上的字无效字符_标识中的无效字符
查看>>
python下用decode和encode 中文转码
查看>>
Python下调用Linux的Shell命令
查看>>
Python接口自动化测试实战系列
查看>>
python下载_安装_配置_以及第一行python程序---python工作笔记009
查看>>
Python不协调机器人消息.内容
查看>>
Python与C#之间内存共享互传信息
查看>>
python与c语言混合编程_你试过C语言和Python一起混合编程吗?两者相加不是已经无敌了!...
查看>>
python与excel
查看>>