快速排序

  快速排序 是C.R.A.Hoare于1962年提出的一种划分交换排序。它采用了一种分治的策略,通常称其为分治法(Divide-and-ConquerMethod)。

  基本思想: 

  • 1.先从数列中取出一个数作为基准数
  • 2.分区过程,将比这个数大的数全放到它的右边,小于或等于它的数全放到它的左边。
  • 3.再对左右区间重复第二步,直到各区间只有一个数。  

  快速排序的本质就是把比基准数大的都放在基准数的右边,把比基准数小的放在基准数的左边(类似二叉搜索树),这样就找到了该数据在数组中的正确位置。

  然后采用递归的方式分别对前半部分和后半部分排序,当前半部分和后半部分均有序时该数组就自然有序了。

public class QuickSort {
    public static void main(String[] args) {
        int[] arr = { 49, 38, 65, 97, 23, 22, 76, 1, 5, 8, 2, 0, -1, 22 };
        quickSort(arr, 0, arr.length - 1);
        System.out.println("排序后:");
        for (int i : arr) {
            System.out.println(i);
        }
    }

    void quickSort(int[] arr, int low, int high) {
        if (low < high) {
            // 得到基准数的索引
            int index = getIndex(arr, low, high);
            // 进行迭代对基准数之前和之后的数组进行相同的操作使整个数组变成有序
            quickSort(arr, low, index - 1);
            quickSort(arr, index + 1, high);
        }

    }

    int getIndex(int[] arr, int low, int high) {
        // 基准数选择
        int tmp = arr[low];
        while (low < high) {
            // 当队尾的元素大于等于基准数时,向前挪动high指针
            while (low < high && arr[high] >= tmp) {
                high--;
            }
            // 如果队尾元素小于tmp了,需要将其赋值给low,即替换到左半区
            arr[low] = arr[high];
            // 当队首元素小于等于tmp时,向前挪动low指针
            while (low < high && arr[low] <= tmp) {
                low++;
            }
            // 当队首元素大于tmp时,需要将其赋值给high,即替换到右半区
            arr[high] = arr[low];
        }
        // 此时low和high相等,就是基准数tmp的正确索引位置
        // low位置的值不是tmp,将tmp赋值给arr[low]
        arr[low] = tmp;
        return low; // 返回基准数的位置
    }
}

 

posted @ 2021-03-18 11:13  zjcfrancis  阅读(72)  评论(0编辑  收藏  举报