zoukankan      html  css  js  c++  java
  • 快速排序

    1.快速排序法简介

       在数组中选一个基准数;

       将数组中小于基准数的数据移到基准数左边,大于基准数的移到右边;

       对于基准数左、右两边的数组,不断重复以上两个过程,直到每个子集只有一个元素,即为全部有序。

    2.快速排序法图解
    在这里插入图片描述

    3.代码

    public class QuickSort {
        public static void main(String[] args) {
            int[] arr = {-9, 78, 0, 23, -456, 70, -1, 900, 4561, 21};
            quickSort(arr, 0, arr.length - 1);
            System.out.println(Arrays.toString(arr));
        }
    
        public static void quickSort(int[] arr, int left, int right) {
            int leftIndex = left;//待排序数组左下标
            int rightIndex = right;//待排序数组右下标
            int pivot = arr[(leftIndex + rightIndex) / 2];//数组的中间值
            int temp = 0;//用于交换
            //将所有比pivot大的值放到pivot右边,小的放到pivot左边
            while (leftIndex < rightIndex) {
                //在pivot的左边找到一个大于等于pivot大的数时退出
                while (arr[leftIndex] < pivot) {
                    leftIndex += 1;
                }
                while (arr[rightIndex] > pivot) {
                    rightIndex -= 1;
                }
                //leftIndex>=rightIndex:此时pivot左右两边已找完,退出while循环
                if (leftIndex >= rightIndex) {
                    break;
                }
    
                //交换
                temp = arr[leftIndex];
                arr[leftIndex] = arr[rightIndex];
                arr[rightIndex] = temp;
    
                //如果交换完后,arr[leftIndex] == pivot,则rightIndex--
                if (arr[leftIndex] == pivot) {
                    rightIndex--;
                }
                //如果交换完后,arr[rightIndex] == pivot,leftIndex++
                if (arr[rightIndex] == pivot) {
                    leftIndex++;
                }
            }
            //如果leftIndex == rightIndex;必须leftIndex++,rightIndex--,否则栈会溢出
            if (leftIndex == rightIndex) {
                rightIndex--;
                leftIndex++;
            }
            //左递归
            if (left < rightIndex) {
                quickSort(arr, left, rightIndex);
            }
            //右递归
            if (right > rightIndex) {
                quickSort(arr, leftIndex, right);
            }
        }
    }
  • 相关阅读:
    codevs1288 埃及分数
    codevs1792 分解质因数
    dp
    JAVA大数贪心
    求最长不重叠子串
    初识后缀数组
    dp
    两数相除,判断小数位是否有限位
    构造二分图匹配
    建立多个树状数组
  • 原文地址:https://www.cnblogs.com/isalo/p/13095237.html
Copyright © 2011-2022 走看看