Java achieve fast row

Java achieve fast row

Quicksort uses divide and conquer (Divide and conquer) a strategy to sequence the (list) 2 into smaller and larger subsequences, then sort recursively two sequences.

The core idea of ​​the fast discharge is: to be sorted sequence (assuming index from start to end) select any one of data as a pivot (split point, also called reference point), and through the data, will be less than the data pivot placed pivot of before, data greater than or equal to pivot on the back of the pivot. After the two sub-recursive ordered sequence.

Process is as follows.

Fast row 1.PNG

Here we give the sort of place is achieved, that is, the extra space is not required during the execution of the algorithm.

public class Quick {
    // 快速排序,a是数组,n表示数组的大小
    public static void quickSort(int[] a, int n) {
        quickSortInternally(a, 0, n - 1);
    }

    // 快速排序递归函数
    private static void quickSortInternally(int[] a, int start, int end) {
        if (start >= end) {
            return;
        }

        int q = partition(a, start, end); // 获取分区点
        quickSortInternally(a, start, q - 1);
        quickSortInternally(a, q + 1, end);
    }
}

The above is a recursive implementation, it can be seen with the merge sort code is somewhat similar, where the main point is to get the partition.

private static int partition(int[] a, int start, int end) {
    int pivot = a[end];
    int i = start;
    for (int j = start; j < end; ++j) {
        if (a[j] < pivot) {
            if (i == j) {
                ++i;
            } else {
                swap(a, i, j);
                ++i;
            }
        }
    }
    swap(a, i, end);
    return i;
}

public static void swap(int[] a, int i, int j) {
    int tmp = a[i];
    a[i] = a[j];
    a[j] = tmp;
}

Here we select the partition point is the last node needs to arrange the array. Here are the steps will get the first partition point, you can look at.

Fast row .gif

I can be seen that always points to the first node array is greater than the value of the partition point, j is iterate to find the node value is less than the split point, and then exchanging the position of the node pointed to i, then i ++, j such that when traversing the after again array i are smaller than the partition value of the left point, right of i is greater than equal partition point i and the final position of the partition point switch. This first pass traversal is complete.

Fast row is a place, an unstable algorithm, his time complexity is O (nlogn), compared to merge sort, fast row has the advantage of space, but his time complexity is not as stable as merge sort, when required nearly ordered array arrangement, we still select the last point, then as the partition element, the fast discharge time complexity becomes O (n- 2 ), and

Guess you like

Origin www.cnblogs.com/youch/p/10951363.html