快速排序

来源:互联网 发布:域名注册通 吾爱破解 编辑:程序博客网 时间:2024/06/18 04:18

基本思想

快排主要就是一个分治法的应用, 先设数组最左侧的元素值ral,先 确定其在整个数组的最终位置,然后将其分为两个子数组,再根据递归思想以此反复。

确定ral最终位置的方法:

先将数组最左侧的元素值设为ral,最左侧元素位置为low最右侧位置为high先判断high的值是否比ral值小, 如果小则将high的值复制给low,high的值不变(否则heigh向左移如果还是比ral大则继续移动),值后判断low值是否比ral值大,如果大则将low的值赋值给high(否则low继续向右移动)

代码

public class KuaiPai {    public static void main(String[] args) {        int[] a = {-111, -23, 0, -5, 4, 2};        /*         * 第一个参数 数组a         * 第二个参数 low(数组第一个元素的下标)         * 第三个参数 high(数组最后元素的下标)         */        QuickSort(a, 0, 5);        for (int i = 0; i < a.length; i++) {            System.out.println(a[i]);        }    }    private static void QuickSort(int[] a, int low, int high) {        int pos;        if (low < high) {            pos = FindPos(a, low, high);            QuickSort(a, low, pos - 1);            QuickSort(a, pos + 1, high);        }    }//确定low的最终位置    private static int FindPos(int[] a, int low, int high) {        int val = a[low];        while (low < high ) {            //如果h > val 则 h 向左移动            while (low < high && a[high] >= val) {                --high;            }            //否则将h的值赋给l 且h的值不变            a[low] = a[high];            //如果l < val 则 l 向右移动            while (low < high && a[low] <= val) {                ++low;            }            //否则将l的值赋给h 且l 的值不变            a[high] = a[low];        }        a[low] = val;        return low;    }}
0 0