十大排序之快速排序

// 快速排序
public class QuickSort {
    public static void main(String[] args) {
        int[] arr = {-9,78,0,23,-567,-70};
//        int[] arr = {1,4,3,2};
        //       测试时间复杂度 O(n^2)
/*
        int [] arr = new int[80000];
        for (int i = 0; i < arr.length; i++) {
            // 生成 [0,8000000)的随机数
            arr[i] = (int) (Math.random()*8000000);
        }
*/
        long start_Time = System.currentTimeMillis();
        quickSort(arr,0,arr.length-1);
        long stop_Time = System.currentTimeMillis();
        // 毫秒之间
        System.out.printf("耗费 %d ms",stop_Time - start_Time);
        System.out.println(Arrays.toString(arr));
    }
    public static void quickSort(int[] arr, int left, int right) {
        int leftIndex = left;
        int rightIndex = right;
        int temp =0;
        // 中心点
        int pivot = arr[(left + right) / 2];
        /**
         *  while 循环的目的是比pivot 值小的放到左边
         *  比pivot 值大的 放到右边
         */
        while (leftIndex < rightIndex){
            // 在 pivot 的左边一直找 ,找到大于等于pivot 值,才退出
            while (arr[leftIndex] < pivot){
                 leftIndex +=1;
            }

            // 在 pivot 的右边一直找 ,找到小于等于pivot 值,才退出
            while (arr[rightIndex] > pivot){
                rightIndex -=1;
            }

            /**
             * 如果 leftIndex >= rightIndex  说明 pivot 的左右的值 ,已经按照左边的全部
             * 是小于pivot 值,右边全部是大于等于pivot的值 退出循环
              */
            if(leftIndex == rightIndex){
                break;
            }
            // 如果不等于退出条件就是找到了相应的值 进行交换
            temp = arr[leftIndex];
            arr [leftIndex] = arr[rightIndex];
            arr [rightIndex] = temp;

            /**
             * 交换完成后 有三种情况
             * 1、左边的leftIndex 已经移动到中间点 但是 右边的rightIndex还没有移动到中间点 所以右边的需要后退一步 继续判断循环
             * 2、右边的rightIndex 已经移动到中间点 但是 左边的leftIndex还没有移动到中间点,需要前移 继续循环
             * 3、就是两边都没有移动到中间点 继续循环判断
             *  这里的判断可以不写 这里判断的目的是减少循环的次数
             */
            if(arr[leftIndex] == pivot){
                rightIndex -=1;
            }

            if(arr[rightIndex] == pivot){
                leftIndex +=1;

            }

        }
        // 这里既是防止死循环(栈溢出)的同时也是划分左递归 和 右递归 开始和结束的区域
        if(leftIndex == rightIndex){
            leftIndex +=1;
            rightIndex -=1;
        }
        // 左递归 对左边的区域进行排序
        if(left < rightIndex){
            quickSort(arr,left, rightIndex);
        }
        //右递归 对右边的区域进行排序
        if (right > leftIndex){
            quickSort(arr,leftIndex ,right);
        }

    }
}

发布了39 篇原创文章 · 获赞 13 · 访问量 2293

猜你喜欢

转载自blog.csdn.net/qq_43205282/article/details/105399291