二10、快速排序算法——JAVA实现(递归)

1、快速排序原理:
   首先找到一个基准,通常以第一个元素做为基准(pivot),而后先从右向左搜索, 若是发现比pivot小,则和pivot交换,而后从左向右搜索,若是发现比pivot大,则和pivot交换,以此循环,一轮循环完后,pivot左边的都比它小,而右边的都比它大, 此时pivot的位置就是排好序后的最终位置,此时pivot将数组划分为左右两部分,每部分继续上面的排序操做(推荐递归方式)。

2、代码实现:
   排序前数组为:[1, 3, 2, 8, 5, 10, 22, 11, 2, 18]
   排序后数组为:[1, 2, 2, 3, 5, 8, 10, 11, 18, 22]数组

/**
 * 快速排序
 *
 * @author wxf
 * @date 2019/1/14 9:22
 **/
public class FastSort {

    public static void main(String[] args) {
        int[] a = {1, 3, 2, 8, 5, 10, 22, 11, 2, 18};
        quickSort(a, 0, a.length - 1);
        System.out.println(Arrays.toString(a));
    }

    /**
     * 快速排序
     *
     * @param arr  数组
     * @param low  基准数位置
     * @param high 数组长度
     */
    private static void quickSort(int[] arr, int low, int high) {
        int start = low;
        //arr[low]为基准数
        int key = arr[low];
        int end = high;
        while (start < end) {
            //右->左查找,找到比基准数小的值则交换位置
            while (arr[end] >= key && end > start) {
                end--;
            }
//            if (arr[end] < key) {
//                int temp = arr[end];
//                arr[end] = key;
//                arr[low] = temp;
//            }
            arr[start] = arr[end];
            //左->右查找,找到比基准数大的值则交换位置
            while (arr[start] <= key && end > start) {
                start++;
            }
//            if (arr[start] > key) {
//                int temp = arr[start];
//                arr[start] = key;
//                arr[end] = temp;
//            }
            arr[end] = arr[start];
        }
        arr[start] = key;
        //递归
        if (start > low) {
            quickSort(arr, low, start - 1);
        }
        if (end < high) {
            quickSort(arr, start + 1, high);
        }
    }
}
复制代码
相关文章
相关标签/搜索