快速排序

来源:互联网 发布:php 私有属性 编辑:程序博客网 时间:2024/06/10 12:30

快排算是用的很多的一种排序了,其的思想是,有一个准线temp(一般默认第一个),从左右两边同时开始,左边找到比temp大于等于的第一个元素,右边找到比temp小于等于的第一个元素,两两交换。直到两个下标元素相碰为止,然后开始递归。将两个子数组递归下去就ok。

public class QuickSort {    public static void main(String[] args) {        int[] a = { 6, 1, 2, 7, 9, 3, 4, 5, 10, 8 };        quickSort(0, a.length - 1, a);        for (int i = 0; i < a.length; i++) {            System.out.print(a[i] + ",");        }    }    public static int getTemp(int left, int right, int[] a) {        // left和right分别定义当前数组的最左边的数字的key 和 最右边的数字的key        if (left > right)            return 0;        int temp = a[left]; // 数字最左边的数字作为基准数        while (left < right) {            while (left < right && a[right] >= temp) {                right--;            }            a[left] = a[right]; // 比基准数小的移动到左边            while (left < right && a[left] <= temp) {                left++;            }            a[right] = a[left]; // 比基准数大的移动到右边        }        a[left] = temp;        return left; // 返回当前基准数的位置    }    public static void quickSort(int left, int right, int[] a) {        if (left < right) {            int temp = getTemp(left, right, a);            quickSort(left, temp - 1, a);            quickSort(temp + 1, right, a);        }    }}