Java quick sort method

Keywords: Java

Principle of quick sorting:

Select a key value as the base value. Those smaller than the benchmark value are all on the left (generally unordered), and those larger than the benchmark value are all on the right (generally unordered). Generally select the first element of the sequence.

Compare from the back to the front, and use the benchmark value to compare with the last value. If the exchange position is smaller than the benchmark value, if the next value is not compared, the exchange will not be started until the first value smaller than the benchmark value is found. After finding this value, compare from the front to the back. If there is a value larger than the reference value, exchange the position. If you do not continue to compare the next value, do not exchange until you find the first value larger than the reference value. Until compare index from front to back > compare index from back to front, end the first cycle, at this time, for the benchmark value, the left and right sides are orderly.

Then compare the left and right sequences respectively and repeat the above cycle.

Code instance:

public class FastSort {

    public static void main(String[] args) {
        System.out.println("Quick sort test");
        int[] a = { 121,  16,12,222,3333,212, 15, 1, 30,23, 9,33,56,66,543,65,665 };
        int start = 0;
        int end = a.length - 1;
        sort(a, start, end);
        for (int i = 0; i < a.length; i++) {


    public static void sort(int[] a, int low, int high) {
        int start = low;
        int end = high;
        int key = a[low];

        while (end > start) {
            // Compare back to front
            while (end > start && a[end] >= key)
                // If there is no one smaller than the key value, compare to the next until there is a swap location smaller than the key value
//And then compare before and after
end--; if (a[end] <= key) { int temp = a[end]; a[end] = a[start]; a[start] = temp; } // Compare before and after while (end > start && a[start] <= key) // If there is no larger than the key value, compare to the next until there is a swap location larger than the key value start++; if (a[start] >= key) { int temp = a[start]; a[start] = a[end]; a[end] = temp; } // At the end of the first cycle comparison, the position of the key value has been determined.
// The values on the left are smaller than the key values, and the values on the right are larger than the key values
// But the order of the two sides may be different. Make the following recursive call
} // recursion if (start > low) sort(a, low, start - 1);// Left sequence. First index location to key index-1 if (end < high) sort(a, end + 1, high);// Right sequence. Index from key+1 To the last } }

Posted by deejay on Sun, 03 May 2020 18:30:19 -0700