Quick sort based on the idea of partition

1, the main idea
  • According to a baseline, usually the first number, the larger than this number on the right side, smaller than the number on the left. Such a sequence is divided into two by the reference number.
  • Then the two sequences are selected about a reference number perform the same logic above, the split continued until only divided into a sequence element or elements is the zero order.
2, code implementation
package com.hncj.daily;

import java.util.Arrays;

public class QuickSort {
    public static void main(String[] args) {
        int[] arr = new int[]{1, 2, 3, 8, 8, 7, 13, 11, 22, 19};
        divide(arr, 0, arr.length - 1);
        Arrays.stream(arr).forEach(item -> System.out.println(item));
    }

    /**
     * 将一个无序序列划分为两个无序序列
     * @param arr
     * @param start
     * @param end
     * @return
     */
    public static int partition(int[] arr, int start, int end) {
        //以第一个数为基准
        int base = arr[start];
        while (start != end) {
            //从右往左找找到第一个比基准小的放在arr[start]的位置
            while (start < end && arr[end] >= base) {
                end--;
            }
            arr[start] = arr[end];
            //从左往右找到第一个比基准大的放在arr[end]的位置
            while (start < end && arr[start] <= base) {
                start++;
            }
            arr[end] = arr[start];
        }
        //此时start=end,start便是基准的位置,基准左边的数都比基准小,基准右边的数都比基准大
        arr[start] = base;
        return start;
    }

    /**
     * 分治的思想进行快速排序
     * @param arr
     * @param start
     * @param end
     */
    public static void divide(int[] arr, int start, int end) {
        //序列中至少有两个元素才进行划分,一个或零个元素即为有序
        if (start < end) {
            //根据一个基准将序列划分为两个无序序列
            int index = partition(arr, start, end);
            //再将左边的序列继续划分
            divide(arr, start, index - 1);
            //将右边的序列划分
            divide(arr, index + 1, end);
        }
    }
}
3. Reflections
  • Can be summed up fast row of formulas

    Put a small left large right place

  • Why should a scan from right to left and then from left to right scan once, rather than one-way scanning?

    In order to have the opportunity to place large numbers to the right of the decimal opportunity to be placed on the left, if it has been a one-way scanning, it will lead to the loss of value to be covered during placement.

Guess you like

Origin www.cnblogs.com/wotoufahaiduo/p/11682043.html