java 快速排序 算法

来源:互联网 发布:阿里云百度收录 编辑:程序博客网 时间:2024/06/03 07:03
public class MyQuickSort {    /** * 亲测绝对正确 * * */    public static void main(String[] args) {        int[] ints = { 4, 9, 3, 10, 2, 0, 8, 1 };        int low = 0;        int high = ints.length - 1;        System.out.println("排序前:");        for (int i : ints) {            System.out.print(i+",");        }        System.out.println();        System.out.println("排序后:");        MyQuickSort sort = new MyQuickSort();        sort.fastSort(ints, low, high);        for (int i : ints) {            System.out.print(i+",");        }    }    /* 快速排序 */    private void fastSort(int[] ints, int low, int high) {        int middle = 0;        if (low < high) {            // 1,找到第一次比较之后的中间位置            middle = doSort(ints, low, high);            // 2,第一次比较后,middle将数组分成两部分,左边都是比ints[middle]小的,右边都是比ints[middle]大的,            // 3,middle左边部分进行排序            fastSort(ints, low, middle - 1);            // 4,middle右边部分进行排序            fastSort(ints, middle + 1, high);        }    }    private int doSort(int[] ints, int low, int high) {        // 一般从一个数组的第一个数开始比较        int data = ints[low];        while (low < high) {            // data跟数组最后开始往前比,如果data<ints[high],high往前挪一位;            while (data < ints[high] && low < high) {                high--;            }            // 交换            swap(ints, low, high);            // data跟数组最前开始往后比,如果data>ints[low],low往后挪一位;            while (data > ints[low] && low < high) {                low++;            }            // 交换            swap(ints, low, high);        }        // low=high的时候返回low,即为data在数组中的最终位置        return low;    }    private void swap(int[] ints, int low, int high) {        if (low == high) {            return;        }        int temp = ints[low];        ints[low] = ints[high];        ints[high] = temp;    }}
0 0
原创粉丝点击