Quick sort of classical algorithm in Java (Quick Sort)

Quick sort of classical algorithm in Java (Quick Sort)

Quick sort of thought

The basic idea is: a trip by ordering the data to be sorted into two independent parts, the part where all the data than the other part of all data to be small,
then this method of data quickly sort the two parts separately, the entire sorting process can be recursively in order to achieve the entire data becomes an ordered sequence.

It assumed that the array A: 46 30 82 90 56 17 95 15, taking the number of the first base 46, l = 0 (l letters, not a number 1) directed to the first number, h = 7 refers to the last number:

从右向左找出第一个小于46的数;先比较A[0]和A[7]:
    46 30  82  90  56  17  95  15
    =》46和15比较=》15  30  82  90  56  17  95  46:交换位置,此时l需要+1变为l=1;h=7
(如果之前比较没有找到小于46的数,则继续取h=6位置的数和46比较,直到取到小于46的数为止)

然后从左向右找出第一个大于46的数:比较A[1]和A[7]:
    15  30  82  90  56  17  95  46
    =》30和46比较=》15  30  82  90  56  17  95  46:未交换位置,继续取左边下一个数字,

继续从左向右找出第一个大于46的数,此时所以l=2;h=7;比较A[2]和A[7]:
    15  30  82  90  56  17  95  46
    =》82和46比较=》15  30 46 90  56  17  95  82:交换位置

此时需要从右向左再找出下一个比46小的数,所以l=2,h=6,比较A[2]和A[6]:
    15  30 46 90  56  17  95  82
    =》46和95比较=》15  30 46 90  56  17  95  82:未交换位置

继续从左向右找比46小的数字,此时l=2,h=5,比较A[2]和A[5]:
    15  30 46 90  56  17  95  46
    =》46和17比较=》15  30  17  90  56 46 95  82:交换位置

再从左向右找比46大的数字,此时l=3,h=5;比较A[3]和A[5]:
    15  30  17  90  56 46 95  82
    =》90和46比较=》15  30  17 46 56  90  95  82:交换位置

再从右向左找比46小的数字,此时l=3,h=4; 比较A[3]和A[4]:
    15  30  17 46 56  90  95  82
    =》46和56比较=》15  30  17 42 56  90  95  82:为交换位置

继续从右向左找比46小的数字,此时l=3,h=3,l==h;此时A[3]左边数字(15,30,17,)全部是小于右边数字(90,95,82)的;

然后对子序列各自进行如上排序,直到子序列元素个数不大于1为止;
  public static void main(String[] args) {
        int[] a = {46, 30, 82, 90, 56, 17, 95, 15};
        int start = 0;
        int end = a.length - 1;
        sort(a, start, end);
        for (int anA : a) {
            System.out.println(anA);
        }
    }

    public static void sort(int arr[], int low, int high) {
        int l = low;
        int h = high;
        int baseNum = arr[low];

        while (l < h) {
            //1.从右向左查找小于指定基数的数,找到之后跳出循环执行下面if循环,交换数据
            while (l < h && arr[h] >= baseNum) {
                h--;
            }
            //交换数据
            if (l < h) {
                int temp = arr[h];
                arr[h] = arr[l];
                arr[l] = temp;
                l++;
            }

            //2.从左向右查找大于指定基数的数,找到后跳出循环执行下面if循环,交换数据
            while (l < h && arr[l] <= baseNum)
                l++;
            //交换数据
            if (l < h) {
                int temp = arr[h];
                arr[h] = arr[l];
                arr[l] = temp;
                h--;
            }
        }
        if (l > low) {
            sort(arr, low, l - 1);
        }
        if (h < high) {
            sort(arr, l + 1, high);
        }
    }

Guess you like

Origin www.cnblogs.com/shen-hua/p/11304495.html